source
stringlengths
3
92
c
stringlengths
26
2.25M
stat_ops_expectation_value.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "stat_ops.h" #include "utility.h" #include "constant.h" double expectation_value_X_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_Y_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_Z_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count,UINT pivot_qubit_index, const CTYPE* state, ITYPE dim); double expectation_value_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state, ITYPE dim); // calculate expectation value of X on target qubit double expectation_value_X_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index); ITYPE basis_1 = basis_0 ^ mask; sum += creal( conj(state[basis_0]) * state[basis_1] ) * 2; } return sum; } // calculate expectation value of Y on target qubit double expectation_value_Y_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE mask = 1ULL << target_qubit_index; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index,mask,target_qubit_index); ITYPE basis_1 = basis_0 ^ mask; sum += cimag( conj(state[basis_0]) * state[basis_1] ) * 2; } return sum; } // calculate expectation value of Z on target qubit double expectation_value_Z_Pauli_operator(UINT target_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim; ITYPE state_index; double sum =0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ int sign = 1 - 2 * ((state_index >> target_qubit_index)%2); sum += creal( conj(state[state_index]) * state[state_index] ) * sign; } return sum; } // calculate expectation value for single-qubit pauli operator double expectation_value_single_qubit_Pauli_operator(UINT target_qubit_index, UINT Pauli_operator_type, const CTYPE *state, ITYPE dim) { if(Pauli_operator_type == 0){ return state_norm_squared(state,dim); }else if(Pauli_operator_type == 1){ return expectation_value_X_Pauli_operator(target_qubit_index, state, dim); }else if(Pauli_operator_type == 2){ return expectation_value_Y_Pauli_operator(target_qubit_index, state, dim); }else if(Pauli_operator_type == 3){ return expectation_value_Z_Pauli_operator(target_qubit_index, state, dim); }else{ fprintf(stderr,"invalid expectation value of pauli operator is called"); exit(1); } } // calculate expectation value of multi-qubit Pauli operator on qubits. // bit-flip mask : the n-bit binary string of which the i-th element is 1 iff the i-th pauli operator is X or Y // phase-flip mask : the n-bit binary string of which the i-th element is 1 iff the i-th pauli operator is Y or Z // We assume bit-flip mask is nonzero, namely, there is at least one X or Y operator. // the pivot qubit is any qubit index which has X or Y // To generate bit-flip mask and phase-flip mask, see get_masks_*_list at utility.h double expectation_value_multi_qubit_Pauli_operator_XZ_mask(ITYPE bit_flip_mask, ITYPE phase_flip_mask, UINT global_phase_90rot_count,UINT pivot_qubit_index, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim/2; const ITYPE pivot_mask = 1ULL << pivot_qubit_index; ITYPE state_index; double sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ ITYPE basis_0 = insert_zero_to_basis_index(state_index, pivot_mask, pivot_qubit_index); ITYPE basis_1 = basis_0 ^ bit_flip_mask; UINT sign_0 = count_population(basis_0 & phase_flip_mask)%2; sum += creal(state[basis_0] * conj(state[basis_1]) * PHASE_90ROT[ (global_phase_90rot_count + sign_0*2)%4 ] * 2.0); } return sum; } double expectation_value_multi_qubit_Pauli_operator_Z_mask(ITYPE phase_flip_mask, const CTYPE* state, ITYPE dim){ const ITYPE loop_dim = dim; ITYPE state_index; double sum = 0.; #ifdef _OPENMP #pragma omp parallel for reduction(+:sum) #endif for(state_index=0;state_index<loop_dim;++state_index){ int bit_parity = count_population(state_index & phase_flip_mask)%2; int sign = 1 - 2*bit_parity; sum += pow(cabs(state[state_index]),2) * sign; } return sum; } double expectation_value_multi_qubit_Pauli_operator_partial_list(const UINT* target_qubit_index_list, const UINT* Pauli_operator_type_list, UINT target_qubit_index_count, const CTYPE* state, ITYPE dim){ ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_partial_list(target_qubit_index_list, Pauli_operator_type_list, target_qubit_index_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); double result; if(bit_flip_mask == 0){ result = expectation_value_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state,dim); }else{ result = expectation_value_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state, dim); } return result; } double expectation_value_multi_qubit_Pauli_operator_whole_list(const UINT* Pauli_operator_type_list, UINT qubit_count, const CTYPE* state, ITYPE dim){ ITYPE bit_flip_mask = 0; ITYPE phase_flip_mask = 0; UINT global_phase_90rot_count = 0; UINT pivot_qubit_index = 0; get_Pauli_masks_whole_list(Pauli_operator_type_list, qubit_count, &bit_flip_mask, &phase_flip_mask, &global_phase_90rot_count, &pivot_qubit_index); double result; if(bit_flip_mask == 0){ result = expectation_value_multi_qubit_Pauli_operator_Z_mask(phase_flip_mask, state, dim); }else{ result = expectation_value_multi_qubit_Pauli_operator_XZ_mask(bit_flip_mask, phase_flip_mask, global_phase_90rot_count, pivot_qubit_index, state, dim); } return result; }
batch_norm.h
// Copyright 2018 Xiaomi, 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. #ifndef MACE_KERNELS_BATCH_NORM_H_ #define MACE_KERNELS_BATCH_NORM_H_ #if defined(MACE_ENABLE_NEON) && defined(__aarch64__) #include <arm_neon.h> #endif #include <memory> #include <vector> #include "mace/core/future.h" #include "mace/core/tensor.h" #include "mace/kernels/activation.h" #include "mace/public/mace.h" namespace mace { namespace kernels { template<DeviceType D, typename T> struct BatchNormFunctor; template<> struct BatchNormFunctor<DeviceType::CPU, float> : OpKernel { BatchNormFunctor(OpKernelContext *context, const bool folded_constant, const ActivationType activation, const float relux_max_limit) : OpKernel(context), folded_constant_(folded_constant), activation_(activation), relux_max_limit_(relux_max_limit) {} MaceStatus operator()(const Tensor *input, const Tensor *scale, const Tensor *offset, const Tensor *mean, const Tensor *var, const float epsilon, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); // Batch normalization in the paper https://arxiv.org/abs/1502.03167 . // The calculation formula for inference is // Y = \frac{ \scale } { \sqrt{var+\variance_epsilon} } * X + // ( \offset - \frac { \scale * mean } { // \sqrt{var+\variance_epsilon} } // new_scale = \frac{ \scale } { \sqrt{var+\variance_epsilon} } // new_offset = \offset - mean * common_val; // Y = new_scale * X + new_offset; const index_t batch = input->dim(0); const index_t channels = input->dim(1); const index_t height = input->dim(2); const index_t width = input->dim(3); Tensor::MappingGuard input_mapper(input); Tensor::MappingGuard scale_mapper(scale); Tensor::MappingGuard offset_mapper(offset); Tensor::MappingGuard output_mapper(output); const float *input_ptr = input->data<float>(); const float *scale_ptr = scale->data<float>(); const float *offset_ptr = offset->data<float>(); float *output_ptr = output->mutable_data<float>(); std::vector<float> new_scale; std::vector<float> new_offset; if (!folded_constant_) { new_scale.resize(channels); new_offset.resize(channels); Tensor::MappingGuard mean_mapper(mean); Tensor::MappingGuard var_mapper(var); const float *mean_ptr = mean->data<float>(); const float *var_ptr = var->data<float>(); #pragma omp parallel for for (index_t c = 0; c < channels; ++c) { new_scale[c] = scale_ptr[c] / std::sqrt(var_ptr[c] + epsilon); new_offset[c] = offset_ptr[c] - mean_ptr[c] * new_scale[c]; } } const float *scale_data = folded_constant_ ? scale_ptr : new_scale.data(); const float *offset_data = folded_constant_ ? offset_ptr : new_offset.data(); index_t channel_size = height * width; index_t batch_size = channels * channel_size; // NEON is slower, so stick to the trivial implementaion #pragma omp parallel for collapse(2) for (index_t b = 0; b < batch; ++b) { for (index_t c = 0; c < channels; ++c) { index_t offset = b * batch_size + c * channel_size; for (index_t hw = 0; hw < height * width; ++hw) { output_ptr[offset + hw] = scale_data[c] * input_ptr[offset + hw] + offset_data[c]; } } } DoActivation(output_ptr, output_ptr, output->size(), activation_, relux_max_limit_); return MACE_SUCCESS; } const bool folded_constant_; const ActivationType activation_; const float relux_max_limit_; }; #ifdef MACE_ENABLE_OPENCL class OpenCLBatchNormKernel { public: virtual MaceStatus Compute( OpKernelContext *context, const Tensor *input, const Tensor *scale, const Tensor *offset, const Tensor *mean, const Tensor *var, const float epsilon, Tensor *output, StatsFuture *future) = 0; MACE_VIRTUAL_EMPTY_DESTRUCTOR(OpenCLBatchNormKernel); }; template<typename T> struct BatchNormFunctor<DeviceType::GPU, T> : OpKernel { BatchNormFunctor(OpKernelContext *context, const bool folded_constant, const ActivationType activation, const float relux_max_limit); MaceStatus operator()(const Tensor *input, const Tensor *scale, const Tensor *offset, const Tensor *mean, const Tensor *var, const float epsilon, Tensor *output, StatsFuture *future); std::unique_ptr<OpenCLBatchNormKernel> kernel_; }; #endif // MACE_ENABLE_OPENCL } // namespace kernels } // namespace mace #endif // MACE_KERNELS_BATCH_NORM_H_
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // 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 // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/APINotes/APINotesManager.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <functional> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; /// A key method to reduce duplicate debug info from Sema. virtual void anchor(); ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; api_notes::APINotesManager APINotes; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SmallPtrSet<Expr *, 2>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } /// \brief Callback to the parser to parse a type expressed as a string. std::function<TypeResult(StringRef, StringRef, SourceLocation)> ParseTypeFromStringCallback; class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal swift_name /// attribute for the decl \p D. Raise a diagnostic if the name is invalid /// for the given declaration. /// /// For a function, this will validate a compound Swift name, /// e.g. <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, /// and the function will output the number of parameter names, and whether /// this is a single-arg initializer. /// /// For a type, enum constant, property, or variable declaration, this will /// validate either a simple identifier, or a qualified /// <code>context.identifier</code> name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation ArgLoc, const IdentifierInfo *AttrName); private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as a non-type, and an expression representing /// that name has been formed. NC_ContextIndependentExpr, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification ContextIndependentExpr(ExprResult E) { NameClassification Result(NC_ContextIndependentExpr); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_ContextIndependentExpr); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); void diagnosePointerAuthDisabled(SourceLocation loc, SourceRange range); bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); QualType adjustParameterTypeForObjCAutoRefCount(QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Uuid); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name, bool Override); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Map any API notes provided for this declaration to attributes on the /// declaration. /// /// Triggered by declaration-attribute processing. void ProcessAPINotes(Decl *D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Check whether a nullability type specifier can be added to the given /// type through some means not written in source (e.g. API notes). /// /// \param type The type to which the nullability specifier will be /// added. On success, this type will be updated appropriately. /// /// \param nullability The nullability specifier to add. /// /// \param diagLoc The location to use for diagnostics. /// /// \param allowArrayTypes Whether to accept nullability specifiers on an /// array type (e.g., because it will decay to a pointer). /// /// \param overrideExisting Whether to override an existing, locally-specified /// nullability specifier rather than complaining about the conflict. /// /// \returns true if nullability cannot be applied, false otherwise. bool checkImplicitNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation diagLoc, bool allowArrayTypes, bool overrideExisting); /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, and false is returned. bool CheckConstraintExpression(Expr *CE); private: /// \brief Caches pairs of template-like decls whose associated constraints /// were checked for subsumption and whether or not the first's constraints /// did in fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; public: /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction(TemplateDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); bool CheckConstraintSatisfaction(ClassTemplatePartialSpecializationDecl *TD, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); bool CheckConstraintSatisfaction(VarTemplatePartialSpecializationDecl *TD, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check that the associated constraints of a template declaration match the /// associated constraints of an older declaration of which it is a /// redeclaration. bool CheckRedeclarationConstraintMatch(TemplateParameterList *Old, TemplateParameterList *New); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction& Satisfaction); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction& Satisfaction); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied because it was ill-formed. void DiagnoseUnsatisfiedIllFormedConstraint(SourceLocation DiagnosticLocation, StringRef Diagnostic); void DiagnoseRedeclarationConstraintMismatch(const TemplateParameterList *Old, const TemplateParameterList *New); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, SourceLocation TemplateKWLoc = SourceLocation(), AssumedTemplateKind *ATK = nullptr); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(Decl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, SourceLocation ConceptNameLoc, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); // Concepts Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); VarDecl *getVarTemplateSpecialization( VarTemplateDecl *VarTempl, const TemplateArgumentListInfo *TemplateArgs, const DeclarationNameInfo &MemberNameInfo, SourceLocation TemplateKWLoc); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; /// Check whether the declared result type of the given Objective-C /// method declaration is compatible with the method's class. ResultTypeCompatibilityKind checkRelatedResultTypeCompatibility(const ObjCMethodDecl *Method, const ObjCInterfaceDecl *CurrentClass); void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckForDelayedContext = true); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee, bool CheckCaller = true); /// Check if the expression is allowed to be used in expressions for the /// OpenMP devices. void checkOpenMPDeviceExpr(const Expr *E); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Marks all the functions that might be required for the currently active /// OpenMP context. void markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse); public: /// Struct to store the context selectors info for declare variant directive. using OMPCtxStringType = SmallString<8>; using OMPCtxSelectorData = OpenMPCtxSelectorData<SmallVector<OMPCtxStringType, 4>, ExprResult>; /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction( DeclGroupPtrTy DG, Expr *VariantRef, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param Data Set of context-specific data for the specified context /// selector. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, SourceRange SR, ArrayRef<OMPCtxSelectorData> Data); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation DepLinMapLastLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause( ArrayRef<Expr *> VarList, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, Function = 0x2, DerivedToBase = 0x4, ObjC = 0x8, ObjCLifetime = 0x10, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); DeviceDiagBuilder(DeviceDiagBuilder &&D); DeviceDiagBuilder(const DeviceDiagBuilder &) = default; ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); DeviceDiagBuilder targetDiag(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
symv_x_coo_n_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/kernel_plain.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t symv_coo_n_hi_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; const ALPHA_INT nnz = A->nnz; const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number **tmp = (ALPHA_Number **)malloc(sizeof(ALPHA_Number *) * thread_num); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (int i = 0; i < thread_num; ++i) { tmp[i] = malloc(sizeof(ALPHA_Number) * m); memset(tmp[i], 0, sizeof(ALPHA_Number) * m); } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < nnz; i++) { const ALPHA_INT threadId = alpha_get_thread_id(); const ALPHA_INT r = A->row_indx[i]; const ALPHA_INT c = A->col_indx[i]; if (r > c) { continue; } ALPHA_Number v; alpha_mul(v, alpha, A->values[i]); if (r == c) { alpha_madde(tmp[threadId][r], v, x[c]); } else { alpha_madde(tmp[threadId][r], v, x[c]); alpha_madde(tmp[threadId][c], v, x[r]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); for (ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(y[i], y[i], tmp[j][i]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (int i = 0; i < thread_num; ++i) { alpha_free(tmp[i]); } alpha_free(tmp); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_COO *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT thread_num = alpha_get_thread_num(); return symv_coo_n_hi_omp(alpha, A, x, beta, y); }
convolutiondepthwise_3x3_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2019 BUG1989. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static inline signed char float2int8(float v) { int int32 = round(v); if (int32 > 127) return 127; if (int32 < -127) return -127; return (signed char)int32; } static void convdw3x3s1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const signed char* kernel = (const signed char*)_kernel + p * 9; int* outptr0 = out; int* outptr0n = outptr0 + outw; const signed char* img0 = bottom_blob.channel(p); const signed char* r0 = img0; const signed char* r1 = img0 + w; const signed char* r2 = img0 + w * 2; const signed char* r3 = img0 + w * 3; int i = 0; #if __ARM_NEON int8x16_t _k0123456789x = vld1q_s8(kernel); int16x8_t _k_s16 = vmovl_s8(vget_low_s8(_k0123456789x)); int16x8_t _kn_s16 = vmovl_s8(vget_high_s8(_k0123456789x)); int16x4_t _k0123 = vget_low_s16(_k_s16); int16x4_t _k4567 = vget_high_s16(_k_s16); int16x4_t _k8xxx = vget_low_s16(_kn_s16); #endif // __ARM_NEON for (; i + 1 < outh; i += 2) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "ld1 {v4.8b, v5.8b}, [%3] \n" "ld1 {v6.8b, v7.8b}, [%4] \n" "ld1 {v8.8b, v9.8b}, [%5] \n" "ld1 {v10.8b, v11.8b}, [%6] \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "add %5, %5, #8 \n" "add %6, %6, #8 \n" "ext v12.8b, v4.8b, v5.8b, #1 \n" "ext v13.8b, v4.8b, v5.8b, #2 \n" "ext v14.8b, v6.8b, v7.8b, #1 \n" "ext v15.8b, v6.8b, v7.8b, #2 \n" "ext v16.8b, v8.8b, v9.8b, #1 \n" "ext v17.8b, v8.8b, v9.8b, #2 \n" "ext v18.8b, v10.8b, v11.8b, #1 \n" "ext v19.8b, v10.8b, v11.8b, #2 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v12.8h, v12.8b, #0 \n" // r01 "sshll v13.8h, v13.8b, #0 \n" // r02 "sshll v6.8h, v6.8b, #0 \n" // r10 "sshll v14.8h, v14.8b, #0 \n" // r11 "sshll v15.8h, v15.8b, #0 \n" // r12 "sshll v8.8h, v8.8b, #0 \n" // r20 "sshll v16.8h, v16.8b, #0 \n" // r21 "sshll v17.8h, v17.8b, #0 \n" // r22 "sshll v10.8h, v10.8b, #0 \n" // r30 "sshll v18.8h, v18.8b, #0 \n" // r31 "sshll v19.8h, v19.8b, #0 \n" // r32 // r0 "smull v20.4s, v4.4h, %14.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %14.h[0] \n" "smull v22.4s, v12.4h, %14.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v12.8h, %14.h[1] \n" "smull v24.4s, v13.4h, %14.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v13.8h, %14.h[2] \n" // r1 "smull v26.4s, v6.4h, %14.h[0] \n" // (r10 - r17) * k00 "smull2 v27.4s, v6.8h, %14.h[0] \n" "smull v28.4s, v14.4h, %14.h[1] \n" // (r11 - r18) * k01 "smull2 v29.4s, v14.8h, %14.h[1] \n" "smull v30.4s, v15.4h, %14.h[2] \n" // (r12 - r19) * k02 "smull2 v31.4s, v15.8h, %14.h[2] \n" "smlal v20.4s, v6.4h, %14.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v6.8h, %14.h[3] \n" "smlal v22.4s, v14.4h, %15.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v14.8h, %15.h[0] \n" "smlal v24.4s, v15.4h, %15.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v15.8h, %15.h[1] \n" // r2 "smlal v26.4s, v8.4h, %14.h[3] \n" // (r20 - r27) * k03 "smlal2 v27.4s, v8.8h, %14.h[3] \n" "smlal v28.4s, v16.4h, %15.h[0] \n" // (r21 - r28) * k04 "smlal2 v29.4s, v16.8h, %15.h[0] \n" "smlal v30.4s, v17.4h, %15.h[1] \n" // (r22 - r29) * k05 "smlal2 v31.4s, v17.8h, %15.h[1] \n" "smlal v20.4s, v8.4h, %15.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v8.8h, %15.h[2] \n" "smlal v22.4s, v16.4h, %15.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v16.8h, %15.h[3] \n" "smlal v24.4s, v17.4h, %16.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v17.8h, %16.h[0] \n" // r3 "smlal v26.4s, v10.4h, %15.h[2] \n" // (r30 - r37) * k06 "smlal2 v27.4s, v10.8h, %15.h[2] \n" "smlal v28.4s, v18.4h, %15.h[3] \n" // (r31 - r38) * k07 "smlal2 v29.4s, v18.8h, %15.h[3] \n" "smlal v30.4s, v19.4h, %16.h[0] \n" // (r32 - r39) * k08 "smlal2 v31.4s, v19.8h, %16.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v26.4s, v26.4s, v28.4s \n" "add v27.4s, v27.4s, v29.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" "add v26.4s, v26.4s, v30.4s \n" "add v27.4s, v27.4s, v31.4s \n" "st1 {v20.4s, v21.4s}, [%1], #32 \n" "st1 {v26.4s, v27.4s}, [%2], #32 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr0n), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr0), "2"(outptr0n), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k8xxx) // %16 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld1.s8 {d30-d31}, [%3] \n" // r0 "add %3, %3, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q5, d10 \n" // r01 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P14[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P14[0] \n" "vmull.s16 q9, d10, %P14[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P14[1] \n" "vmlal.s16 q7, d12, %P14[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P14[2] \n" // r1 "vld1.s8 {d30-d31}, [%4] \n" // r1 "add %4, %4, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q5, d10 \n" // r11 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P14[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P14[3] \n" "vmlal.s16 q9, d10, %P15[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P15[0] \n" "vmlal.s16 q7, d12, %P15[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P15[1] \n" // sum1 "vmull.s16 q11, d30, %P14[0] \n" // (r10 - r17) * k00 "vmull.s16 q12, d31, %P14[0] \n" "vmull.s16 q13, d10, %P14[1] \n" // (r11 - r18) * k01 "vmull.s16 q14, d11, %P14[1] \n" "vmlal.s16 q11, d12, %P14[2] \n" // (r12 - r19) * k02 "vmlal.s16 q12, d13, %P14[2] \n" // r2 "vld1.s8 {d30-d31}, [%5] \n" // r2 "add %5, %5, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q5, d10 \n" // r21 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P15[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P15[2] \n" "vmlal.s16 q9, d10, %P15[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P15[3] \n" "vmlal.s16 q7, d12, %P16[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P16[0] \n" // sum1 "vmlal.s16 q11, d30, %P14[3] \n" // (r20 - r27) * k03 "vmlal.s16 q12, d31, %P14[3] \n" "vmlal.s16 q13, d10, %P15[0] \n" // (r21 - r28) * k04 "vmlal.s16 q14, d11, %P15[0] \n" "vmlal.s16 q11, d12, %P15[1] \n" // (r22 - r29) * k05 "vmlal.s16 q12, d13, %P15[1] \n" // r3 "vld1.s8 {d30-d31}, [%6] \n" // r3 "add %6, %6, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r30 "vmovl.s8 q5, d10 \n" // r31 "vmovl.s8 q6, d12 \n" // r32 // sum1 "vmlal.s16 q11, d30, %P15[2] \n" // (r30 - r37) * k06 "vmlal.s16 q12, d31, %P15[2] \n" "vmlal.s16 q13, d10, %P15[3] \n" // (r31 - r38) * k07 "vmlal.s16 q14, d11, %P15[3] \n" "vmlal.s16 q11, d12, %P16[0] \n" // (r32 - r39) * k08 "vmlal.s16 q12, d13, %P16[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vadd.s32 q11, q11, q13 \n" "vadd.s32 q12, q12, q14 \n" "vst1.s32 {d14-d17}, [%1]! \n" "vst1.s32 {d22-d25}, [%2]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr0n), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr0), "2"(outptr0n), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k8xxx) // %16 : "cc", "memory", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO NEON int sum0 = 0; int sum0n = 0; sum0 += (int)r0[0] * kernel[0]; sum0 += (int)r0[1] * kernel[1]; sum0 += (int)r0[2] * kernel[2]; sum0 += (int)r1[0] * kernel[3]; sum0 += (int)r1[1] * kernel[4]; sum0 += (int)r1[2] * kernel[5]; sum0 += (int)r2[0] * kernel[6]; sum0 += (int)r2[1] * kernel[7]; sum0 += (int)r2[2] * kernel[8]; sum0n += (int)r1[0] * kernel[0]; sum0n += (int)r1[1] * kernel[1]; sum0n += (int)r1[2] * kernel[2]; sum0n += (int)r2[0] * kernel[3]; sum0n += (int)r2[1] * kernel[4]; sum0n += (int)r2[2] * kernel[5]; sum0n += (int)r3[0] * kernel[6]; sum0n += (int)r3[1] * kernel[7]; sum0n += (int)r3[2] * kernel[8]; *outptr0 = sum0; *outptr0n = sum0n; r0++; r1++; r2++; r3++; outptr0++; outptr0n++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr0 += outw; outptr0n += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "ld1 {v4.8b, v5.8b}, [%2] \n" "ld1 {v6.8b, v7.8b}, [%3] \n" "ld1 {v8.8b, v9.8b}, [%4] \n" "add %2, %2, #8 \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "ext v12.8b, v4.8b, v5.8b, #1 \n" "ext v13.8b, v4.8b, v5.8b, #2 \n" "ext v14.8b, v6.8b, v7.8b, #1 \n" "ext v15.8b, v6.8b, v7.8b, #2 \n" "ext v16.8b, v8.8b, v9.8b, #1 \n" "ext v17.8b, v8.8b, v9.8b, #2 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v12.8h, v12.8b, #0 \n" // r01 "sshll v13.8h, v13.8b, #0 \n" // r02 "sshll v6.8h, v6.8b, #0 \n" // r10 "sshll v14.8h, v14.8b, #0 \n" // r11 "sshll v15.8h, v15.8b, #0 \n" // r12 "sshll v8.8h, v8.8b, #0 \n" // r20 "sshll v16.8h, v16.8b, #0 \n" // r21 "sshll v17.8h, v17.8b, #0 \n" // r22 // r0 "smull v20.4s, v4.4h, %10.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %10.h[0] \n" "smull v22.4s, v12.4h, %10.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v12.8h, %10.h[1] \n" "smull v24.4s, v13.4h, %10.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v13.8h, %10.h[2] \n" // r1 "smlal v20.4s, v6.4h, %10.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v6.8h, %10.h[3] \n" "smlal v22.4s, v14.4h, %11.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v14.8h, %11.h[0] \n" "smlal v24.4s, v15.4h, %11.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v15.8h, %11.h[1] \n" // r2 "smlal v20.4s, v8.4h, %11.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v8.8h, %11.h[2] \n" "smlal v22.4s, v16.4h, %11.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v16.8h, %11.h[3] \n" "smlal v24.4s, v17.4h, %12.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v17.8h, %12.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" "st1 {v20.4s, v21.4s}, [%1], #32 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr0), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx) // %12 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld1.s8 {d30-d31}, [%2] \n" // r0 "add %2, %2, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q5, d10 \n" // r01 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P10[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P10[0] \n" "vmull.s16 q9, d10, %P10[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P10[1] \n" "vmlal.s16 q7, d12, %P10[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P10[2] \n" // r1 "vld1.s8 {d30-d31}, [%3] \n" // r1 "add %3, %3, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q5, d10 \n" // r11 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P10[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P10[3] \n" "vmlal.s16 q9, d10, %P11[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P11[0] \n" "vmlal.s16 q7, d12, %P11[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P11[1] \n" // r2 "vld1.s8 {d30-d31}, [%4] \n" // r2 "add %4, %4, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q5, d10 \n" // r21 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P11[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P11[2] \n" "vmlal.s16 q9, d10, %P11[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P11[3] \n" "vmlal.s16 q7, d12, %P12[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P12[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vst1.s32 {d14-d17}, [%1]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr0), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx) // %12 : "cc", "memory", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr0 = sum; r0++; r1++; r2++; outptr0++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const signed char* kernel = (const signed char*)_kernel + p * 9; int* outptr = out; const signed char* img = bottom_blob.channel(p); const signed char* r0 = img; const signed char* r1 = img + w; const signed char* r2 = img + w * 2; int i = 0; #if __ARM_NEON int8x16_t _k0123456789x = vld1q_s8(kernel); int16x8_t _k_s16 = vmovl_s8(vget_low_s8(_k0123456789x)); int16x8_t _kn_s16 = vmovl_s8(vget_high_s8(_k0123456789x)); int16x4_t _k0123 = vget_low_s16(_k_s16); int16x4_t _k4567 = vget_high_s16(_k_s16); int16x4_t _k8xxx = vget_low_s16(_kn_s16); #endif // __ARM_NEON for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "ld2 {v4.8b, v5.8b}, [%2], #16 \n" "ld2 {v6.8b, v7.8b}, [%2] \n" "ld2 {v8.8b, v9.8b}, [%3], #16 \n" "ld2 {v10.8b, v11.8b}, [%3] \n" "ld2 {v12.8b, v13.8b}, [%4], #16 \n" "ld2 {v14.8b, v15.8b}, [%4] \n" "ext v6.8b, v4.8b, v6.8b, #1 \n" "ext v10.8b, v8.8b, v10.8b, #1 \n" "ext v14.8b, v12.8b, v14.8b, #1 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v5.8h, v5.8b, #0 \n" // r01 "sshll v6.8h, v6.8b, #0 \n" // r02 "sshll v8.8h, v8.8b, #0 \n" // r10 "sshll v9.8h, v9.8b, #0 \n" // r11 "sshll v10.8h, v10.8b, #0 \n" // r12 "sshll v12.8h, v12.8b, #0 \n" // r20 "sshll v13.8h, v13.8b, #0 \n" // r21 "sshll v14.8h, v14.8b, #0 \n" // r22 // r0 "smull v20.4s, v4.4h, %10.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %10.h[0] \n" "smull v22.4s, v5.4h, %10.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v5.8h, %10.h[1] \n" "smull v24.4s, v6.4h, %10.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v6.8h, %10.h[2] \n" // r1 "smlal v20.4s, v8.4h, %10.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v8.8h, %10.h[3] \n" "smlal v22.4s, v9.4h, %11.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v9.8h, %11.h[0] \n" "smlal v24.4s, v10.4h, %11.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v10.8h, %11.h[1] \n" // r2 "smlal v20.4s, v12.4h, %11.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v12.8h, %11.h[2] \n" "smlal v22.4s, v13.4h, %11.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v13.8h, %11.h[3] \n" "smlal v24.4s, v14.4h, %12.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v14.8h, %12.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" "st1 {v20.4s, v21.4s}, [%1], #32 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx) // %12 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld2.s8 {d30-d31}, [%2]! \n" // r0 "vld2.s8 {d10-d11}, [%2] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r01 "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P10[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P10[0] \n" "vmull.s16 q9, d10, %P10[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P10[1] \n" "vmlal.s16 q7, d12, %P10[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P10[2] \n" // r1 "vld2.s8 {d30-d31}, [%3]! \n" // r1 "vld2.s8 {d10-d11}, [%3] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r11 "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P10[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P10[3] \n" "vmlal.s16 q9, d10, %P11[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P11[0] \n" "vmlal.s16 q7, d12, %P11[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P11[1] \n" // r2 "vld2.s8 {d30-d31}, [%4]! \n" // r2 "vld2.s8 {d10-d11}, [%4] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r21 "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P11[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P11[2] \n" "vmlal.s16 q9, d10, %P11[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P11[3] \n" "vmlal.s16 q7, d12, %P12[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P12[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vst1.s32 {d14-d17}, [%1]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx) // %12 : "cc", "memory", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } static void convdw3x3s1_int8_requant_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2 * p]; const float scale_requant_out = scales_requant[2 * p + 1]; const signed char* kernel = (const signed char*)_kernel + p * 9; signed char* outptr0 = out; signed char* outptr0n = outptr0 + outw; const signed char* img0 = bottom_blob.channel(p); const signed char* r0 = img0; const signed char* r1 = img0 + w; const signed char* r2 = img0 + w * 2; const signed char* r3 = img0 + w * 3; int i = 0; #if __ARM_NEON int8x16_t _k0123456789x = vld1q_s8(kernel); int16x8_t _k_s16 = vmovl_s8(vget_low_s8(_k0123456789x)); int16x8_t _kn_s16 = vmovl_s8(vget_high_s8(_k0123456789x)); int16x4_t _k0123 = vget_low_s16(_k_s16); int16x4_t _k4567 = vget_high_s16(_k_s16); int16x4_t _k8xxx = vget_low_s16(_kn_s16); #endif // __ARM_NEON for (; i + 1 < outh; i += 2) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "0: \n" "ld1 {v4.8b, v5.8b}, [%3] \n" "ld1 {v6.8b, v7.8b}, [%4] \n" "ld1 {v8.8b, v9.8b}, [%5] \n" "ld1 {v10.8b, v11.8b}, [%6] \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "add %5, %5, #8 \n" "add %6, %6, #8 \n" "ext v12.8b, v4.8b, v5.8b, #1 \n" "ext v13.8b, v4.8b, v5.8b, #2 \n" "ext v14.8b, v6.8b, v7.8b, #1 \n" "ext v15.8b, v6.8b, v7.8b, #2 \n" "ext v16.8b, v8.8b, v9.8b, #1 \n" "ext v17.8b, v8.8b, v9.8b, #2 \n" "ext v18.8b, v10.8b, v11.8b, #1 \n" "ext v19.8b, v10.8b, v11.8b, #2 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v12.8h, v12.8b, #0 \n" // r01 "sshll v13.8h, v13.8b, #0 \n" // r02 "sshll v6.8h, v6.8b, #0 \n" // r10 "sshll v14.8h, v14.8b, #0 \n" // r11 "sshll v15.8h, v15.8b, #0 \n" // r12 "sshll v8.8h, v8.8b, #0 \n" // r20 "sshll v16.8h, v16.8b, #0 \n" // r21 "sshll v17.8h, v17.8b, #0 \n" // r22 "sshll v10.8h, v10.8b, #0 \n" // r30 "sshll v18.8h, v18.8b, #0 \n" // r31 "sshll v19.8h, v19.8b, #0 \n" // r32 // r0 "smull v20.4s, v4.4h, %14.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %14.h[0] \n" "smull v22.4s, v12.4h, %14.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v12.8h, %14.h[1] \n" "smull v24.4s, v13.4h, %14.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v13.8h, %14.h[2] \n" // r1 "smull v26.4s, v6.4h, %14.h[0] \n" // (r10 - r17) * k00 "smull2 v27.4s, v6.8h, %14.h[0] \n" "smull v28.4s, v14.4h, %14.h[1] \n" // (r11 - r18) * k01 "smull2 v29.4s, v14.8h, %14.h[1] \n" "smull v30.4s, v15.4h, %14.h[2] \n" // (r12 - r19) * k02 "smull2 v31.4s, v15.8h, %14.h[2] \n" "smlal v20.4s, v6.4h, %14.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v6.8h, %14.h[3] \n" "smlal v22.4s, v14.4h, %15.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v14.8h, %15.h[0] \n" "smlal v24.4s, v15.4h, %15.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v15.8h, %15.h[1] \n" // r2 "smlal v26.4s, v8.4h, %14.h[3] \n" // (r20 - r27) * k03 "smlal2 v27.4s, v8.8h, %14.h[3] \n" "smlal v28.4s, v16.4h, %15.h[0] \n" // (r21 - r28) * k04 "smlal2 v29.4s, v16.8h, %15.h[0] \n" "smlal v30.4s, v17.4h, %15.h[1] \n" // (r22 - r29) * k05 "smlal2 v31.4s, v17.8h, %15.h[1] \n" "smlal v20.4s, v8.4h, %15.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v8.8h, %15.h[2] \n" "smlal v22.4s, v16.4h, %15.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v16.8h, %15.h[3] \n" "smlal v24.4s, v17.4h, %16.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v17.8h, %16.h[0] \n" // r3 "smlal v26.4s, v10.4h, %15.h[2] \n" // (r30 - r37) * k06 "smlal2 v27.4s, v10.8h, %15.h[2] \n" "smlal v28.4s, v18.4h, %15.h[3] \n" // (r31 - r38) * k07 "smlal2 v29.4s, v18.8h, %15.h[3] \n" "smlal v30.4s, v19.4h, %16.h[0] \n" // (r32 - r39) * k08 "smlal2 v31.4s, v19.8h, %16.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v26.4s, v26.4s, v28.4s \n" "add v27.4s, v27.4s, v29.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" "add v26.4s, v26.4s, v30.4s \n" "add v27.4s, v27.4s, v31.4s \n" "dup v4.4s, %w17 \n" // bias "dup v5.4s, %w18 \n" // scale_in "dup v6.4s, %w19 \n" // scale_out // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" "scvtf v26.4s, v26.4s \n" "scvtf v27.4s, v27.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, v5.4s \n" "fmul v21.4s, v21.4s, v5.4s \n" "fmul v26.4s, v26.4s, v5.4s \n" "fmul v27.4s, v27.4s, v5.4s \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, v4.4s \n" "fadd v21.4s, v21.4s, v4.4s \n" "fadd v26.4s, v26.4s, v4.4s \n" "fadd v27.4s, v27.4s, v4.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, v6.4s \n" "fmul v21.4s, v21.4s, v6.4s \n" "fmul v26.4s, v26.4s, v6.4s \n" "fmul v27.4s, v27.4s, v6.4s \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" "fcvtas v26.4s, v26.4s \n" "fcvtas v27.4s, v27.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn v9.4h, v26.4s \n" "sqxtn2 v7.8h, v21.4s \n" "sqxtn2 v9.8h, v27.4s \n" // top_s16 -> top_s8 "sqxtn v8.8b, v7.8h \n" "sqxtn v10.8b, v9.8h \n" // save top_s8 "st1 {v8.8b}, [%1], #8 \n" "st1 {v10.8b}, [%2], #8 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr0n), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr0), "2"(outptr0n), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k8xxx), // %16 "r"(bias0), // %17 "r"(scale_requant_in), // %18 "r"(scale_requant_out) // %19 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld1.s8 {d30-d31}, [%3] \n" // r0 "add %3, %3, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q5, d10 \n" // r01 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P14[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P14[0] \n" "vmull.s16 q9, d10, %P14[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P14[1] \n" "vmlal.s16 q7, d12, %P14[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P14[2] \n" // r1 "vld1.s8 {d30-d31}, [%4] \n" // r1 "add %4, %4, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q5, d10 \n" // r11 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P14[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P14[3] \n" "vmlal.s16 q9, d10, %P15[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P15[0] \n" "vmlal.s16 q7, d12, %P15[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P15[1] \n" // sum1 "vmull.s16 q11, d30, %P14[0] \n" // (r10 - r17) * k00 "vmull.s16 q12, d31, %P14[0] \n" "vmull.s16 q13, d10, %P14[1] \n" // (r11 - r18) * k01 "vmull.s16 q14, d11, %P14[1] \n" "vmlal.s16 q11, d12, %P14[2] \n" // (r12 - r19) * k02 "vmlal.s16 q12, d13, %P14[2] \n" // r2 "vld1.s8 {d30-d31}, [%5] \n" // r2 "add %5, %5, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q5, d10 \n" // r21 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P15[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P15[2] \n" "vmlal.s16 q9, d10, %P15[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P15[3] \n" "vmlal.s16 q7, d12, %P16[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P16[0] \n" // sum1 "vmlal.s16 q11, d30, %P14[3] \n" // (r20 - r27) * k03 "vmlal.s16 q12, d31, %P14[3] \n" "vmlal.s16 q13, d10, %P15[0] \n" // (r21 - r28) * k04 "vmlal.s16 q14, d11, %P15[0] \n" "vmlal.s16 q11, d12, %P15[1] \n" // (r22 - r29) * k05 "vmlal.s16 q12, d13, %P15[1] \n" // r3 "vld1.s8 {d30-d31}, [%6] \n" // r3 "add %6, %6, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r30 "vmovl.s8 q5, d10 \n" // r31 "vmovl.s8 q6, d12 \n" // r32 // sum1 "vmlal.s16 q11, d30, %P15[2] \n" // (r30 - r37) * k06 "vmlal.s16 q12, d31, %P15[2] \n" "vmlal.s16 q13, d10, %P15[3] \n" // (r31 - r38) * k07 "vmlal.s16 q14, d11, %P15[3] \n" "vmlal.s16 q11, d12, %P16[0] \n" // (r32 - r39) * k08 "vmlal.s16 q12, d13, %P16[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vadd.s32 q11, q11, q13 \n" "vadd.s32 q12, q12, q14 \n" "vdup.f32 q13, %17 \n" // bias "vdup.f32 q14, %18 \n" // scale_in "vdup.f32 q15, %19 \n" // scale_out // top_s32 -> top_f32 "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q0, q7, q14 \n" "vmul.f32 q4, q8, q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q0, q0, q13 \n" "vadd.f32 q4, q4, q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q0, q15 \n" "vmul.f32 q4, q4, q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s16, s16 \n" "vcvtr.s32.f32 s17, s17 \n" "vcvtr.s32.f32 s18, s18 \n" "vcvtr.s32.f32 s19, s19 \n" // top_s32 -> top_s16 "vqmovn.s32 d14, q0 \n" "vqmovn.s32 d15, q4 \n" // top_s16 -> top_s8 "vqmovn.s16 d14, q7 \n" // save top_s8 "vst1.8 {d14}, [%1]! \n" // top_s32 -> top_f32 "vcvt.f32.s32 q11, q11 \n" "vcvt.f32.s32 q12, q12 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q0, q11, q14 \n" "vmul.f32 q4, q12, q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q0, q0, q13 \n" "vadd.f32 q4, q4, q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q0, q15 \n" "vmul.f32 q4, q4, q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s16, s16 \n" "vcvtr.s32.f32 s17, s17 \n" "vcvtr.s32.f32 s18, s18 \n" "vcvtr.s32.f32 s19, s19 \n" // top_s32 -> top_s16 "vqmovn.s32 d14, q0 \n" "vqmovn.s32 d15, q4 \n" // top_s16 -> top_s8 "vqmovn.s16 d14, q7 \n" // save top_s8 "vst1.8 {d14}, [%2]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr0n), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr0), "2"(outptr0n), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k8xxx), // %16 "r"(bias0), // %17 "r"(scale_requant_in), // %18 "r"(scale_requant_out) // %19 : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { // TODO NEON int sum0 = 0; int sum0n = 0; sum0 += (int)r0[0] * kernel[0]; sum0 += (int)r0[1] * kernel[1]; sum0 += (int)r0[2] * kernel[2]; sum0 += (int)r1[0] * kernel[3]; sum0 += (int)r1[1] * kernel[4]; sum0 += (int)r1[2] * kernel[5]; sum0 += (int)r2[0] * kernel[6]; sum0 += (int)r2[1] * kernel[7]; sum0 += (int)r2[2] * kernel[8]; sum0n += (int)r1[0] * kernel[0]; sum0n += (int)r1[1] * kernel[1]; sum0n += (int)r1[2] * kernel[2]; sum0n += (int)r2[0] * kernel[3]; sum0n += (int)r2[1] * kernel[4]; sum0n += (int)r2[2] * kernel[5]; sum0n += (int)r3[0] * kernel[6]; sum0n += (int)r3[1] * kernel[7]; sum0n += (int)r3[2] * kernel[8]; *outptr0 = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); *outptr0n = float2int8(((float)sum0n * scale_requant_in + bias0) * scale_requant_out); r0++; r1++; r2++; r3++; outptr0++; outptr0n++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr0 += outw; outptr0n += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "dup v26.4s, %w13 \n" "dup v27.4s, %w14 \n" "dup v28.4s, %w15 \n" "0: \n" "ld1 {v4.8b, v5.8b}, [%2] \n" "ld1 {v6.8b, v7.8b}, [%3] \n" "ld1 {v8.8b, v9.8b}, [%4] \n" "add %2, %2, #8 \n" "add %3, %3, #8 \n" "add %4, %4, #8 \n" "ext v12.8b, v4.8b, v5.8b, #1 \n" "ext v13.8b, v4.8b, v5.8b, #2 \n" "ext v14.8b, v6.8b, v7.8b, #1 \n" "ext v15.8b, v6.8b, v7.8b, #2 \n" "ext v16.8b, v8.8b, v9.8b, #1 \n" "ext v17.8b, v8.8b, v9.8b, #2 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v12.8h, v12.8b, #0 \n" // r01 "sshll v13.8h, v13.8b, #0 \n" // r02 "sshll v6.8h, v6.8b, #0 \n" // r10 "sshll v14.8h, v14.8b, #0 \n" // r11 "sshll v15.8h, v15.8b, #0 \n" // r12 "sshll v8.8h, v8.8b, #0 \n" // r20 "sshll v16.8h, v16.8b, #0 \n" // r21 "sshll v17.8h, v17.8b, #0 \n" // r22 // r0 "smull v20.4s, v4.4h, %10.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %10.h[0] \n" "smull v22.4s, v12.4h, %10.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v12.8h, %10.h[1] \n" "smull v24.4s, v13.4h, %10.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v13.8h, %10.h[2] \n" // r1 "smlal v20.4s, v6.4h, %10.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v6.8h, %10.h[3] \n" "smlal v22.4s, v14.4h, %11.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v14.8h, %11.h[0] \n" "smlal v24.4s, v15.4h, %11.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v15.8h, %11.h[1] \n" // r2 "smlal v20.4s, v8.4h, %11.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v8.8h, %11.h[2] \n" "smlal v22.4s, v16.4h, %11.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v16.8h, %11.h[3] \n" "smlal v24.4s, v17.4h, %12.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v17.8h, %12.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, v27.4s \n" "fmul v21.4s, v21.4s, v27.4s \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, v26.4s \n" "fadd v21.4s, v21.4s, v26.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, v28.4s \n" "fmul v21.4s, v21.4s, v28.4s \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn2 v7.8h, v21.4s \n" // top_s16 -> top_s8 "sqxtn v8.8b, v7.8h \n" // save top_s8 "st1 {v8.8b}, [%1], #8 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr0), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx), // %12 "r"(bias0), // %13 "r"(scale_requant_in), // %14 "r"(scale_requant_out) // %15 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld1.s8 {d30-d31}, [%2] \n" // r0 "add %2, %2, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q5, d10 \n" // r01 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P10[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P10[0] \n" "vmull.s16 q9, d10, %P10[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P10[1] \n" "vmlal.s16 q7, d12, %P10[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P10[2] \n" // r1 "vld1.s8 {d30-d31}, [%3] \n" // r1 "add %3, %3, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q5, d10 \n" // r11 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P10[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P10[3] \n" "vmlal.s16 q9, d10, %P11[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P11[0] \n" "vmlal.s16 q7, d12, %P11[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P11[1] \n" // r2 "vld1.s8 {d30-d31}, [%4] \n" // r2 "add %4, %4, #8 \n" "vext.s8 d10, d30, d31, #1 \n" "vext.s8 d12, d30, d31, #2 \n" "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q5, d10 \n" // r21 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P11[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P11[2] \n" "vmlal.s16 q9, d10, %P11[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P11[3] \n" "vmlal.s16 q7, d12, %P12[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P12[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vdup.f32 q13, %13 \n" // bias "vdup.f32 q14, %14 \n" // scale_in "vdup.f32 q15, %15 \n" // scale_out // top_s32 -> top_f32 "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q0, q7, q14 \n" "vmul.f32 q4, q8, q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q0, q0, q13 \n" "vadd.f32 q4, q4, q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q0, q15 \n" "vmul.f32 q4, q4, q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s16, s16 \n" "vcvtr.s32.f32 s17, s17 \n" "vcvtr.s32.f32 s18, s18 \n" "vcvtr.s32.f32 s19, s19 \n" // top_s32 -> top_s16 "vqmovn.s32 d14, q0 \n" "vqmovn.s32 d15, q4 \n" // top_s16 -> top_s8 "vqmovn.s16 d14, q7 \n" // save top_s8 "vst1.8 {d14}, [%1]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr0), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx), // %12 "r"(bias0), // %13 "r"(scale_requant_in), // %14 "r"(scale_requant_out) // %15 : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr0 = float2int8(((float)sum * scale_requant_in + bias0) * scale_requant_out); r0++; r1++; r2++; outptr0++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_requant_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* bias = _bias; const int tailstep = w - 2 * outw + w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2 * p]; const float scale_requant_out = scales_requant[2 * p + 1]; const signed char* kernel = (const signed char*)_kernel + p * 9; signed char* outptr = out; const signed char* img = bottom_blob.channel(p); const signed char* r0 = img; const signed char* r1 = img + w; const signed char* r2 = img + w * 2; int i = 0; #if __ARM_NEON int8x16_t _k0123456789x = vld1q_s8(kernel); int16x8_t _k_s16 = vmovl_s8(vget_low_s8(_k0123456789x)); int16x8_t _kn_s16 = vmovl_s8(vget_high_s8(_k0123456789x)); int16x4_t _k0123 = vget_low_s16(_k_s16); int16x4_t _k4567 = vget_high_s16(_k_s16); int16x4_t _k8xxx = vget_low_s16(_kn_s16); #endif // __ARM_NEON for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "dup v26.4s, %w13 \n" "dup v27.4s, %w14 \n" "dup v28.4s, %w15 \n" "0: \n" "ld2 {v4.8b, v5.8b}, [%2], #16 \n" "ld2 {v6.8b, v7.8b}, [%2] \n" "ld2 {v8.8b, v9.8b}, [%3], #16 \n" "ld2 {v10.8b, v11.8b}, [%3] \n" "ld2 {v12.8b, v13.8b}, [%4], #16 \n" "ld2 {v14.8b, v15.8b}, [%4] \n" "ext v6.8b, v4.8b, v6.8b, #1 \n" "ext v10.8b, v8.8b, v10.8b, #1 \n" "ext v14.8b, v12.8b, v14.8b, #1 \n" "sshll v4.8h, v4.8b, #0 \n" // r00 "sshll v5.8h, v5.8b, #0 \n" // r01 "sshll v6.8h, v6.8b, #0 \n" // r02 "sshll v8.8h, v8.8b, #0 \n" // r10 "sshll v9.8h, v9.8b, #0 \n" // r11 "sshll v10.8h, v10.8b, #0 \n" // r12 "sshll v12.8h, v12.8b, #0 \n" // r20 "sshll v13.8h, v13.8b, #0 \n" // r21 "sshll v14.8h, v14.8b, #0 \n" // r22 // r0 "smull v20.4s, v4.4h, %10.h[0] \n" // (r00 - r07) * k00 "smull2 v21.4s, v4.8h, %10.h[0] \n" "smull v22.4s, v5.4h, %10.h[1] \n" // (r01 - r08) * k01 "smull2 v23.4s, v5.8h, %10.h[1] \n" "smull v24.4s, v6.4h, %10.h[2] \n" // (r02 - r09) * k02 "smull2 v25.4s, v6.8h, %10.h[2] \n" // r1 "smlal v20.4s, v8.4h, %10.h[3] \n" // (r10 - r17) * k03 "smlal2 v21.4s, v8.8h, %10.h[3] \n" "smlal v22.4s, v9.4h, %11.h[0] \n" // (r11 - r18) * k04 "smlal2 v23.4s, v9.8h, %11.h[0] \n" "smlal v24.4s, v10.4h, %11.h[1] \n" // (r12 - r19) * k05 "smlal2 v25.4s, v10.8h, %11.h[1] \n" // r2 "smlal v20.4s, v12.4h, %11.h[2] \n" // (r20 - r27) * k06 "smlal2 v21.4s, v12.8h, %11.h[2] \n" "smlal v22.4s, v13.4h, %11.h[3] \n" // (r21 - r28) * k07 "smlal2 v23.4s, v13.8h, %11.h[3] \n" "smlal v24.4s, v14.4h, %12.h[0] \n" // (r22 - r29) * k08 "smlal2 v25.4s, v14.8h, %12.h[0] \n" // add and save "add v20.4s, v20.4s, v22.4s \n" "add v21.4s, v21.4s, v23.4s \n" "add v20.4s, v20.4s, v24.4s \n" "add v21.4s, v21.4s, v25.4s \n" // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, v27.4s \n" "fmul v21.4s, v21.4s, v27.4s \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, v26.4s \n" "fadd v21.4s, v21.4s, v26.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, v28.4s \n" "fmul v21.4s, v21.4s, v28.4s \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn2 v7.8h, v21.4s \n" // top_s16 -> top_s8 "sqxtn v8.8b, v7.8h \n" // save top_s8 "st1 {v8.8b}, [%1], #8 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx), // %12 "r"(bias0), // %13 "r"(scale_requant_in), // %14 "r"(scale_requant_out) // %15 : "cc", "memory", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } #else if (nn > 0) { asm volatile( "0: \n" // r0 "vld2.s8 {d30-d31}, [%2]! \n" // r0 "vld2.s8 {d10-d11}, [%2] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r01 "vmovl.s8 q15, d30 \n" // r00 "vmovl.s8 q6, d12 \n" // r02 // sum0 "vmull.s16 q7, d30, %P10[0] \n" // (r00 - r07) * k00 "vmull.s16 q8, d31, %P10[0] \n" "vmull.s16 q9, d10, %P10[1] \n" // (r01 - r08) * k01 "vmull.s16 q10, d11, %P10[1] \n" "vmlal.s16 q7, d12, %P10[2] \n" // (r02 - r09) * k02 "vmlal.s16 q8, d13, %P10[2] \n" // r1 "vld2.s8 {d30-d31}, [%3]! \n" // r1 "vld2.s8 {d10-d11}, [%3] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r11 "vmovl.s8 q15, d30 \n" // r10 "vmovl.s8 q6, d12 \n" // r12 // sum0 "vmlal.s16 q7, d30, %P10[3] \n" // (r10 - r17) * k03 "vmlal.s16 q8, d31, %P10[3] \n" "vmlal.s16 q9, d10, %P11[0] \n" // (r11 - r18) * k04 "vmlal.s16 q10, d11, %P11[0] \n" "vmlal.s16 q7, d12, %P11[1] \n" // (r12 - r19) * k05 "vmlal.s16 q8, d13, %P11[1] \n" // r2 "vld2.s8 {d30-d31}, [%4]! \n" // r2 "vld2.s8 {d10-d11}, [%4] \n" "vext.s8 d12, d30, d10, #1 \n" "vmovl.s8 q5, d31 \n" // r21 "vmovl.s8 q15, d30 \n" // r20 "vmovl.s8 q6, d12 \n" // r22 // sum0 "vmlal.s16 q7, d30, %P11[2] \n" // (r20 - r27) * k06 "vmlal.s16 q8, d31, %P11[2] \n" "vmlal.s16 q9, d10, %P11[3] \n" // (r21 - r28) * k07 "vmlal.s16 q10, d11, %P11[3] \n" "vmlal.s16 q7, d12, %P12[0] \n" // (r22 - r29) * k08 "vmlal.s16 q8, d13, %P12[0] \n" "subs %0, %0, #1 \n" // add and save "vadd.s32 q7, q7, q9 \n" "vadd.s32 q8, q8, q10 \n" "vdup.f32 q11, %13 \n" // bias "vdup.f32 q12, %14 \n" // scale_in "vdup.f32 q13, %15 \n" // scale_out // top_s32 -> top_f32 "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q0, q7, q12 \n" "vmul.f32 q4, q8, q12 \n" // top_f32 = top_f32 + bias "vadd.f32 q0, q0, q11 \n" "vadd.f32 q4, q4, q11 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q0, q13 \n" "vmul.f32 q4, q4, q13 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s16, s16 \n" "vcvtr.s32.f32 s17, s17 \n" "vcvtr.s32.f32 s18, s18 \n" "vcvtr.s32.f32 s19, s19 \n" // top_s32 -> top_s16 "vqmovn.s32 d14, q0 \n" "vqmovn.s32 d15, q4 \n" // top_s16 -> top_s8 "vqmovn.s16 d14, q7 \n" // save top_s8 "vst1.8 {d14}, [%1]! \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k4567), // %11 "w"(_k8xxx), // %12 "r"(bias0), // %13 "r"(scale_requant_in), // %14 "r"(scale_requant_out) // %15 : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr = float2int8(((float)sum * scale_requant_in + bias0) * scale_requant_out); r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
GeometryConverter.h
/* -*-c++-*- IfcQuery www.ifcquery.com * MIT License Copyright (c) 2017 Fabian Gerold 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. */ #pragma once #include <unordered_set> #include <ifcpp/model/BasicTypes.h> #include <ifcpp/model/BuildingModel.h> #include <ifcpp/model/OpenMPIncludes.h> #include <ifcpp/model/StatusCallback.h> #include <ifcpp/IFC4/include/IfcCurtainWall.h> #include <ifcpp/IFC4/include/IfcGloballyUniqueId.h> #include <ifcpp/IFC4/include/IfcPropertySetDefinitionSet.h> #include <ifcpp/IFC4/include/IfcRelAggregates.h> #include <ifcpp/IFC4/include/IfcRelContainedInSpatialStructure.h> #include <ifcpp/IFC4/include/IfcRelDefinesByProperties.h> #include <ifcpp/IFC4/include/IfcSpace.h> #include <ifcpp/IFC4/include/IfcWindow.h> #include "IncludeCarveHeaders.h" #include "GeometryInputData.h" #include "RepresentationConverter.h" #include "CSG_Adapter.h" class GeometryConverter : public StatusCallback { protected: shared_ptr<BuildingModel> m_ifc_model; shared_ptr<GeometrySettings> m_geom_settings; shared_ptr<RepresentationConverter> m_representation_converter; std::map<std::string, shared_ptr<ProductShapeData> > m_product_shape_data; std::map<std::string, shared_ptr<BuildingObject> > m_map_outside_spatial_structure; double m_recent_progress = 0; double m_csg_eps = 1.5e-05; std::map<int, std::vector<shared_ptr<StatusCallback::Message> > > m_messages; #ifdef ENABLE_OPENMP Mutex m_writelock_messages; #endif public: // getters and setters shared_ptr<BuildingModel>& getBuildingModel() { return m_ifc_model; } shared_ptr<RepresentationConverter>& getRepresentationConverter() { return m_representation_converter; } shared_ptr<GeometrySettings>& getGeomSettings() { return m_geom_settings; } std::map<std::string, shared_ptr<ProductShapeData> >& getShapeInputData() { return m_product_shape_data; } std::map<std::string, shared_ptr<BuildingObject> >& getObjectsOutsideSpatialStructure() { return m_map_outside_spatial_structure; } GeometryConverter( shared_ptr<BuildingModel>& ifc_model ) { m_ifc_model = ifc_model; m_geom_settings = shared_ptr<GeometrySettings>( new GeometrySettings() ); resetNumVerticesPerCircle(); shared_ptr<UnitConverter>& unit_converter = m_ifc_model->getUnitConverter(); m_representation_converter = shared_ptr<RepresentationConverter>( new RepresentationConverter( m_geom_settings, unit_converter ) ); // redirect all messages to this->messageTarget m_ifc_model->setMessageTarget( this ); m_representation_converter->setMessageTarget( this ); } virtual ~GeometryConverter() {} void resetModel() { progressTextCallback( L"Unloading model, cleaning up memory..." ); clearInputCache(); m_recent_progress = 0.0; m_ifc_model->clearCache(); m_ifc_model->clearIfcModel(); progressTextCallback( L"Unloading model done" ); progressValueCallback( 0.0, "parse" ); #ifdef _DEBUG GeomDebugDump::clearMeshsetDump(); #endif } void clearInputCache() { m_product_shape_data.clear(); m_map_outside_spatial_structure.clear(); m_representation_converter->clearCache(); m_messages.clear(); } void resetNumVerticesPerCircle() { m_geom_settings->resetNumVerticesPerCircle(); } void setCsgEps(double eps) { m_csg_eps = eps; } void setModel( shared_ptr<BuildingModel> model ) { if( m_ifc_model ) { m_ifc_model->unsetMessageCallBack(); } clearInputCache(); m_ifc_model = model; m_representation_converter->clearCache(); m_representation_converter->setUnitConverter( m_ifc_model->getUnitConverter() ); m_ifc_model->setMessageTarget( this ); } void resolveProjectStructure( shared_ptr<ProductShapeData>& product_data ) { if( !product_data ) { return; } if( product_data->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> ifc_object_def(product_data->m_ifc_object_definition); if (!ifc_object_def) { return; } product_data->m_added_to_spatial_structure = true; const std::vector<weak_ptr<IfcRelAggregates> >& vec_IsDecomposedBy = ifc_object_def->m_IsDecomposedBy_inverse; for( size_t ii = 0; ii < vec_IsDecomposedBy.size(); ++ii ) { const weak_ptr<IfcRelAggregates>& rel_aggregates_weak_ptr = vec_IsDecomposedBy[ii]; if( rel_aggregates_weak_ptr.expired() ) { continue; } shared_ptr<IfcRelAggregates> rel_aggregates( rel_aggregates_weak_ptr ); if( rel_aggregates ) { const std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = rel_aggregates->m_RelatedObjects; for( size_t jj = 0; jj < vec_related_objects.size(); ++jj ) { const shared_ptr<IfcObjectDefinition>& related_obj_def = vec_related_objects[jj]; if( related_obj_def ) { std::string related_guid; if (related_obj_def->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; related_guid = converterX.to_bytes(related_obj_def->m_GlobalId->m_value); } auto it_product_map = m_product_shape_data.find(related_guid); if( it_product_map != m_product_shape_data.end() ) { shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second; if( related_product_shape ) { product_data->addChildProduct( related_product_shape, product_data ); resolveProjectStructure( related_product_shape ); } } } } } } shared_ptr<IfcSpatialStructureElement> spatial_ele = dynamic_pointer_cast<IfcSpatialStructureElement>(ifc_object_def); if( spatial_ele ) { const std::vector<weak_ptr<IfcRelContainedInSpatialStructure> >& vec_contains = spatial_ele->m_ContainsElements_inverse; for( size_t ii = 0; ii < vec_contains.size(); ++ii ) { const weak_ptr<IfcRelContainedInSpatialStructure>& rel_contained_weak_ptr = vec_contains[ii]; if( rel_contained_weak_ptr.expired() ) { continue; } shared_ptr<IfcRelContainedInSpatialStructure> rel_contained( rel_contained_weak_ptr ); if( rel_contained ) { const std::vector<shared_ptr<IfcProduct> >& vec_related_elements = rel_contained->m_RelatedElements; for( size_t jj = 0; jj < vec_related_elements.size(); ++jj ) { const shared_ptr<IfcProduct>& related_product = vec_related_elements[jj]; if( related_product ) { std::string related_guid; if (related_product->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; related_guid = converterX.to_bytes(related_product->m_GlobalId->m_value); } auto it_product_map = m_product_shape_data.find(related_guid); if( it_product_map != m_product_shape_data.end() ) { shared_ptr<ProductShapeData>& related_product_shape = it_product_map->second; if( related_product_shape ) { product_data->addChildProduct( related_product_shape, product_data ); resolveProjectStructure( related_product_shape ); } } } } } } } // TODO: handle IfcRelAssignsToProduct } void readAppearanceFromPropertySet( const shared_ptr<IfcPropertySet>& prop_set, shared_ptr<ProductShapeData>& product_shape ) { if( !prop_set ) { return; } for( auto& ifc_property : prop_set->m_HasProperties ) { if( !ifc_property ) { continue; } shared_ptr<IfcSimpleProperty> simple_property = dynamic_pointer_cast<IfcSimpleProperty>(ifc_property); if( simple_property ) { // ENTITY IfcSimpleProperty ABSTRACT SUPERTYPE OF(ONEOF( IfcPropertyBoundedValue, IfcPropertyEnumeratedValue, IfcPropertyListValue, // IfcPropertyReferenceValue, IfcPropertySingleValue, IfcPropertyTableValue)) shared_ptr<IfcIdentifier> property_name = simple_property->m_Name; std::wstring name_str = property_name->m_value; if( name_str.compare( L"LayerName" ) == 0 ) { // TODO: implement layers } shared_ptr<IfcText> description = simple_property->m_Description; shared_ptr<IfcPropertySingleValue> property_single_value = dynamic_pointer_cast<IfcPropertySingleValue>(simple_property); if( property_single_value ) { //shared_ptr<IfcValue>& nominal_value = property_single_value->m_NominalValue; //optional //shared_ptr<IfcUnit>& unit = property_single_value->m_Unit; //optional } continue; } shared_ptr<IfcComplexProperty> complex_property = dynamic_pointer_cast<IfcComplexProperty>(ifc_property); if( complex_property ) { if( !complex_property->m_UsageName ) continue; if( complex_property->m_UsageName->m_value.compare( L"Color" ) == 0 ) { vec4 vec_color; m_representation_converter->getStylesConverter()->convertIfcComplexPropertyColor( complex_property, vec_color ); shared_ptr<AppearanceData> appearance_data( new AppearanceData( -1 ) ); if( !appearance_data ) { throw OutOfMemoryException( __FUNC__ ); } appearance_data->m_apply_to_geometry_type = AppearanceData::GEOM_TYPE_ANY; appearance_data->m_color_ambient.setColor( vec_color ); appearance_data->m_color_diffuse.setColor( vec_color ); appearance_data->m_color_specular.setColor( vec_color ); appearance_data->m_shininess = 35.f; product_shape->addAppearance( appearance_data ); } } } } /*\brief method convertGeometry: Creates geometry for Carve from previously loaded BuildingModel model. **/ void convertGeometry() { progressTextCallback( L"Creating geometry..." ); progressValueCallback( 0, "geometry" ); m_product_shape_data.clear(); m_map_outside_spatial_structure.clear(); m_representation_converter->clearCache(); if( !m_ifc_model ) { return; } shared_ptr<ProductShapeData> ifc_project_data; std::vector<shared_ptr<IfcObjectDefinition> > vec_object_definitions; double length_to_meter_factor = 1.0; if( m_ifc_model->getUnitConverter() ) { length_to_meter_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor(); } carve::setEpsilon( m_csg_eps ); const std::map<int, shared_ptr<BuildingEntity> >& map_entities = m_ifc_model->getMapIfcEntities(); if (map_entities.size() > 0) { for (auto it = map_entities.begin(); it != map_entities.end(); ++it) { shared_ptr<BuildingEntity> obj = it->second; if (obj) { shared_ptr<IfcObjectDefinition> object_def = dynamic_pointer_cast<IfcObjectDefinition>(obj); if (object_def) { vec_object_definitions.push_back(object_def); } } } } // create geometry for for each IfcProduct independently, spatial structure will be resolved later std::map<std::string, shared_ptr<ProductShapeData> >* map_products_ptr = &m_product_shape_data; const int num_object_definitions = (int)vec_object_definitions.size(); #ifdef ENABLE_OPENMP Mutex writelock_map; Mutex writelock_ifc_project; #pragma omp parallel firstprivate(num_object_definitions) shared(map_products_ptr) { // time for one product may vary significantly, so schedule not so many #pragma omp for schedule(dynamic,40) #endif for( int i = 0; i < num_object_definitions; ++i ) { shared_ptr<IfcObjectDefinition> object_def = vec_object_definitions[i]; const int entity_id = object_def->m_entity_id; std::string guid; if (object_def->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; guid = converterX.to_bytes(object_def->m_GlobalId->m_value); } shared_ptr<ProductShapeData> product_geom_input_data( new ProductShapeData( entity_id ) ); product_geom_input_data->m_ifc_object_definition = object_def; // TODO: check for equal product shapes: each representation and each item must be equal, also openings must be equal: m_HasOpenings_inverse std::stringstream thread_err; if( !m_geom_settings->getRenderObjectFilter()(object_def) ) { // geometry will be created in method subtractOpenings continue; } else if( dynamic_pointer_cast<IfcProject>(object_def) ) { #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_ifc_project ); #endif ifc_project_data = product_geom_input_data; } try { convertIfcProductShape( product_geom_input_data ); } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { thread_err << e.what(); } catch( carve::exception& e ) { thread_err << e.str(); } catch( std::exception& e ) { thread_err << e.what(); } catch( ... ) { thread_err << "undefined error, product id " << entity_id; } { #ifdef ENABLE_OPENMP ScopedLock scoped_lock( writelock_map ); #endif map_products_ptr->insert( std::make_pair( guid, product_geom_input_data ) ); if( thread_err.tellp() > 0 ) { messageCallback( thread_err.str().c_str(), StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } } // progress callback double progress = (double)i / (double)num_object_definitions; if( progress - m_recent_progress > 0.02 ) { #ifdef ENABLE_OPENMP if( omp_get_thread_num() == 0 ) #endif { // leave 10% of progress to openscenegraph internals progressValueCallback( progress*0.9, "geometry" ); m_recent_progress = progress; } } } #ifdef ENABLE_OPENMP } // implicit barrier #endif // subtract openings in related objects, such as IFCBUILDINGELEMENTPART connected to a window through IFCRELAGGREGATES for( auto it = map_products_ptr->begin(); it != map_products_ptr->end(); ++it ) { shared_ptr<ProductShapeData> product_geom_input_data = it->second; try { subtractOpeningsInRelatedObjects(product_geom_input_data); } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, ""); } catch( carve::exception& e ) { messageCallback(e.str(), StatusCallback::MESSAGE_TYPE_ERROR, ""); } catch( std::exception& e ) { messageCallback(e.what(), StatusCallback::MESSAGE_TYPE_ERROR, ""); } catch( ... ) { messageCallback("undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__); } } try { // now resolve spatial structure if( ifc_project_data ) { resolveProjectStructure( ifc_project_data ); } // check if there are entities that are not in spatial structure for( auto it_product_shapes = m_product_shape_data.begin(); it_product_shapes != m_product_shape_data.end(); ++it_product_shapes ) { shared_ptr<ProductShapeData> product_shape = it_product_shapes->second; if( !product_shape ) { continue; } if( !product_shape->m_added_to_spatial_structure ) { if( !product_shape->m_ifc_object_definition.expired() ) { shared_ptr<IfcObjectDefinition> ifc_object_def( product_shape->m_ifc_object_definition ); shared_ptr<IfcFeatureElementSubtraction> opening = dynamic_pointer_cast<IfcFeatureElementSubtraction>(ifc_object_def); if( !m_geom_settings->getRenderObjectFilter()(ifc_object_def) ) { continue; } std::string guid; if (ifc_object_def->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; guid = converterX.to_bytes(ifc_object_def->m_GlobalId->m_value); } m_map_outside_spatial_structure[guid] = ifc_object_def; } } } } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( ... ) { messageCallback( "undefined error", StatusCallback::MESSAGE_TYPE_ERROR, __FUNC__ ); } m_representation_converter->getProfileCache()->clearProfileCache(); progressTextCallback( L"Loading file done" ); progressValueCallback( 1.0, "geometry" ); } //\brief method convertIfcProduct: Creates geometry objects (meshset with connected vertex-edge-face graph) from an IfcProduct object // caution: when using OpenMP, this method runs in parallel threads, so every write access to member variables needs a write lock void convertIfcProductShape( shared_ptr<ProductShapeData>& product_shape ) { if( product_shape->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition); shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if (!ifc_product) { return; } if( !ifc_product->m_Representation ) { return; } double length_factor = 1.0; if( m_ifc_model ) { if( m_ifc_model->getUnitConverter() ) { length_factor = m_ifc_model->getUnitConverter()->getLengthInMeterFactor(); } } // evaluate IFC geometry shared_ptr<IfcProductRepresentation>& product_representation = ifc_product->m_Representation; std::vector<shared_ptr<IfcRepresentation> >& vec_representations = product_representation->m_Representations; for( size_t i_representations = 0; i_representations < vec_representations.size(); ++i_representations ) { const shared_ptr<IfcRepresentation>& representation = vec_representations[i_representations]; if( !representation ) { continue; } try { shared_ptr<RepresentationData> representation_data( new RepresentationData() ); m_representation_converter->convertIfcRepresentation( representation, representation_data ); product_shape->m_vec_representations.push_back( representation_data ); representation_data->m_parent_product = product_shape; } catch( OutOfMemoryException& e ) { throw e; } catch( BuildingException& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } catch( std::exception& e ) { messageCallback( e.what(), StatusCallback::MESSAGE_TYPE_ERROR, "" ); } } // IfcProduct has an ObjectPlacement that can be local or global product_shape->m_object_placement = ifc_product->m_ObjectPlacement; if( ifc_product->m_ObjectPlacement ) { // IfcPlacement2Matrix follows related placements in case of local coordinate systems std::unordered_set<IfcObjectPlacement*> placement_already_applied; m_representation_converter->getPlacementConverter()->convertIfcObjectPlacement( ifc_product->m_ObjectPlacement, product_shape, placement_already_applied, false ); } // handle openings std::vector<shared_ptr<ProductShapeData> > vec_opening_data; const shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_product); if( ifc_element ) { m_representation_converter->subtractOpenings(ifc_element, product_shape); } // Fetch the IFCProduct relationships if( ifc_product->m_IsDefinedBy_inverse.size() > 0 ) { std::vector<weak_ptr<IfcRelDefinesByProperties> >& vec_IsDefinedBy_inverse = ifc_product->m_IsDefinedBy_inverse; for( size_t i = 0; i < vec_IsDefinedBy_inverse.size(); ++i ) { shared_ptr<IfcRelDefinesByProperties> rel_def( vec_IsDefinedBy_inverse[i] ); shared_ptr<IfcPropertySetDefinitionSelect> relating_property_definition_select = rel_def->m_RelatingPropertyDefinition; if( relating_property_definition_select ) { // TYPE IfcPropertySetDefinitionSelect = SELECT (IfcPropertySetDefinition ,IfcPropertySetDefinitionSet); shared_ptr<IfcPropertySetDefinition> property_set_def = dynamic_pointer_cast<IfcPropertySetDefinition>(relating_property_definition_select); if( property_set_def ) { shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def); if( property_set ) { readAppearanceFromPropertySet( property_set, product_shape ); } continue; } shared_ptr<IfcPropertySetDefinitionSet> property_set_def_set = dynamic_pointer_cast<IfcPropertySetDefinitionSet>(relating_property_definition_select); if( property_set_def_set ) { std::vector<shared_ptr<IfcPropertySetDefinition> >& vec_propterty_set_def = property_set_def_set->m_vec; std::vector<shared_ptr<IfcPropertySetDefinition> >::iterator it_property_set_def; for( it_property_set_def = vec_propterty_set_def.begin(); it_property_set_def != vec_propterty_set_def.end(); ++it_property_set_def ) { shared_ptr<IfcPropertySetDefinition> property_set_def2 = (*it_property_set_def); if( property_set_def2 ) { shared_ptr<IfcPropertySet> property_set = dynamic_pointer_cast<IfcPropertySet>(property_set_def2); if( property_set ) { readAppearanceFromPropertySet( property_set, product_shape ); } } } continue; } } } } } void subtractOpeningsInRelatedObjects(shared_ptr<ProductShapeData>& product_shape) { if( product_shape->m_ifc_object_definition.expired() ) { return; } shared_ptr<IfcObjectDefinition> ifc_object_def(product_shape->m_ifc_object_definition); shared_ptr<IfcProduct> ifc_product = dynamic_pointer_cast<IfcProduct>(ifc_object_def); if (!ifc_product) { return; } shared_ptr<IfcElement> ifc_element = dynamic_pointer_cast<IfcElement>(ifc_product); if( !ifc_element ) { return; } if( ifc_element->m_HasOpenings_inverse.size() == 0 ) { return; } // collect aggregated objects const std::vector<weak_ptr<IfcRelAggregates> >& vec_decomposed_by = ifc_element->m_IsDecomposedBy_inverse; for( auto& decomposed_by : vec_decomposed_by ) { if( decomposed_by.expired() ) { continue; } shared_ptr<IfcRelAggregates> decomposed_by_aggregates(decomposed_by); std::vector<shared_ptr<IfcObjectDefinition> >& vec_related_objects = decomposed_by_aggregates->m_RelatedObjects; for( auto& related_object : vec_related_objects ) { if( !related_object ) { continue; } std::string guid; if (related_object->m_GlobalId) { std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converterX; guid = converterX.to_bytes(related_object->m_GlobalId->m_value); auto it_find_related_shape = m_product_shape_data.find(guid); if( it_find_related_shape != m_product_shape_data.end() ) { shared_ptr<ProductShapeData>& related_product_shape = it_find_related_shape->second; m_representation_converter->subtractOpenings(ifc_element, related_product_shape); } } } } } virtual void messageTarget( void* ptr, shared_ptr<StatusCallback::Message> m ) { GeometryConverter* myself = (GeometryConverter*)ptr; if( myself ) { if( m->m_entity ) { #ifdef ENABLE_OPENMP ScopedLock lock( myself->m_writelock_messages ); #endif // make sure that the same message for one entity does not appear several times const int entity_id = m->m_entity->m_entity_id; auto it = myself->m_messages.find( entity_id ); if( it != myself->m_messages.end() ) { std::vector<shared_ptr<StatusCallback::Message> >& vec_message_for_entity = it->second; for( size_t i = 0; i < vec_message_for_entity.size(); ++i ) { shared_ptr<StatusCallback::Message>& existing_message = vec_message_for_entity[i]; if( existing_message->m_message_text.compare( m->m_message_text ) == 0 ) { // same message for same entity is already there, so ignore message return; } } vec_message_for_entity.push_back( m ); } else { std::vector<shared_ptr<StatusCallback::Message> >& vec = myself->m_messages.insert( std::make_pair( entity_id, std::vector<shared_ptr<StatusCallback::Message> >() ) ).first->second; vec.push_back( m ); } } myself->messageCallback( m ); } } };
pegasos_predict.c
/* Copyright (c) 2016 Drew Schmidt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <math.h> #include "utils/blas.h" #include "utils/safeomp.h" // TODO coinflip of x==0 ? #define SIGN(x) ((x) > 0 ? 1 : -1) /* * @param * @param pred (output); n-length vector */ void svm_pegasos_predict(cbool intercept, const svmdata_t *const restrict newdata) { const int n = newdata->nr; const int p = newdata->nc; const double *const x_new = newdata->x; int *const pred = newdata->y; const double *const w = newdata->w; #pragma omp parallel for default(none) if(n>OMP_MIN_SIZE) for (int i=0; i<n; i++) { double tmp = vecvecprod(COL_MAJOR, intercept, n, p, x_new+i, w); pred[i] = SIGN(tmp); } }
16_omp_heap.c
// clang-format off // RUN: %c-to-llvm %omp_c_flags %s | %apply-typeart -S 2>&1 | FileCheck %s // REQUIRES: openmp // clang-format on #include <stdlib.h> void foo(int** x) { #pragma omp parallel // transformed to @__kmpc_fork_call { double* pd = calloc(10, sizeof(double)); pd = realloc(pd, 20 * sizeof(double)); } #pragma omp parallel for for (int i = 0; i < 10; ++i) { x[i] = (int*)malloc(8 * sizeof(int)); free(x[i]); } } // CHECK: [[POINTER:%[0-9]+]] = call noalias i8* @calloc(i64 [[SIZE:[0-9]+]], i64 8) // CHECK-NEXT: call void @__typeart_alloc_omp(i8* [[POINTER]], i32 6, i64 [[SIZE]]) // CHECK-NEXT: bitcast i8* [[POINTER]] to double* // CHECK: __typeart_free_omp(i8* [[POINTER:%[0-9]+]]) // CHECK-NEXT: [[POINTER2:%[0-9]+]] = call i8* @realloc(i8* [[POINTER]], i64 160) // CHECK-NEXT: __typeart_alloc_omp(i8* [[POINTER2]], i32 6, i64 20) // CHECK: [[POINTER:%[0-9]+]] = call noalias i8* @malloc // CHECK-NEXT: call void @__typeart_alloc_omp(i8* [[POINTER]], i32 2, i64 8) // CHECK-NEXT: bitcast i8* [[POINTER]] to i32* // CHECK: call void @free // CHECK-NEXT: call void @__typeart_free_omp // CHECK: TypeArtPass [Heap] // CHECK-NEXT: Malloc{{[ ]*}}:{{[ ]*}}3 // CHECK-NEXT: Free{{[ ]*}}:{{[ ]*}}1 // CHECK-NEXT: Alloca{{[ ]*}}:{{[ ]*}}0
lister.c
/* * `Pattern detection in large temporal graphs using algebraic fingerprints` * * This experimental source code is supplied to accompany the * aforementioned paper. * * The source code is configured for a gcc build to a native * microarchitecture that must support the AVX2 and PCLMULQDQ * instruction set extensions. Other builds are possible but * require manual configuration of 'Makefile' and 'builds.h'. * * The source code is subject to the following license. * * The MIT License (MIT) * * Copyright (c) 2019 S. Thejaswi, A. Gionis * * 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. * */ #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<time.h> #include<sys/utsname.h> #include<string.h> #include<stdarg.h> #include<assert.h> #include<ctype.h> #include<omp.h> /************************************************************* Configuration. */ #define MAX_K 32 #define MAX_SHADES 32 #define PREFETCH_PAD 32 #define MAX_THREADS 128 #define UNDEFINED -1 #define MATH_INF ((index_t)0x3FFFFFFF) #include"builds.h" // get build config typedef long int index_t; // default to 64-bit indexing #include"gf.h" // finite fields #include"ffprng.h" // fast-forward pseudorandom number generator #define MIN(x,y) (x)<(y) ? (x) : (y) #define MAX(x,y) (x)>(y) ? (x) : (y) /********************************************************************* Flags. */ index_t flag_bin_input = 0; // default to ASCII input /************************************************************* Common macros. */ /* Linked list navigation macros. */ #define pnlinknext(to,el) { (el)->next = (to)->next; (el)->prev = (to); (to)->next->prev = (el); (to)->next = (el); } #define pnlinkprev(to,el) { (el)->prev = (to)->prev; (el)->next = (to); (to)->prev->next = (el); (to)->prev = (el); } #define pnunlink(el) { (el)->next->prev = (el)->prev; (el)->prev->next = (el)->next; } #define pnrelink(el) { (el)->next->prev = (el); (el)->prev->next = (el); } /*********************************************************** Error reporting. */ #define ERROR(...) error(__FILE__,__LINE__,__func__,__VA_ARGS__); static void error(const char *fn, int line, const char *func, const char *format, ...) { va_list args; va_start(args, format); fprintf(stderr, "ERROR [file = %s, line = %d]\n" "%s: ", fn, line, func); vfprintf(stderr, format, args); fprintf(stderr, "\n"); va_end(args); abort(); } /********************************************************* Get the host name. */ #define MAX_HOSTNAME 256 const char *sysdep_hostname(void) { static char hn[MAX_HOSTNAME]; struct utsname undata; uname(&undata); strcpy(hn, undata.nodename); return hn; } /********************************************************* Available threads. */ index_t num_threads(void) { #ifdef BUILD_PARALLEL return omp_get_max_threads(); #else return 1; #endif } /********************************************** Memory allocation & tracking. */ #define MALLOC(x) malloc_wrapper(x) #define FREE(x) free_wrapper(x) index_t malloc_balance = 0; struct malloc_track_struct { void *p; size_t size; struct malloc_track_struct *prev; struct malloc_track_struct *next; }; typedef struct malloc_track_struct malloc_track_t; malloc_track_t malloc_track_root; size_t malloc_total = 0; #define MEMTRACK_STACK_CAPACITY 256 size_t memtrack_stack[MEMTRACK_STACK_CAPACITY]; index_t memtrack_stack_top = -1; void *malloc_wrapper(size_t size) { if(malloc_balance == 0) { malloc_track_root.prev = &malloc_track_root; malloc_track_root.next = &malloc_track_root; } void *p = malloc(size); if(p == NULL) ERROR("malloc fails"); malloc_balance++; malloc_track_t *t = (malloc_track_t *) malloc(sizeof(malloc_track_t)); t->p = p; t->size = size; pnlinkprev(&malloc_track_root, t); malloc_total += size; for(index_t i = 0; i <= memtrack_stack_top; i++) if(memtrack_stack[i] < malloc_total) memtrack_stack[i] = malloc_total; return p; } void free_wrapper(void *p) { malloc_track_t *t = malloc_track_root.next; for(; t != &malloc_track_root; t = t->next) { if(t->p == p) break; } if(t == &malloc_track_root) ERROR("FREE issued on a non-tracked pointer %p", p); malloc_total -= t->size; pnunlink(t); free(t); free(p); malloc_balance--; } index_t *alloc_idxtab(index_t n) { index_t *t = (index_t *) MALLOC(sizeof(index_t)*n); return t; } void push_memtrack(void) { assert(memtrack_stack_top + 1 < MEMTRACK_STACK_CAPACITY); memtrack_stack[++memtrack_stack_top] = malloc_total; } size_t pop_memtrack(void) { assert(memtrack_stack_top >= 0); return memtrack_stack[memtrack_stack_top--]; } size_t current_mem(void) { return malloc_total; } double inGiB(size_t s) { return (double) s / (1 << 30); } void print_current_mem(void) { fprintf(stdout, "{curr: %.2lfGiB}", inGiB(current_mem())); fflush(stdout); } void print_pop_memtrack(void) { fprintf(stdout, "{peak: %.2lfGiB}", inGiB(pop_memtrack())); fflush(stdout); } /******************************************************** Timing subroutines. */ #define TIME_STACK_CAPACITY 256 double start_stack[TIME_STACK_CAPACITY]; index_t start_stack_top = -1; void push_time(void) { assert(start_stack_top + 1 < TIME_STACK_CAPACITY); start_stack[++start_stack_top] = omp_get_wtime(); } double pop_time(void) { double wstop = omp_get_wtime(); assert(start_stack_top >= 0); double wstart = start_stack[start_stack_top--]; return (double) (1000.0*(wstop-wstart)); } /******************************************************************* Sorting. */ void shellsort(index_t n, index_t *a) { index_t h = 1; index_t i; for(i = n/3; h < i; h = 3*h+1) ; do { for(i = h; i < n; i++) { index_t v = a[i]; index_t j = i; do { index_t t = a[j-h]; if(t <= v) break; a[j] = t; j -= h; } while(j >= h); a[j] = v; } h /= 3; } while(h > 0); } #define LEFT(x) (x<<1) #define RIGHT(x) ((x<<1)+1) #define PARENT(x) (x>>1) void heapsort_indext(index_t n, index_t *a) { /* Shift index origin from 0 to 1 for convenience. */ a--; /* Build heap */ for(index_t i = 2; i <= n; i++) { index_t x = i; while(x > 1) { index_t y = PARENT(x); if(a[x] <= a[y]) { /* heap property ok */ break; } /* Exchange a[x] and a[y] to enforce heap property */ index_t t = a[x]; a[x] = a[y]; a[y] = t; x = y; } } /* Repeat delete max and insert */ for(index_t i = n; i > 1; i--) { index_t t = a[i]; /* Delete max */ a[i] = a[1]; /* Insert t */ index_t x = 1; index_t y, z; while((y = LEFT(x)) < i) { z = RIGHT(x); if(z < i && a[y] < a[z]) { index_t s = z; z = y; y = s; } /* Invariant: a[y] >= a[z] */ if(t >= a[y]) { /* ok to insert here without violating heap property */ break; } /* Move a[y] up the heap */ a[x] = a[y]; x = y; } /* Insert here */ a[x] = t; } } /******************************************************* Bitmap manipulation. */ void bitset(index_t *map, index_t j, index_t value) { assert((value & (~1UL)) == 0); map[j/64] = (map[j/64] & ~(1UL << (j%64))) | ((value&1) << (j%64)); } index_t bitget(index_t *map, index_t j) { return (map[j/64]>>(j%64))&1UL; } /*************************************************** Random numbers and such. */ index_t irand(void) { return (((index_t) rand())<<31)^((index_t) rand()); } void randshuffle_seq(index_t n, index_t *p, ffprng_t gen) { for(index_t i = 0; i < n-1; i++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); index_t x = i+(rnd%(n-i)); index_t t = p[x]; p[x] = p[i]; p[i] = t; } } void randperm(index_t n, index_t seed, index_t *p) { #ifdef BUILD_PARALLEL index_t nt = 64; #else index_t nt = 1; #endif index_t block_size = n/nt; index_t f[128][128]; assert(nt < 128); ffprng_t base; FFPRNG_INIT(base, seed); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { for(index_t j = 0; j < nt; j++) f[t][j] = 0; index_t start = t*block_size; index_t stop = (t == nt-1) ? n-1 : (start+block_size-1); ffprng_t gen; FFPRNG_FWD(gen, start, base); for(index_t i = start; i <= stop; i++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); index_t bin = (index_t) ((unsigned long) rnd)%((unsigned long)nt); f[t][bin]++; } } for(index_t bin = 0; bin < nt; bin++) { for(index_t t = 1; t < nt; t++) { f[0][bin] += f[t][bin]; } } index_t run = 0; for(index_t j = 1; j <= nt; j++) { index_t fp = f[0][j-1]; f[0][j-1] = run; run += fp; } f[0][nt] = run; FFPRNG_INIT(base, seed); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { ffprng_t gen; index_t start = 0; index_t stop = n-1; index_t pos = f[0][t]; FFPRNG_FWD(gen, start, base); for(index_t i = start; i <= stop; i++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); index_t bin = (index_t) ((unsigned long) rnd)%((unsigned long)nt); if(bin == t) p[pos++] = i; } assert(pos == f[0][t+1]); } FFPRNG_INIT(base, (seed^0x9078563412EFDCABL)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { ffprng_t fwd, gen; index_t start = f[0][t]; index_t stop = f[0][t+1]-1; index_t u; FFPRNG_FWD(fwd, (1234567890123456L*t), base); FFPRNG_RAND(u, fwd); FFPRNG_INIT(gen, u); randshuffle_seq(stop-start+1, p + start, gen); } } /********************************** Initialize an array with random scalars. */ void randinits_scalar(scalar_t *a, index_t s, ffprng_scalar_t seed) { ffprng_t base; FFPRNG_INIT(base, seed); index_t nt = num_threads(); index_t block_size = s/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { ffprng_t gen; index_t start = t*block_size; index_t stop = (t == nt-1) ? s-1 : (start+block_size-1); FFPRNG_FWD(gen, start, base); for(index_t i = start; i <= stop; i++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); scalar_t rs = (scalar_t) rnd; a[i] = rs; } } } /***************************************************** (Parallel) prefix sum. */ index_t prefixsum(index_t n, index_t *a, index_t k) { #ifdef BUILD_PARALLEL index_t s[MAX_THREADS]; index_t nt = num_threads(); assert(nt < MAX_THREADS); index_t length = n; index_t block_size = length/nt; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t tsum = (stop-start+1)*k; for(index_t u = start; u <= stop; u++) tsum += a[u]; s[t] = tsum; } index_t run = 0; for(index_t t = 1; t <= nt; t++) { index_t v = s[t-1]; s[t-1] = run; run += v; } s[nt] = run; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t trun = s[t]; for(index_t u = start; u <= stop; u++) { index_t tv = a[u]; a[u] = trun; trun += tv + k; } assert(trun == s[t+1]); } #else index_t run = 0; for(index_t u = 0; u < n; u++) { index_t tv = a[u]; a[u] = run; run += tv + k; } #endif return run; } /************************************************************* Parallel sum. */ index_t parallelsum(index_t n, index_t *a) { index_t sum = 0; #ifdef BUILD_PARALLEL index_t s[MAX_THREADS]; index_t nt = num_threads(); assert(nt < MAX_THREADS); index_t length = n; index_t block_size = length/nt; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t tsum = 0; for(index_t u = start; u <= stop; u++) tsum += a[u]; s[t] = tsum; } for(index_t t = 0; t < nt; t++) sum += s[t]; #else for(index_t i = 0; i < n; i++) { sum += a[i]; } #endif return sum; } // count number of non-zero values in an array index_t parallelcount(index_t n, index_t *a) { index_t total_cnt = 0; #ifdef BUILD_PARALLEL index_t nt = num_threads(); index_t block_size = n/nt; index_t *cnt_nt = alloc_idxtab(nt); #pragma omp parallel for for(index_t th = 0; th <nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); index_t cnt = 0; for(index_t i = start; i <= stop; i++) cnt += (a[i] ? 1 : 0); cnt_nt[th] = cnt; } for(index_t th = 0; th < nt; th++) total_cnt += cnt_nt[th]; #else for(index_t i = 0; i < n; i++) total_cnt += (a[i] ? 1 : 0); #endif return total_cnt; } /************************ Search for an interval of values in a sorted array. */ index_t get_interval(index_t n, index_t *a, index_t lo_val, index_t hi_val, index_t *iv_start, index_t *iv_end) { assert(n >= 0); if(n == 0) { *iv_start = 0; return 0; } assert(lo_val <= hi_val); // find first element in interval (if any) with binary search index_t lo = 0; index_t hi = n-1; // at or above lo, and at or below hi (if any) while(lo < hi) { index_t mid = (lo+hi)/2; // lo <= mid < hi index_t v = a[mid]; if(hi_val < v) { hi = mid-1; // at or below hi (if any) } else { if(v < lo_val) lo = mid+1; // at or above lo (if any), lo <= hi else hi = mid; // at or below hi (exists) } // 0 <= lo <= n-1 } if(a[lo] < lo_val || a[lo] > hi_val) { // array contains no values in interval if(a[lo] < lo_val) { lo++; assert(lo == n || a[lo+1] > hi_val); } else { assert(lo == 0 || a[lo-1] < lo_val); } *iv_start = lo; *iv_end = hi; return 0; } assert(lo_val <= a[lo] && a[lo] <= hi_val); *iv_start = lo; // find interval end (last index in interval) with binary search lo = 0; hi = n-1; // last index (if any) is at or above lo, and at or below hi while(lo < hi) { index_t mid = (lo+hi+1)/2; // lo < mid <= hi index_t v = a[mid]; if(hi_val < v) { hi = mid-1; // at or below hi, lo <= hi } else { if(v < lo_val) lo = mid+1; // at or above lo else lo = mid; // at or above lo, lo <= hi } } assert(lo == hi); *iv_end = lo; // lo == hi return 1+*iv_end-*iv_start; // return cut size } /******************************************************************** Stack. */ typedef struct stack_node { index_t u; index_t l; index_t t; } stack_node_t; typedef struct stack { index_t size; // size of stack index_t n; // number of elements stack_node_t *a; }stk_t; stk_t * stack_alloc(index_t size) { stk_t *s = (stk_t *) malloc(sizeof(stk_t)); s->size = size; s->n = 0; s->a = (stack_node_t *) malloc(s->size*sizeof(stack_node_t)); #ifdef DEBUG for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; e->u = UNDEFINED; e->l = UNDEFINED; e->t = UNDEFINED; } #endif return s; } void stack_free(stk_t *s) { free(s->a); free(s); } void stack_push(stk_t *s, stack_node_t *e_in) { assert(s->n < s->size); stack_node_t *e = s->a + s->n; e->u = e_in->u; //e->l = e_in->l; e->t = e_in->t; s->n++; } void stack_pop(stk_t *s, stack_node_t *e_out) { assert(s->n > 0); s->n--; stack_node_t *e = s->a + s->n; e_out->u = e->u; //e_out->l = e->l; e_out->t = e->t; #ifdef DEBUG e->u = UNDEFINED; //e->l = UNDEFINED; e->t = UNDEFINED; #endif } void stack_top(stk_t *s, stack_node_t *e_out) { assert(s->n >= 0); stack_node_t *e = s->a + s->n-1; e_out->u = e->u; e_out->l = e->l; e_out->t = e->t; } void stack_empty(stk_t *s) { s->n = 0; } void stack_get_vertices(stk_t *s, index_t *uu) { for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; uu[i] = e->u; } } void stack_get_timestamps(stk_t *s, index_t *tt) { for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; tt[i] = e->t; } } #ifdef DEBUG void print_stack(stk_t *s) { fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "print stack\n"); fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "size: %ld\n", s->size); fprintf(stdout, "n: %ld\n", s->n); fprintf(stdout, "a: "); for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; fprintf(stdout, "[%ld, %ld, %ld]%s", e->u, e->l, e->t, (i==s->n-1)?"\n":" "); } fprintf(stdout, "-----------------------------------------------\n"); } void print_stacknode(stack_node_t *e) { fprintf(stdout, "print stack-node: [%ld, %ld, %ld]\n", e->u, e->l, e->t); } #endif /****************************************************************** Sieving. */ long long int num_muls; long long int trans_bytes; #define SHADE_LINES ((MAX_SHADES+SCALARS_IN_LINE-1)/SCALARS_IN_LINE) typedef unsigned int shade_map_t; void constrained_sieve_pre(index_t n, index_t k, index_t g, index_t pfx, index_t num_shades, shade_map_t *d_s, ffprng_scalar_t seed, line_array_t *d_x) { assert(g == SCALARS_IN_LINE); assert(num_shades <= MAX_SHADES); line_t wdj[SHADE_LINES*MAX_K]; ffprng_t base; FFPRNG_INIT(base, seed); for(index_t j = 0; j < k; j++) { for(index_t dl = 0; dl < SHADE_LINES; dl++) { index_t jsdl = j*SHADE_LINES+dl; LINE_SET_ZERO(wdj[jsdl]); for(index_t a = 0; a < SCALARS_IN_LINE; a++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, base); scalar_t rs = (scalar_t) rnd; LINE_STORE_SCALAR(wdj[jsdl], a, rs); // W: [cached] } } } index_t nt = num_threads(); index_t length = n; index_t block_size = length/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { ffprng_t gen; index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); FFPRNG_FWD(gen, SHADE_LINES*SCALARS_IN_LINE*start, base); line_t vd[SHADE_LINES]; for(index_t j = 0; j < SHADE_LINES; j++) { LINE_SET_ZERO(vd[j]); // to cure an annoying compiler warning } for(index_t u = start; u <= stop; u++) { scalar_t uu[MAX_K]; shade_map_t shades_u = d_s[u]; // R: n shade_map_t for(index_t dl = 0; dl < SHADE_LINES; dl++) { for(index_t a = 0; a < SCALARS_IN_LINE; a++) { index_t d = dl*SCALARS_IN_LINE + a; ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); scalar_t rs = (scalar_t) rnd; rs = rs & (-((scalar_t)((shades_u >> d)&(d < num_shades)))); LINE_STORE_SCALAR(vd[dl], a, rs); // W: [cached] } } for(index_t j = 0; j < k; j++) { scalar_t uj; SCALAR_SET_ZERO(uj); for(index_t dl = 0; dl < SHADE_LINES; dl++) { index_t jsdl = j*SHADE_LINES+dl; line_t ln; LINE_MUL(ln, wdj[jsdl], vd[dl]); // R: [cached] // MUL: n*SHADE_LINES*g*k scalar_t lns; LINE_SUM(lns, ln); SCALAR_ADD(uj, uj, lns); } uu[j] = uj; } line_t ln; LINE_SET_ZERO(ln); for(index_t a = 0; a < SCALARS_IN_LINE; a++) { index_t ap = a < (1L << k) ? pfx+a : 0; scalar_t xua; SCALAR_SET_ZERO(xua); for(index_t j = 0; j < k; j++) { scalar_t z_uj = uu[j]; // R: [cached] z_uj = z_uj & (-((scalar_t)(((ap) >> j)&1))); SCALAR_ADD(xua, xua, z_uj); } LINE_STORE_SCALAR(ln, a, xua); } LINE_STORE(d_x, u, ln); // W: ng scalar_t } } num_muls += n*SHADE_LINES*g*k; trans_bytes += sizeof(scalar_t)*n*g + sizeof(shade_map_t)*n; } /***************************************************************** Line sum. */ scalar_t line_sum(index_t l, index_t g, line_array_t *d_s) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { SCALAR_SET_ZERO(ts[t]); index_t start = t*block_size; index_t stop = (t == nt-1) ? l-1 : (start+block_size-1); line_t ln; line_t acc; LINE_SET_ZERO(acc); for(index_t i = start; i <= stop; i++) { LINE_LOAD(ln, d_s, i); // R: lg scalar_t LINE_ADD(acc, acc, ln); } scalar_t lsum; LINE_SUM(lsum, acc); ts[t] = lsum; } scalar_t sum; SCALAR_SET_ZERO(sum); for(index_t t = 0; t < nt; t++) { SCALAR_ADD(sum, sum, ts[t]); } trans_bytes += sizeof(scalar_t)*l*g; return sum; } void vertex_acc(index_t l, index_t g, index_t stride, line_array_t *d_s, scalar_t *out) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); //scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { //SCALAR_SET_ZERO(ts[t]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; scalar_t lsum; for(index_t i = start; i <= stop; i++) { LINE_LOAD(ln, d_s, i); // R: lg scalar_t LINE_SUM(lsum, ln); out[i] = lsum; // R: scalar_t, W: scalar_t } } //scalar_t sum; //SCALAR_SET_ZERO(sum); //for(index_t t = 0; t < nt; t++) { // SCALAR_ADD(sum, sum, ts[t]); //} trans_bytes += sizeof(scalar_t)*(l*g+2); } scalar_t line_sum_stride(index_t l, index_t g, index_t stride, line_array_t *d_s) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { SCALAR_SET_ZERO(ts[th]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; line_t acc; LINE_SET_ZERO(acc); for(index_t i = start; i <= stop; i++) { index_t ii = i*stride; LINE_LOAD(ln, d_s, ii); // R: lg scalar_t LINE_ADD(acc, acc, ln); } scalar_t lsum; LINE_SUM(lsum, acc); ts[th] = lsum; } scalar_t sum; SCALAR_SET_ZERO(sum); for(index_t th = 0; th < nt; th++) { SCALAR_ADD(sum, sum, ts[th]); } trans_bytes += sizeof(scalar_t)*l*g; return sum; } void vertex_acc_stride(index_t l, index_t g, index_t stride, line_array_t *d_s, scalar_t *out) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); //scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { //SCALAR_SET_ZERO(ts[th]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; scalar_t lsum; for(index_t i = start; i <= stop; i++) { index_t ii = i*stride; LINE_LOAD(ln, d_s, ii); // R: lg scalar_t LINE_SUM(lsum, ln); out[i] = lsum; // R: scalar_t, W: scalar_t } } //scalar_t sum; //SCALAR_SET_ZERO(sum); //for(index_t th = 0; th < nt; th++) { // SCALAR_ADD(sum, sum, ts[th]); //} trans_bytes += sizeof(scalar_t)*(l*g+2); } /************************************************ k-temppath generating function. */ #define TEMP_PATH_LINE_IDX(n, k, tmax, l, t, u) (((l-1)*(tmax+1)*(n))+((n)*(t))+(u)) #ifdef DEBUG #define PRINT_LINE(source) \ { \ scalar_t *s = (scalar_t *)&source; \ for(index_t i = 0; i < SCALARS_IN_LINE; i++) { \ fprintf(stdout, SCALAR_FORMAT_STRING"%s", \ (long) s[i], \ i==SCALARS_IN_LINE-1 ? "\n":" "); \ } \ } void print_dx(index_t n, line_array_t *d_x) { fprintf(stdout, "d_x:\n"); for(index_t u = 0; u < n; u ++) { line_t xu; LINE_LOAD(xu, d_x, u); fprintf(stdout, "%ld: ", u); PRINT_LINE(xu); } } void print_ds(index_t n, index_t k, index_t tmax, line_array_t *d_s) { fprintf(stdout, "d_s: \n"); for(index_t l = 1; l <= k; l++) { fprintf(stdout, "--------------------------------------------------\n"); fprintf(stdout, "--------------------------------------------------\n"); fprintf(stdout, "l: %ld\n", l); fprintf(stdout, "--------------------------------------------------\n"); fprintf(stdout, "--------------------------------------------------\n"); for(index_t t = 0; t <= tmax; t++) { fprintf(stdout, "--------------------------------------------------\n"); fprintf(stdout, "t: %ld\n", t); fprintf(stdout, "--------------------------------------------------\n"); for(index_t u = 0; u < n; u++) { fprintf(stdout, "%ld: ", u+1); index_t i_ult = TEMP_PATH_LINE_IDX(n, k, tmax, l, t, u); line_t p_ult; LINE_LOAD(p_ult, d_s, i_ult); PRINT_LINE(p_ult); scalar_t sum; LINE_SUM(sum, p_ult); fprintf(stdout, "line sum: "SCALAR_FORMAT_STRING"\n",sum); } } } } #endif void init_ds(index_t n, index_t k, index_t tmax, line_array_t *d_s) { line_t p_zero; LINE_SET_ZERO(p_zero); for(index_t l = 1; l <= k; l++) { for(index_t t = 0; t <= tmax; t++) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_ult = TEMP_PATH_LINE_IDX(n, k, tmax, l, t, u); LINE_STORE(d_s, i_ult, p_zero); // W: ng scalar_t } } } } void k_temp_path_genf_round(index_t n, index_t m, index_t k, index_t tmax, index_t t, index_t g, index_t l, index_t *d_pos, index_t *d_adj, index_t yl_seed, line_array_t *d_x, line_array_t *d_s) { assert(g == SCALARS_IN_LINE); index_t nt = num_threads(); index_t length = n; index_t block_size = length/nt; ffprng_t y_base; FFPRNG_INIT(y_base, yl_seed); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? length-1 : (start+block_size-1); ffprng_t y_gen; index_t y_pos = d_pos[(t-1)*n+start]-((t-1)*n+start); FFPRNG_FWD(y_gen, y_pos, y_base); for(index_t u = start; u <= stop; u++) { index_t pu = d_pos[n*(t-1)+u]; index_t deg = d_adj[pu]; line_t p_ult; LINE_SET_ZERO(p_ult); for(index_t j = 1; j <= deg; j++) { index_t v = d_adj[pu+j]; line_t p_vl1t1; index_t i_vl1t1 = TEMP_PATH_LINE_IDX(n, k, tmax, l-1, t-1, v); LINE_LOAD(p_vl1t1, d_s, i_vl1t1); #ifdef BUILD_PREFETCH // prefetch next line index_t nv = d_adj[pu+j+(j < deg ? 1 : 2)]; index_t i_nvl1t1 = TEMP_PATH_LINE_IDX(n, k, tmax, l-1, t-1, nv); LINE_PREFETCH(d_s, i_nvl1t1); #endif ffprng_scalar_t rnd; FFPRNG_RAND(rnd, y_gen); scalar_t y_luvt = (scalar_t) rnd; line_t sy; LINE_MUL_SCALAR(sy, p_vl1t1, y_luvt); LINE_ADD(p_ult, p_ult, sy); } line_t xu; LINE_LOAD(xu, d_x, u); LINE_MUL(p_ult, p_ult, xu); line_t p_ult1; index_t i_ult1 = TEMP_PATH_LINE_IDX(n, k, tmax, l, t-1, u); LINE_LOAD(p_ult1, d_s, i_ult1); LINE_ADD(p_ult, p_ult, p_ult1); index_t i_ult = TEMP_PATH_LINE_IDX(n, k, tmax, l, t, u); LINE_STORE(d_s, i_ult, p_ult); // W: ng scalar_t } } // total edges at time `t` index_t m_t = d_pos[n*(t-1) + n-1] - d_pos[n*(t-1)] - (n-1) + d_adj[d_pos[n*(t-1)+(n-1)]]; trans_bytes += ((2*n*tmax)+m_t)*sizeof(index_t) + (2*n+m_t)*g*sizeof(scalar_t); num_muls += (n*g+m_t); } scalar_t k_temp_path_genf(index_t n, index_t m, index_t k, index_t tmax, index_t g, index_t vert_loc, index_t *d_pos, index_t *d_adj, ffprng_scalar_t y_seed, line_array_t *d_x, scalar_t *vs) { assert( g == SCALARS_IN_LINE); assert( k >= 1); line_array_t *d_s= (line_array_t *) MALLOC(LINE_ARRAY_SIZE(k*(tmax+1)*n*g)); init_ds(n, k, tmax, d_s); // initialise: l = 1 for(index_t u = 0; u < n; u++) { for(index_t t = 0; t <= tmax; t++) { line_t xu; LINE_LOAD(xu, d_x, u); index_t i_u_1 = TEMP_PATH_LINE_IDX(n, k, tmax, 1, t, u); LINE_STORE(d_s, i_u_1, xu); } } srand(y_seed); for(index_t l = 2; l <= k; l++) { ffprng_scalar_t yl_seed = irand(); // new seed for each l for(index_t t = l-1; t <= tmax; t++) { k_temp_path_genf_round(n, m, k, tmax, t, g, l, d_pos, d_adj, yl_seed, d_x, d_s); } } // sum up index_t ii = TEMP_PATH_LINE_IDX(n, k, tmax, k, tmax, 0); scalar_t sum = line_sum(n, g, ((line_array_t *)(((line_t *) d_s)+ii))); // vertex-localisation if(vert_loc) { vertex_acc(n, g, k, ((line_array_t *)(((line_t *) d_s)+ii)), vs); } //print_ds(n, k, tmax, d_s); // free memory FREE(d_s); return sum; } /************************************************************ The oracle(s). */ index_t temppath_oracle(index_t n, index_t k, index_t tmax, index_t *h_pos, index_t *h_adj, index_t num_shades, shade_map_t *h_s, ffprng_scalar_t y_seed, ffprng_scalar_t z_seed, index_t vert_loc, scalar_t *master_vsum) { push_memtrack(); assert(k >= 1 && k < 31); //index_t m = h_pos[n-1]+h_adj[h_pos[n-1]]+1-n; index_t m = h_pos[n*(tmax-1)+n-1]+h_adj[h_pos[n*(tmax-1)+n-1]]+1-(n*tmax); index_t sum_size = 1 << k; index_t g = SCALARS_IN_LINE; index_t outer = (sum_size + g-1) / g; // number of iterations for outer loop num_muls = 0; trans_bytes = 0; index_t *d_pos = h_pos; index_t *d_adj = h_adj; line_array_t *d_x = (line_array_t *) MALLOC(LINE_ARRAY_SIZE(n*g)); /* Run the work & time it. */ push_time(); scalar_t master_sum; SCALAR_SET_ZERO(master_sum); if(vert_loc) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) master_vsum[i] = 0; } for(index_t out = 0; out < outer; out++) { constrained_sieve_pre(n, k, g, g*out, num_shades, h_s, z_seed, d_x); #define GENF_TYPE "k_temp_path_genf" scalar_t sum = k_temp_path_genf(n, m, k, tmax, g, vert_loc, d_pos, d_adj, y_seed, d_x, master_vsum); SCALAR_ADD(master_sum, master_sum, sum); } double time = pop_time(); double trans_rate = trans_bytes / (time/1000.0); double mul_rate = num_muls / time; FREE(d_x); fprintf(stdout, SCALAR_FORMAT_STRING " %.2lf ms [%.2lfGiB/s, %.2lfGHz] %d", (long) master_sum, time, trans_rate/((double) (1 << 30)), mul_rate/((double) 1e6), master_sum != 0); fprintf(stdout, " "); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fflush(stdout); return master_sum != 0; } /************************************** k-path generating function (mark 1). */ #define PATH_LINE_IDX(b, k, l, u) ((k)*(u)+(l)-1) #ifdef DEBUG void print_kpath_ds(index_t n, index_t k, line_array_t *d_s) { for(index_t l = 1; l <= k; l++) { fprintf(stdout,"-------------------------------------------------\n"); fprintf(stdout, "l: %ld\n", l); fprintf(stdout,"-------------------------------------------------\n"); for(index_t u = 0; u < n; u++) { fprintf(stdout, "%ld: ", u+1); index_t i_u_l = PATH_LINE_IDX(b, k, l, u); line_t pul; LINE_LOAD(pul, d_s, i_u_l); PRINT_LINE(pul); scalar_t sum; LINE_SUM(sum, pul); fprintf(stdout, "line sum: "SCALAR_FORMAT_STRING"\n",sum); } } } #endif void k_path_genf_round(index_t n, index_t m, index_t k, index_t g, index_t l, index_t *d_pos, index_t *d_adj, ffprng_scalar_t yl_seed, line_array_t *d_s) { assert(g == SCALARS_IN_LINE); index_t nt = num_threads(); index_t length = n; index_t block_size = length/nt; ffprng_t y_base; FFPRNG_INIT(y_base, yl_seed); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); ffprng_t y_gen; index_t y_pos = d_pos[start]-start; FFPRNG_FWD(y_gen, y_pos, y_base); for(index_t u = start; u <= stop; u++) { index_t pu = d_pos[u]; // R: n index_t [hw pref] index_t deg = d_adj[pu]; // R: n index_t [hw pref] line_t pul; LINE_SET_ZERO(pul); for(index_t j = 1; j <= deg; j++) { index_t v = d_adj[pu+j]; // R: m index_t [hw pref] line_t pvl1; index_t i_v_l1 = PATH_LINE_IDX(b, k, l-1, v); LINE_LOAD(pvl1, d_s, i_v_l1); #ifdef BUILD_PREFETCH // prefetch next line index_t nv = d_adj[pu+j+(j < deg ? 1 : 2)]; index_t i_nv_l1 = PATH_LINE_IDX(b, k, l-1, nv); LINE_PREFETCH(d_s, i_nv_l1); #endif ffprng_scalar_t rnd; FFPRNG_RAND(rnd, y_gen); scalar_t y_luv = (scalar_t) rnd; line_t sy; LINE_MUL_SCALAR(sy, pvl1, y_luv); // MUL: ng LINE_ADD(pul, pul, sy); } line_t pul0; index_t i_u_l0 = PATH_LINE_IDX(b, k, 1, u); LINE_LOAD(pul0, d_s, i_u_l0); LINE_MUL(pul, pul, pul0); index_t i_u_l = PATH_LINE_IDX(b, k, l, u); LINE_STORE(d_s, i_u_l, pul); // W: ng scalar_t } } trans_bytes += (2*n+m)*sizeof(index_t) + (m+n)*g*sizeof(scalar_t); num_muls += (n*g+m); } scalar_t k_path_genf(index_t n, index_t m, index_t k, index_t g, index_t *d_pos, index_t *d_adj, ffprng_scalar_t y_seed, line_array_t *d_x, scalar_t *vs) { assert(g == SCALARS_IN_LINE); assert(k >= 1); line_array_t *d_s = (line_array_t *) MALLOC(LINE_ARRAY_SIZE(k*n*g)); // Save the base case to d_s #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { line_t xu; LINE_LOAD(xu, d_x, u); // R: ng scalar_t [hw prefetched] index_t i_u_1 = PATH_LINE_IDX(b, k, 1, u); LINE_STORE(d_s, i_u_1, xu); // W: ng scalar_t } // Run the recurrence srand(y_seed); for(index_t l = 2; l <= k; l++) { ffprng_scalar_t yl_seed = irand(); // different y-values for every round k_path_genf_round(n,m,k,g,l,d_pos,d_adj,yl_seed,d_s); } // Sum up scalar_t sum = line_sum_stride(n, g, k, ((line_array_t *)(((line_t *) d_s) + k-1))); // vertex localisation vertex_acc_stride(n, g, k, ((line_array_t *)(((line_t *) d_s) + k-1)), vs); FREE(d_s); trans_bytes += 2*n*g*sizeof(scalar_t); num_muls += 0; return sum; } /************************************************************ The oracle(s). */ index_t path_oracle(index_t n, index_t k, index_t *h_pos, index_t *h_adj, index_t num_shades, shade_map_t *h_s, ffprng_scalar_t y_seed, ffprng_scalar_t z_seed, scalar_t *master_vsum) { push_memtrack(); assert(k >= 1 && k < 31); index_t m = h_pos[n-1]+h_adj[h_pos[n-1]]+1-n; index_t sum_size = 1 << k; index_t g = SCALARS_IN_LINE; index_t outer = (sum_size + g-1) / g; // number of iterations for outer loop num_muls = 0; trans_bytes = 0; index_t *d_pos = h_pos; index_t *d_adj = h_adj; line_array_t *d_x = (line_array_t *) MALLOC(LINE_ARRAY_SIZE(n*g)); /* Run the work & time it. */ push_time(); scalar_t master_sum; SCALAR_SET_ZERO(master_sum); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) master_vsum[i] = 0; for(index_t out = 0; out < outer; out++) { constrained_sieve_pre(n, k, g, g*out, num_shades, h_s, z_seed, d_x); scalar_t sum = k_path_genf(n, m, k, g, d_pos, d_adj, y_seed, d_x, master_vsum); SCALAR_ADD(master_sum, master_sum, sum); } double time = pop_time(); double trans_rate = trans_bytes / (time/1000.0); double mul_rate = num_muls / time; FREE(d_x); fprintf(stdout, SCALAR_FORMAT_STRING " %.2lf ms [%.2lfGiB/s, %.2lfGHz] %d", (long) master_sum, time, trans_rate/((double) (1 << 30)), mul_rate/((double) 1e6), master_sum != 0); fprintf(stdout, " "); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fflush(stdout); return master_sum != 0; } /************************************************* Rudimentary graph builder. */ typedef struct { index_t is_directed; index_t num_vertices; index_t num_edges; index_t max_time; index_t edge_capacity; index_t *edges; index_t *colors; } graph_t; static index_t *enlarge(index_t m, index_t m_was, index_t *was) { assert(m >= 0 && m_was >= 0); index_t *a = (index_t *) MALLOC(sizeof(index_t)*m); index_t i; if(was != (void *) 0) { for(i = 0; i < m_was; i++) { a[i] = was[i]; } FREE(was); } return a; } graph_t *graph_alloc(index_t n) { assert(n >= 0); index_t i; graph_t *g = (graph_t *) MALLOC(sizeof(graph_t)); g->is_directed = 0; // default: undirected graph g->num_vertices = n; g->num_edges = 0; g->edge_capacity = 100; g->edges = enlarge(3*g->edge_capacity, 0, (void *) 0); g->colors = (index_t *) MALLOC(sizeof(index_t)*n); for(i = 0; i < n; i++) g->colors[i] = UNDEFINED; return g; } void graph_free(graph_t *g) { FREE(g->edges); FREE(g->colors); FREE(g); } void graph_add_edge(graph_t *g, index_t u, index_t v, index_t t) { assert(u >= 0 && v >= 0 && u < g->num_vertices && v < g->num_vertices); assert(t>=0); //assert(t>=0 && t < g->max_time); if(g->num_edges == g->edge_capacity) { g->edges = enlarge(6*g->edge_capacity, 3*g->edge_capacity, g->edges); g->edge_capacity *= 2; } assert(g->num_edges < g->edge_capacity); index_t *e = g->edges + 3*g->num_edges; e[0] = u; e[1] = v; e[2] = t; g->num_edges++; } index_t *graph_edgebuf(graph_t *g, index_t cap) { g->edges = enlarge(3*g->edge_capacity+3*cap, 3*g->edge_capacity, g->edges); index_t *e = g->edges + 3*g->num_edges; g->edge_capacity += cap; g->num_edges += cap; return e; } void graph_set_color(graph_t *g, index_t u, index_t c) { assert(u >= 0 && u < g->num_vertices && c >= 0); g->colors[u] = c; } void graph_set_is_directed(graph_t *g, index_t is_dir) { assert(is_dir == 0 || is_dir == 1); g->is_directed = is_dir; } void graph_set_max_time(graph_t *g, index_t tmax) { assert(tmax > 0); g->max_time = tmax; } #ifdef DEBUG void print_graph(graph_t *g) { index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; fprintf(stdout, "p motif %ld %ld %ld\n", n, m, tmax); index_t *e = g->edges; for(index_t i = 0; i < 3*m; i+=3) { fprintf(stdout, "e %ld %ld %ld\n", e[i]+1, e[i+1]+1, e[i+2]+1); } index_t *c = g->colors; for(index_t i = 0; i < n; i++) fprintf(stdout, "n %ld %ld\n", i+1, c[i]+1); } #endif /************************************* Basic motif query processing routines. */ struct temppathq_struct { index_t is_stub; index_t n; index_t k; index_t tmax; index_t *pos; index_t *adj; index_t nl; index_t *l; index_t ns; shade_map_t *shade; index_t vert_loc; scalar_t *vsum; }; typedef struct temppathq_struct temppathq_t; void adjsort(index_t n, index_t *pos, index_t *adj) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t pu = pos[u]; index_t deg = adj[pu]; heapsort_indext(deg, adj + pu + 1); } } void temppathq_free(temppathq_t *q) { if(!q->is_stub) { FREE(q->pos); FREE(q->adj); FREE(q->l); FREE(q->shade); FREE(q->vsum); } FREE(q); } index_t temppathq_execute(temppathq_t *q) { if(q->is_stub) return 0; return temppath_oracle(q->n, q->k, q->tmax, q->pos, q->adj, q->ns, q->shade, irand(), irand(), q->vert_loc, q->vsum); } #ifdef DEBUG void print_temppathq(temppathq_t *q) { index_t n = q->n; index_t k = q->k; index_t tmax = q->tmax; index_t *pos = q->pos; index_t *adj = q->adj; fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "printing temppathq\n"); fprintf(stdout, "is_stub = %ld\n", q->is_stub); fprintf(stdout, "n = %ld\n", n); fprintf(stdout, "k = %ld\n", k); fprintf(stdout, "tmax = %ld\n", tmax); fprintf(stdout, "pos\n"); fprintf(stdout, "----\n "); for(index_t i = 0; i < n*tmax; i++) { fprintf(stdout, "%ld%s", pos[i], i%n==n-1 ? "\n ":" "); } fprintf(stdout, "adjacency list:\n"); fprintf(stdout, "---------------\n"); for(index_t t = 0; t < tmax; t++) { fprintf(stdout, "t: %ld\n", t+1); fprintf(stdout, "---------------\n"); index_t *pos_t = pos + n*t; for(index_t u = 0; u < n; u++) { index_t pu = pos_t[u]; index_t nu = adj[pu]; index_t *adj_u = adj + pu + 1; fprintf(stdout, "%4ld:", u+1); for(index_t i = 0; i < nu; i++) { fprintf(stdout, " %4ld", adj_u[i]+1); } fprintf(stdout, "\n"); } } index_t nl = q->nl; index_t *l = q->l; fprintf(stdout, "nl = %ld\n", nl); fprintf(stdout, "l:\n"); for(index_t i = 0; i < nl; i++) fprintf(stdout, "%8ld : %8ld\n", nl, l[i]); index_t ns = q ->ns; shade_map_t *shade = q->shade; fprintf(stdout, "ns : %ld\n", ns); fprintf(stdout, "shades:\n"); for(index_t u = 0; u < n; u++) { fprintf(stdout, "%10ld : 0x%08X\n", u+1, shade[u]); } scalar_t *vsum = q->vsum; frpintf(stdout, "vert_loc: %ld\n", q->vert_loc); fprintf(stdout, "vsum:\n"); for(index_t u = 0; u < n; u++) fprintf(stdout, "%10ld : "SCALAR_FORMAT_STRING"\n", u+1, vsum[u]); fprintf(stdout, "-----------------------------------------------\n"); } void print_array(const char *name, index_t n, index_t *a, index_t offset) { fprintf(stdout, "%s (%ld):", name, n); for(index_t i = 0; i < n; i++) { fprintf(stdout, " %ld", a[i] == -1 ? -1 : a[i]+offset); } fprintf(stdout, "\n"); } #endif /*************************************************** basic path query routine */ struct pathq_struct { index_t is_stub; index_t n; index_t k; index_t *pos; index_t *adj; index_t nl; index_t *l; index_t ns; shade_map_t *shade; scalar_t *vsum; }; typedef struct pathq_struct pathq_t; void pathq_free(pathq_t *q) { if(!q->is_stub) { FREE(q->pos); FREE(q->adj); FREE(q->l); FREE(q->shade); FREE(q->vsum); } FREE(q); } #ifdef DEBUG void print_pathq(pathq_t *q) { index_t n = q->n; index_t k = q->k; index_t *pos = q->pos; index_t *adj = q->adj; index_t nl = q->nl; index_t *l = q->l; index_t ns = q ->ns; shade_map_t *shade = q->shade; scalar_t *vsum = q->vsum; fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "printing pathq\n"); fprintf(stdout, "is_stub : %ld\n", q->is_stub); fprintf(stdout, "n : %ld\n", n); fprintf(stdout, "k : %ld\n", k); fprintf(stdout, "pos\n"); fprintf(stdout, "----\n "); for(index_t i = 0; i < n; i++) { fprintf(stdout, "%4ld%s", pos[i], i%n==n-1 ? "\n ":" "); } fprintf(stdout, "adjacency list:\n"); fprintf(stdout, "---------------\n"); for(index_t u = 0; u < n; u++) { index_t pu = pos[u]; index_t nu = adj[pu]; index_t *adj_u = adj + pu + 1; fprintf(stdout, "%4ld:", u+1); for(index_t i = 0; i < nu; i++) { fprintf(stdout, " %4ld", adj_u[i]+1); } fprintf(stdout, "\n"); } fprintf(stdout, "nl = %ld\n", nl); fprintf(stdout, "l:\n"); for(index_t i = 0; i < nl; i++) fprintf(stdout, "%8ld : %8ld\n", nl, l[i]); fprintf(stdout, "ns : %ld\n", ns); fprintf(stdout, "shades:\n"); for(index_t u = 0; u < n; u++) { fprintf(stdout, "%10ld : 0x%08X\n", u+1, shade[u]); } fprintf(stdout, "vsum:\n"); for(index_t u = 0; u < n; u++) fprintf(stdout, "%10ld : "SCALAR_FORMAT_STRING"\n", u+1, vsum[u]); fprintf(stdout, "-----------------------------------------------\n"); } #endif pathq_t * build_pathq(temppathq_t *in) { push_memtrack(); index_t n = in->n; index_t tmax = in->tmax; index_t *i_pos = in->pos; index_t *i_adj = in->adj; shade_map_t *i_shade = in->shade; push_time(); fprintf(stdout, "build pathq: "); fflush(stdout); push_time(); // output position list index_t *c_pos = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) c_pos[u] = 0; for(index_t t = 0; t < tmax; t++) { index_t *i_pos_t = i_pos + t*n; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; c_pos[u] += i_nu; } } index_t c_m = parallelsum(n, c_pos); index_t c_run = prefixsum(n, c_pos, 1); assert(c_run == n+c_m); fprintf(stdout, "[pos: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); index_t *c_adj = (index_t *) MALLOC(sizeof(index_t)*(n+c_m)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) c_adj[c_pos[u]] = 0; for(index_t t = 0; t < tmax; t++) { index_t *i_pos_t = i_pos + t*n; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; index_t o_pu = c_pos[u]; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; c_adj[o_pu + 1 + c_adj[o_pu]++] = v; } } } adjsort(n, c_pos, c_adj); index_t *o_pos = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_pos[u] = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t c_pu = c_pos[u]; index_t c_nu = c_adj[c_pu]; if(c_nu == 0 || c_nu == 1) { o_pos[u] = c_nu; continue; } o_pos[u] = 1; index_t *c_adj_u = c_adj + c_pu; for(index_t j = 2; j <= c_nu; j++) { if(c_adj_u[j-1] != c_adj_u[j]) { o_pos[u]++; } } } index_t o_m = parallelsum(n, o_pos); index_t o_run = prefixsum(n, o_pos, 1); assert(o_run==n+o_m); index_t *o_adj = (index_t *) MALLOC(sizeof(index_t)*(n+o_m)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_adj[o_pos[u]] = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t c_pu = c_pos[u]; index_t c_nu = c_adj[c_pu]; if(c_nu == 0) continue; index_t o_pu = o_pos[u]; index_t *c_adj_u = c_adj + c_pu; o_adj[o_pu + 1 + o_adj[o_pu]++] = c_adj_u[1]; for(index_t j = 2; j <= c_nu; j++) { if(c_adj_u[j-1] != c_adj_u[j]) { o_adj[o_pu + 1 + o_adj[o_pu]++] = c_adj_u[j]; } } } fprintf(stdout, "[adj: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); shade_map_t *o_shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_shade[u] = i_shade[u]; fprintf(stdout, "[shade: %.2lf ms] ", pop_time()); fprintf(stdout, "done. [%.2lf ms] ", pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); FREE(c_pos); FREE(c_adj); pathq_t *out = (pathq_t *) MALLOC(sizeof(pathq_t)); out->is_stub = 0; out->n = n; out->k = in->k; out->pos = o_pos; out->adj = o_adj; out->nl = 0; out->l = (index_t *) MALLOC(sizeof(index_t)*out->nl); out->ns = in->ns; out->shade = o_shade; out->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*n); return out; } // A quick fix to support vertex localised sieving for undirected graphs pathq_t * build_pathq_dir(temppathq_t *in) { push_memtrack(); index_t n = in->n; index_t tmax = in->tmax; index_t *i_pos = in->pos; index_t *i_adj = in->adj; shade_map_t *i_shade = in->shade; push_time(); fprintf(stdout, "build pathq: "); fflush(stdout); push_time(); // output position list index_t *c_pos = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) c_pos[u] = 0; for(index_t t = 0; t < tmax; t++) { index_t *i_pos_t = i_pos + t*n; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; c_pos[u] += i_nu; } } index_t c_m = parallelsum(n, c_pos); index_t c_run = prefixsum(n, c_pos, 1); assert(c_run == n+c_m); fprintf(stdout, "[pos: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); index_t *c_adj = (index_t *) MALLOC(sizeof(index_t)*(n+c_m)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) c_adj[c_pos[u]] = 0; for(index_t t = 0; t < tmax; t++) { index_t *i_pos_t = i_pos + t*n; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; index_t o_pu = c_pos[u]; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; c_adj[o_pu + 1 + c_adj[o_pu]++] = v; } } } adjsort(n, c_pos, c_adj); index_t *o_pos = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_pos[u] = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t c_pu = c_pos[u]; index_t c_nu = c_adj[c_pu]; if(c_nu == 0 || c_nu == 1) { o_pos[u] = c_nu; continue; } o_pos[u] = 1; index_t *c_adj_u = c_adj + c_pu; for(index_t j = 2; j <= c_nu; j++) { if(c_adj_u[j-1] != c_adj_u[j]) { o_pos[u]++; } } } index_t o_m = parallelsum(n, o_pos); index_t o_run = prefixsum(n, o_pos, 1); assert(o_run==n+o_m); index_t *o_adj = (index_t *) MALLOC(sizeof(index_t)*(n+o_m)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_adj[o_pos[u]] = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t c_pu = c_pos[u]; index_t c_nu = c_adj[c_pu]; if(c_nu == 0) continue; index_t o_pu = o_pos[u]; index_t *c_adj_u = c_adj + c_pu; o_adj[o_pu + 1 + o_adj[o_pu]++] = c_adj_u[1]; for(index_t j = 2; j <= c_nu; j++) { if(c_adj_u[j-1] != c_adj_u[j]) { o_adj[o_pu + 1 + o_adj[o_pu]++] = c_adj_u[j]; } } } // convert directed to undirected graph index_t *o_pos_ud = (index_t *) MALLOC(n*sizeof(index_t)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_pos_ud[u] = o_adj[o_pos[u]]; index_t nt = num_threads(); index_t block_size = n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t u = 0; u < n; u++) { index_t o_pu = o_pos[u]; index_t *o_adj_u = o_adj + o_pu; index_t o_nu = o_adj_u[0]; for(index_t j = 1; j <= o_nu; j++) { index_t v = o_adj_u[j]; if(start <= v && v <= stop) o_pos_ud[v]++; } } } index_t o_m_ud = parallelsum(n, o_pos_ud); index_t o_run_ud = prefixsum(n, o_pos_ud, 1); assert(o_run_ud == n+o_m_ud); assert(o_m_ud == 2*o_m); index_t *o_adj_ud = (index_t *) MALLOC((n+o_m_ud)*sizeof(index_t)); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_adj_ud[o_pos_ud[u]] = 0; // first copy the adjacency list as it is #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t o_pu = o_pos[u]; index_t *o_adj_u = o_adj + o_pu; index_t o_nu = o_adj_u[0]; index_t o_pu_ud = o_pos_ud[u]; index_t *o_adj_ud_u = o_adj_ud + o_pu_ud; o_adj_ud_u[0] = o_nu; for(index_t j = 1; j <= o_nu; j++) { index_t v = o_adj_u[j]; o_adj_ud_u[j] = v; } } // add edges in other direction now #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t u = 0; u < n; u++) { index_t o_pu = o_pos[u]; index_t *o_adj_u = o_adj + o_pu; index_t o_nu = o_adj_u[0]; for(index_t j = 1; j <= o_nu; j++) { index_t v = o_adj_u[j]; if(start <= v && v <= stop) { index_t o_pv_ud = o_pos_ud[v]; o_adj_ud[o_pv_ud + 1 + o_adj_ud[o_pv_ud]++] = u; } } } } FREE(o_pos); FREE(o_adj); fprintf(stdout, "[adj: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); shade_map_t *o_shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) o_shade[u] = i_shade[u]; fprintf(stdout, "[shade: %.2lf ms] ", pop_time()); fprintf(stdout, "done. [%.2lf ms] ", pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); FREE(c_pos); FREE(c_adj); pathq_t *out = (pathq_t *) MALLOC(sizeof(pathq_t)); out->is_stub = 0; out->n = n; out->k = in->k; out->pos = o_pos_ud; out->adj = o_adj_ud; out->nl = 0; out->l = (index_t *) MALLOC(sizeof(index_t)*out->nl); out->ns = in->ns; out->shade = o_shade; out->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*n); return out; } scalar_t pathq_execute(pathq_t *q) { if(q->is_stub) return 0; return path_oracle(q->n, q->k, q->pos, q->adj, q->ns, q->shade, irand(), irand(), q->vsum); } /*************** Project a query by cutting out a given interval of vertices. */ index_t get_poscut(index_t n, index_t tmax, index_t *pos, index_t *adj, index_t lo_v, index_t hi_v, index_t *poscut) { // Note: assumes the adjacency lists are sorted assert(lo_v <= hi_v); index_t ncut = n - (hi_v-lo_v+1); for(index_t t = 0; t < tmax; t++) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < lo_v; u++) { index_t pu = pos[t*n + u]; index_t deg = adj[pu]; index_t cs, ce; index_t l = get_interval(deg, adj + pu + 1, lo_v, hi_v, &cs, &ce); poscut[t*ncut + u] = deg - l; } } for(index_t t = 0; t < tmax; t++) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = hi_v+1; u < n; u++) { index_t pu = pos[t*n + u]; index_t deg = adj[pu]; index_t cs, ce; index_t l = get_interval(deg, adj + pu + 1, lo_v, hi_v, &cs, &ce); poscut[t*ncut + (u-hi_v-1+lo_v)] = deg - l; } } index_t run = prefixsum(tmax*ncut, poscut, 1); return run; } temppathq_t *temppathq_cut(temppathq_t *q, index_t lo_v, index_t hi_v) { // Note: assumes the adjacency lists are sorted //fprintf(stdout, "-------------------------------\n"); //fprintf(stdout, "low: %ld, high: %ld\n", lo_v, hi_v); //print_temppathq(q); index_t n = q->n; index_t tmax = q->tmax; index_t *pos = q->pos; index_t *adj = q->adj; assert(0 <= lo_v && lo_v <= hi_v && hi_v < n); // Fast-forward a stub NO when the interval // [lo_v,hi_v] contains an element in q->l for(index_t i = 0; i < q->nl; i++) { if(q->l[i] >= lo_v && q->l[i] <= hi_v) { temppathq_t *qs = (temppathq_t *) MALLOC(sizeof(temppathq_t)); qs->is_stub = 1; return qs; } } index_t ncut = n - (hi_v-lo_v+1); // number of vertices after cut index_t *poscut = alloc_idxtab(tmax*ncut); index_t bcut = get_poscut(n, tmax, pos, adj, lo_v, hi_v, poscut); index_t *adjcut = alloc_idxtab(bcut); index_t gap = hi_v-lo_v+1; //print_array("poscut", tmax*ncut, poscut, 0); for(index_t t = 0; t < tmax; t++) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t v = 0; v < ncut; v++) { index_t u = v; if(u >= lo_v) u += gap; index_t pu = pos[t*n + u]; index_t degu = adj[pu]; index_t cs, ce; index_t l = get_interval(degu, adj + pu + 1, lo_v, hi_v, &cs, &ce); index_t pv = poscut[t*ncut + v]; index_t degv = degu - l; adjcut[pv] = degv; // could parallelize this too for(index_t i = 0; i < cs; i++) adjcut[pv + 1 + i] = adj[pu + 1 + i]; // could parallelize this too for(index_t i = cs; i < degv; i++) adjcut[pv + 1 + i] = adj[pu + 1 + i + l] - gap; } } //print_array("adj_cut", bcut, adjcut, 0); temppathq_t *qq = (temppathq_t *) MALLOC(sizeof(temppathq_t)); qq->is_stub = 0; qq->n = ncut; qq->k = q->k; qq->tmax = q->tmax; qq->pos = poscut; qq->adj = adjcut; qq->nl = q->nl; qq->l = (index_t *) MALLOC(sizeof(index_t)*qq->nl); for(index_t i = 0; i < qq->nl; i++) { index_t u = q->l[i]; assert(u < lo_v || u > hi_v); if(u > hi_v) u -= gap; qq->l[i] = u; } qq->ns = q->ns; qq->shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*ncut); for(index_t v = 0; v < ncut; v++) { index_t u = v; if(u >= lo_v) u += gap; qq->shade[v] = q->shade[u]; } qq->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*ncut); //print_temppathq(qq); //exit(0); return qq; } /****************** Project a query with given projection & embedding arrays. */ #define PROJ_UNDEF 0xFFFFFFFFFFFFFFFFUL index_t get_posproj(index_t n, index_t *pos, index_t *adj, index_t nproj, index_t *proj, index_t *embed, index_t *posproj) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t v = 0; v < nproj; v++) { index_t u = embed[v]; index_t pu = pos[u]; index_t deg = adj[pu]; index_t degproj = 0; for(index_t i = 0; i < deg; i++) { index_t w = proj[adj[pu + 1 + i]]; if(w != PROJ_UNDEF) degproj++; } posproj[v] = degproj; } index_t run = prefixsum(nproj, posproj, 1); return run; } temppathq_t *temppathq_project(temppathq_t *q, index_t nproj, index_t *proj, index_t *embed, index_t nl, index_t *l) { index_t n = q->n; index_t *pos = q->pos; index_t *adj = q->adj; index_t *posproj = alloc_idxtab(nproj); index_t bproj = get_posproj(n, pos, adj, nproj, proj, embed, posproj); index_t *adjproj = alloc_idxtab(bproj); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t v = 0; v < nproj; v++) { index_t pv = posproj[v]; index_t u = embed[v]; index_t pu = pos[u]; index_t deg = adj[pu]; index_t degproj = 0; for(index_t i = 0; i < deg; i++) { index_t w = proj[adj[pu + 1 + i]]; if(w != PROJ_UNDEF) adjproj[pv + 1 + degproj++] = w; } adjproj[pv] = degproj; } temppathq_t *qq = (temppathq_t *) MALLOC(sizeof(temppathq_t)); qq->is_stub = 0; qq->n = nproj; qq->k = q->k; qq->pos = posproj; qq->adj = adjproj; // Now project the l array assert(q->nl == 0); // l array comes from lister qq->nl = nl; qq->l = (index_t *) MALLOC(sizeof(index_t)*nl); for(index_t i = 0; i < nl; i++) { index_t u = proj[l[i]]; assert(u != PROJ_UNDEF); // query is a trivial NO ! qq->l[i] = u; } // Next set up the projected shades qq->ns = q->ns; qq->shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*nproj); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t v = proj[u]; if(v != PROJ_UNDEF) qq->shade[v] = q->shade[u]; } // Reserve a unique shade to every vertex in l // while keeping the remaining shades available // Reserve shades first ... index_t *l_shade = (index_t *) MALLOC(sizeof(index_t)*nl); shade_map_t reserved_shades = 0; for(index_t i = 0; i < nl; i++) { index_t v = qq->l[i]; index_t j = 0; for(; j < qq->ns; j++) if(((qq->shade[v] >> j)&1) == 1 && ((reserved_shades >> j)&1) == 0) break; assert(j < qq->ns); reserved_shades |= 1UL << j; l_shade[i] = j; } // ... then clear all reserved shades in one pass #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t v = 0; v < nproj; v++) qq->shade[v] &= ~reserved_shades; // ... and finally set reserved shades for(index_t i = 0; i < nl; i++) { index_t v = qq->l[i]; qq->shade[v] = 1UL << l_shade[i]; } FREE(l_shade); return qq; } /**************************************************** The interval extractor. */ struct ivlist_struct { index_t start; index_t end; struct ivlist_struct *prev; struct ivlist_struct *next; }; typedef struct ivlist_struct ivlist_t; typedef struct ivext_struct { index_t n; index_t k; ivlist_t *queue; ivlist_t *active_queue_head; ivlist_t *spare_queue_head; ivlist_t *embed_list; } ivext_t; void ivext_enqueue_spare(ivext_t *e, ivlist_t *iv) { pnlinknext(e->spare_queue_head,iv); } void ivext_enqueue_active(ivext_t *e, ivlist_t *iv) { pnlinkprev(e->active_queue_head,iv); } ivlist_t *ivext_dequeue_first_nonsingleton(ivext_t *e) { ivlist_t *iv = e->active_queue_head->next; for(; iv != e->active_queue_head; iv = iv->next) if(iv->end - iv->start + 1 > 1) break; assert(iv != e->active_queue_head); pnunlink(iv); return iv; } ivlist_t *ivext_get_spare(ivext_t *e) { assert(e->spare_queue_head->next != e->spare_queue_head); ivlist_t *iv = e->spare_queue_head->next; pnunlink(iv); return iv; } void ivext_reset(ivext_t *e) { e->active_queue_head = e->queue + 0; e->spare_queue_head = e->queue + 1; e->active_queue_head->next = e->active_queue_head; e->active_queue_head->prev = e->active_queue_head; e->spare_queue_head->prev = e->spare_queue_head; e->spare_queue_head->next = e->spare_queue_head; e->embed_list = (ivlist_t *) 0; for(index_t i = 0; i < e->k + 2; i++) ivext_enqueue_spare(e, e->queue + 2 + i); // rot-safe ivlist_t *iv = ivext_get_spare(e); iv->start = 0; iv->end = e->n-1; ivext_enqueue_active(e, iv); } ivext_t *ivext_alloc(index_t n, index_t k) { ivext_t *e = (ivext_t *) MALLOC(sizeof(ivext_t)); e->n = n; e->k = k; e->queue = (ivlist_t *) MALLOC(sizeof(ivlist_t)*(k+4)); // rot-safe ivext_reset(e); return e; } void ivext_free(ivext_t *e) { ivlist_t *el = e->embed_list; while(el != (ivlist_t *) 0) { ivlist_t *temp = el; el = el->next; FREE(temp); } FREE(e->queue); FREE(e); } void ivext_project(ivext_t *e, ivlist_t *iv) { for(ivlist_t *z = e->active_queue_head->next; z != e->active_queue_head; z = z->next) { assert(z->end < iv->start || z->start > iv->end); if(z->start > iv->end) { z->start -= iv->end-iv->start+1; z->end -= iv->end-iv->start+1; } } ivlist_t *em = (ivlist_t *) MALLOC(sizeof(ivlist_t)); em->start = iv->start; em->end = iv->end; em->next = e->embed_list; e->embed_list = em; } index_t ivext_embed(ivext_t *e, index_t u) { ivlist_t *el = e->embed_list; while(el != (ivlist_t *) 0) { if(u >= el->start) u += el->end - el->start + 1; el = el->next; } return u; } ivlist_t *ivext_halve(ivext_t *e, ivlist_t *iv) { assert(iv->end - iv->start + 1 >= 2); index_t mid = (iv->start + iv->end)/2; // mid < iv->end ivlist_t *h = ivext_get_spare(e); h->start = iv->start; h->end = mid; iv->start = mid+1; return h; } index_t ivext_queue_size(ivext_t *e) { index_t s = 0; for(ivlist_t *iv = e->active_queue_head->next; iv != e->active_queue_head; iv = iv->next) s += iv->end-iv->start+1; return s; } index_t ivext_num_active_intervals(ivext_t *e) { index_t s = 0; for(ivlist_t *iv = e->active_queue_head->next; iv != e->active_queue_head; iv = iv->next) s++; return s; } void ivext_queue_print(FILE *out, ivext_t *e, index_t rot) { index_t j = 0; char x[16384]; char y[16384]; y[0] = '\0'; sprintf(x, "%c%12ld [", rot == 0 ? ' ' : 'R', ivext_queue_size(e)); strcat(y, x); for(ivlist_t *iv = e->active_queue_head->next; iv != e->active_queue_head; iv = iv->next) { assert(iv->start <= iv->end); if(iv->start < iv->end) sprintf(x, "%s[%ld:%ld]", j++ == 0 ? "" : ",", ivext_embed(e, iv->start), ivext_embed(e, iv->end)); else sprintf(x, "%s[%ld]", j++ == 0 ? "[" : ",", ivext_embed(e, iv->start)); strcat(y, x); } strcat(y, "] "); fprintf(out, "%-120s", y); fflush(out); } index_t extract_match(index_t is_root, temppathq_t *query, index_t *match) { // Assumes adjancency lists of query are sorted. fprintf(stdout, "extract: %ld %ld %ld\n", query->n, query->k, query->nl); push_time(); assert(query->k <= query->n); ivext_t *e = ivext_alloc(query->n, query->k); ivext_queue_print(stdout, e, 0); if(!temppathq_execute(query)) { fprintf(stdout, " -- false\n"); ivext_free(e); if(!is_root) temppathq_free(query); double time = pop_time(); fprintf(stdout, "extract done [%.2lf ms]\n", time); return 0; } fprintf(stdout, " -- true\n"); while(ivext_queue_size(e) > e->k) { ivlist_t *iv = ivext_dequeue_first_nonsingleton(e); ivlist_t *h = ivext_halve(e, iv); ivext_enqueue_active(e, iv); temppathq_t *qq = temppathq_cut(query, h->start, h->end); ivext_queue_print(stdout, e, 0); if(temppathq_execute(qq)) { fprintf(stdout, " -- true\n"); if(!is_root) temppathq_free(query); query = qq; is_root = 0; ivext_project(e, h); ivext_enqueue_spare(e, h); } else { fprintf(stdout, " -- false\n"); temppathq_free(qq); pnunlink(iv); ivext_enqueue_active(e, h); qq = temppathq_cut(query, iv->start, iv->end); ivext_queue_print(stdout, e, 0); if(temppathq_execute(qq)) { fprintf(stdout, " -- true\n"); if(!is_root) temppathq_free(query); query = qq; is_root = 0; ivext_project(e, iv); ivext_enqueue_spare(e, iv); } else { fprintf(stdout, " -- false\n"); temppathq_free(qq); ivext_enqueue_active(e, iv); while(ivext_num_active_intervals(e) > e->k) { // Rotate queue until outlier is out ... ivlist_t *iv = e->active_queue_head->next; pnunlink(iv); qq = temppathq_cut(query, iv->start, iv->end); ivext_queue_print(stdout, e, 1); if(temppathq_execute(qq)) { fprintf(stdout, " -- true\n"); if(!is_root) temppathq_free(query); query = qq; is_root = 0; ivext_project(e, iv); ivext_enqueue_spare(e, iv); } else { fprintf(stdout, " -- false\n"); temppathq_free(qq); ivext_enqueue_active(e, iv); } } } } } for(index_t i = 0; i < query->k; i++) match[i] = ivext_embed(e, i); ivext_free(e); if(!is_root) temppathq_free(query); double time = pop_time(); fprintf(stdout, "extract done [%.2lf ms]\n", time); return 1; } /**************************************************************** The lister. */ #define M_QUERY 0 #define M_OPEN 1 #define M_CLOSE 2 #define M_REWIND_U 3 #define M_REWIND_L 4 index_t command_mnemonic(index_t command) { return command >> 60; } index_t command_index(index_t command) { return command & (~(0xFFUL<<60)); } index_t to_command_idx(index_t mnemonic, index_t idx) { assert(idx < (1UL << 60)); return (mnemonic << 60)|idx; } index_t to_command(index_t mnemonic) { return to_command_idx(mnemonic, 0UL); } typedef struct { index_t n; // number of elements in universe index_t k; // size of the sets to be listed index_t *u; // upper bound as a bitmap index_t u_size; // size of upper bound index_t *l; // lower bound index_t l_size; // size of lower bound index_t *stack; // a stack for maintaining state index_t stack_capacity; // ... the capacity of the stack index_t top; // index of stack top temppathq_t *root; // the root query } lister_t; void lister_push(lister_t *t, index_t word) { assert(t->top + 1 < t->stack_capacity); t->stack[++t->top] = word; } index_t lister_pop(lister_t *t) { return t->stack[t->top--]; } index_t lister_have_work(lister_t *t) { return t->top >= 0; } index_t lister_in_l(lister_t *t, index_t j) { for(index_t i = 0; i < t->l_size; i++) if(t->l[i] == j) return 1; return 0; } void lister_push_l(lister_t *t, index_t j) { assert(!lister_in_l(t, j) && t->l_size < t->k); t->l[t->l_size++] = j; } void lister_pop_l(lister_t *t) { assert(t->l_size > 0); t->l_size--; } void lister_reset(lister_t *t) { t->l_size = 0; t->top = -1; lister_push(t, to_command(M_QUERY)); for(index_t i = 0; i < t->n; i++) bitset(t->u, i, 1); t->u_size = t->n; } lister_t *lister_alloc(index_t n, index_t k, temppathq_t *root) { assert(n >= 1 && n < (1UL << 60) && k >= 1 && k <= n); lister_t *t = (lister_t *) MALLOC(sizeof(lister_t)); t->n = n; t->k = k; t->u = alloc_idxtab((n+63)/64); t->l = alloc_idxtab(k); t->stack_capacity = n + k*(k+1+2*k) + 1; t->stack = alloc_idxtab(t->stack_capacity); lister_reset(t); t->root = root; if(t->root != (temppathq_t *) 0) { assert(t->root->n == t->n); assert(t->root->k == t->k); assert(t->root->nl == 0); } return t; } void lister_free(lister_t *t) { if(t->root != (temppathq_t *) 0) temppathq_free(t->root); FREE(t->u); FREE(t->l); FREE(t->stack); FREE(t); } void lister_get_proj_embed(lister_t *t, index_t **proj_out, index_t **embed_out) { index_t n = t->n; index_t usize = t->u_size; index_t *embed = (index_t *) MALLOC(sizeof(index_t)*usize); index_t *proj = (index_t *) MALLOC(sizeof(index_t)*n); // could parallelize this (needs parallel prefix sum) index_t run = 0; for(index_t i = 0; i < n; i++) { if(bitget(t->u, i)) { proj[i] = run; embed[run] = i; run++; } else { proj[i] = PROJ_UNDEF; } } assert(run == usize); *proj_out = proj; *embed_out = embed; } void lister_query_setup(lister_t *t, temppathq_t **q_out, index_t **embed_out) { index_t *proj; index_t *embed; // set up the projection with u and l lister_get_proj_embed(t, &proj, &embed); temppathq_t *qq = temppathq_project(t->root, t->u_size, proj, embed, t->l_size, t->l); FREE(proj); *q_out = qq; *embed_out = embed; } index_t lister_extract(lister_t *t, index_t *s) { // assumes t->u contains all elements of t->l // (otherwise query is trivial no) assert(t->root != (temppathq_t *) 0); if(t->u_size == t->n) { // rush the root query without setting up a copy return extract_match(1, t->root, s); } else { // a first order of business is to set up the query // based on the current t->l and t->u; this includes // also setting up the embedding back to the root, // in case we are lucky and actually discover a match temppathq_t *qq; // will be released by extractor index_t *embed; lister_query_setup(t, &qq, &embed); // now execute the interval extractor ... index_t got_match = extract_match(0, qq, s); // ... and embed the match (if any) if(got_match) { for(index_t i = 0; i < t->k; i++) s[i] = embed[s[i]]; } FREE(embed); return got_match; } } index_t lister_run(lister_t *t, index_t *s) { while(lister_have_work(t)) { index_t cmd = lister_pop(t); index_t mnem = command_mnemonic(cmd); index_t idx = command_index(cmd); switch(mnem) { case M_QUERY: if(t->k <= t->u_size && lister_extract(t, s)) { // we have discovered a match, which we need to // put on the stack to continue work when the user // requests this for(index_t i = 0; i < t->k; i++) lister_push(t, s[i]); lister_push(t, to_command_idx(M_OPEN, t->k-1)); // now report our discovery to user return 1; } break; case M_OPEN: { index_t *x = t->stack + t->top - t->k + 1; index_t k = 0; for(; k < idx; k++) if(!lister_in_l(t, x[k])) break; if(k == idx) { // opening on last element of x not in l // so we can dispense with x as long as we remember to // insert x[idx] back to u when rewinding for(index_t j = 0; j < t->k; j++) lister_pop(t); // axe x from stack if(!lister_in_l(t, x[idx])) { bitset(t->u, x[idx], 0); // remove x[idx] from u t->u_size--; lister_push(t, to_command_idx(M_REWIND_U, x[idx])); lister_push(t, to_command(M_QUERY)); } } else { // have still other elements of x that we need to // open on, so must keep x in stack // -- // invariant that controls stack size: // each open increases l by at least one lister_push(t, to_command_idx(M_CLOSE, idx)); if(!lister_in_l(t, x[idx])) { bitset(t->u, x[idx], 0); // remove x[idx] from u t->u_size--; lister_push(t, to_command_idx(M_REWIND_U, x[idx])); // force x[0],x[1],...,x[idx-1] to l index_t j = 0; for(; j < idx; j++) { if(!lister_in_l(t, x[j])) { if(t->l_size >= t->k) break; lister_push_l(t, x[j]); lister_push(t, to_command_idx(M_REWIND_L, x[j])); } } if(j == idx) lister_push(t, to_command(M_QUERY)); } } } break; case M_CLOSE: assert(idx > 0); lister_push(t, to_command_idx(M_OPEN, idx-1)); break; case M_REWIND_U: bitset(t->u, idx, 1); t->u_size++; break; case M_REWIND_L: lister_pop_l(t); break; } } lister_push(t, to_command(M_QUERY)); return 0; } /******************************************************** Root query builder. */ // Query builder for directed graphs // temppathq_t *build_temppathq_dir(graph_t *g, index_t k, index_t *kk) { push_memtrack(); index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; index_t *pos = alloc_idxtab(n*tmax); index_t *adj = alloc_idxtab(n*tmax+2*m); index_t ns = k; shade_map_t *shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); temppathq_t *root = (temppathq_t *) MALLOC(sizeof(temppathq_t)); root->is_stub = 0; root->n = g->num_vertices; root->k = k; root->tmax = tmax; root->pos = pos; root->adj = adj; root->nl = 0; root->l = (index_t *) MALLOC(sizeof(index_t)*root->nl); root->ns = ns; root->shade = shade; root->vert_loc = 0; root->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*root->n); assert(tmax >= k-1); push_time(); fprintf(stdout, "build query: "); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) pos[u] = 0; double time = pop_time(); fprintf(stdout, "[zero: %.2lf ms] ", time); fflush(stdout); push_time(); index_t *e = g->edges; #ifdef BUILD_PARALLEL // Parallel occurrence count // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges index_t nt = num_threads(); index_t block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { //index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = (pos + (n*t)); //if(start <= u && u <= stop) { // // I am responsible for u, record adjacency to u // pos_t[u]++; //} if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v pos_t[v]++; } } } #else for(index_t j = 0; j < 3*m; j+=3) { //index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = pos + n*t; //pos_t[u]++; pos_t[v]++; } #endif index_t run = prefixsum(n*tmax, pos, 1); assert(run == (n*tmax+m)); time = pop_time(); fprintf(stdout, "[pos: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) adj[pos[u]] = 0; e = g->edges; #ifdef BUILD_PARALLEL // Parallel aggregation to bins // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges nt = num_threads(); block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; //if(start <= u && u <= stop) { // // I am responsible for u, record adjacency to u // index_t pu = pos[n*t+u]; // adj[pu + 1 + adj[pu]++] = v; //} if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v index_t pv = pos[n*t+v]; adj[pv + 1 + adj[pv]++] = u; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; //index_t pu = pos[n*t+u]; index_t pv = pos[n*t+v]; //adj[pu + 1 + adj[pu]++] = v; adj[pv + 1 + adj[pv]++] = u; } #endif time = pop_time(); fprintf(stdout, "[adj: %.2lf ms] ", time); fflush(stdout); //print_temppathq(root); push_time(); adjsort(n*tmax, pos, adj); time = pop_time(); fprintf(stdout, "[adjsort: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { shade_map_t s = 0; for(index_t j = 0; j < k; j++) if(g->colors[u] == kk[j]) s |= 1UL << j; shade[u] = s; //fprintf(stdout, "%4ld: 0x%08X\n", u, shade[u]); } time = pop_time(); fprintf(stdout, "[shade: %.2lf ms] ", time); fflush(stdout); time = pop_time(); fprintf(stdout, "done. [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); return root; } // Query builder for undirected graphs // temppathq_t *build_temppathq(graph_t *g, index_t k, index_t *kk) { push_memtrack(); index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; index_t *pos = alloc_idxtab(n*tmax); index_t *adj = alloc_idxtab(n*tmax+2*m); index_t ns = k; shade_map_t *shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); temppathq_t *root = (temppathq_t *) MALLOC(sizeof(temppathq_t)); root->is_stub = 0; root->n = g->num_vertices; root->k = k; root->tmax = tmax; root->pos = pos; root->adj = adj; root->nl = 0; root->l = (index_t *) MALLOC(sizeof(index_t)*root->nl); root->ns = ns; root->shade = shade; root->vert_loc = 0; root->vsum = (scalar_t *) MALLOC(sizeof(index_t)*root->n); assert(tmax >= k-1); push_time(); fprintf(stdout, "build query: "); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) pos[u] = 0; double time = pop_time(); fprintf(stdout, "[zero: %.2lf ms] ", time); fflush(stdout); push_time(); index_t *e = g->edges; #ifdef BUILD_PARALLEL // Parallel occurrence count // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges index_t nt = num_threads(); index_t block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = (pos + (n*t)); if(start <= u && u <= stop) { // I am responsible for u, record adjacency to u pos_t[u]++; } if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v pos_t[v]++; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = pos + n*t; pos_t[u]++; pos_t[v]++; } #endif index_t run = prefixsum(n*tmax, pos, 1); assert(run == (n*tmax+2*m)); time = pop_time(); fprintf(stdout, "[pos: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) { adj[pos[u]] = 0; } e = g->edges; #ifdef BUILD_PARALLEL // Parallel aggregation to bins // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges nt = num_threads(); block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; if(start <= u && u <= stop) { // I am responsible for u, record adjacency to u index_t pu = pos[n*t+u]; adj[pu + 1 + adj[pu]++] = v; } if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v index_t pv = pos[n*t+v]; adj[pv + 1 + adj[pv]++] = u; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; index_t pu = pos[n*t+u]; index_t pv = pos[n*t+v]; adj[pu + 1 + adj[pu]++] = v; adj[pv + 1 + adj[pv]++] = u; } #endif time = pop_time(); fprintf(stdout, "[adj: %.2lf ms] ", time); fflush(stdout); push_time(); adjsort(n*tmax, pos, adj); time = pop_time(); fprintf(stdout, "[adjsort: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { shade_map_t s = 0; for(index_t j = 0; j < k; j++) if(g->colors[u] == kk[j]) s |= 1UL << j; shade[u] = s; // fprintf(stdout, "%4ld: 0x%08X\n", u, shade[u]); } time = pop_time(); fprintf(stdout, "[shade: %.2lf ms] ", time); fflush(stdout); time = pop_time(); fprintf(stdout, "done. [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); //print_temppathq(root); return root; } void query_pre_mk1(temppathq_t *in, temppathq_t **out_q, index_t **out_map) { push_memtrack(); index_t nt = num_threads(); index_t i_n = in->n; index_t k = in->k; index_t tmax = in->tmax; index_t *i_pos = in->pos; index_t *i_adj = in->adj; index_t ns = in->ns; shade_map_t *i_shade = in->shade; push_time(); fprintf(stdout, "query pre [1]: "); fflush(stdout); push_time(); // input-to-output vertex map index_t *v_map_i2o = (index_t *) MALLOC(sizeof(index_t)*i_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) v_map_i2o[u] = UNDEFINED; index_t v_cnt = 0; #ifdef BUILD_PARALLEL // parallely construct input-to-output vertex map index_t block_size = i_n/nt; index_t t_vcnt[nt]; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); t_vcnt[th] = 0; for(index_t u = start; u <= stop; u++) { if(i_shade[u]) v_map_i2o[u] = t_vcnt[th]++; } } // prefix sum for(index_t th = 1; th < nt; th++) t_vcnt[th] += t_vcnt[th-1]; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); index_t tsum = (th==0 ? 0 : t_vcnt[th-1]); for(index_t u = start; u <= stop; u++) { if(i_shade[u]) v_map_i2o[u] += tsum; } } v_cnt = t_vcnt[nt-1]; #else // serially construct input-to-output vertex map for(index_t u = 0; u < i_n; u++) { if(i_shade[u]) v_map_i2o[u] = v_cnt++; } #endif // output-to-input vertex map // required to reconstruct solution in original graph index_t o_n = v_cnt; index_t *v_map_o2i = (index_t *) MALLOC(sizeof(index_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) { index_t o_u = v_map_i2o[u]; if(o_u != UNDEFINED) v_map_o2i[o_u] = u; } fprintf(stdout, "[map: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output position list index_t *o_pos = alloc_idxtab(o_n*tmax); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_pos[u] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_pos_t[o_u]++; } } } } index_t o_m = parallelsum(o_n*tmax, o_pos); index_t run = prefixsum(o_n*tmax, o_pos, 1); assert(run == (o_n*tmax+o_m)); fprintf(stdout, "[pos: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output adjacency list index_t *o_adj = alloc_idxtab(o_n*tmax + o_m); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_adj[o_pos[u]] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; index_t o_pu = o_pos_t[o_u]; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_adj[o_pu + 1 + o_adj[o_pu]++] = o_v; } } } } fprintf(stdout, "[adj: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output shade map shade_map_t *o_shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel #endif for(index_t u = 0; u < i_n; u++) { index_t o_u = v_map_i2o[u]; if(o_u != UNDEFINED) o_shade[o_u] = i_shade[u]; } fprintf(stdout, "[shade: %.2lf ms] ", pop_time()); fflush(stdout); temppathq_t *out = (temppathq_t *) MALLOC(sizeof(temppathq_t)); out->is_stub = 0; out->n = o_n; out->k = k; out->tmax = tmax; out->pos = o_pos; out->adj = o_adj; out->nl = 0; out->l = (index_t *) MALLOC(sizeof(index_t)*out->nl); out->ns = ns; out->shade = o_shade; out->vert_loc = in->vert_loc; out->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*out->n); *out_q = out; *out_map = v_map_o2i; FREE(v_map_i2o); fprintf(stdout, "done. [%.2lf ms] ", pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); } void query_pre_mk2(index_t is_dir, temppathq_t *in, temppathq_t **out_q, index_t **out_map) { push_memtrack(); index_t nt = num_threads(); index_t i_n = in->n; index_t k = in->k; index_t tmax = in->tmax; index_t *i_pos = in->pos; index_t *i_adj = in->adj; index_t ns = in->ns; shade_map_t *i_shade = in->shade; // Preprocessing steps // 1. merge graph temporal graph to a static instance // 2. build vertex localised sieve for static graph // 3. remove all vertices which are not incident to a match push_time(); // building path query pathq_t * pathq = (pathq_t *) 0; if(is_dir) { pathq = build_pathq_dir(in); } else { pathq = build_pathq(in); } // evaluate vertex localised sieve scalar_t master_sum = 0; scalar_t *master_vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*i_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) master_vsum[u] = 0; // Note: restricting number of repetitions to one. Field size used is // GF(2^64) and per-vertex false negative probability (k/2^{63}). // TODO: cross-verify experimental results // DONE: verified, single run of sieve is sufficient or at most two index_t repeats = 1; for(index_t r = 0; r < repeats; r++) { fprintf(stdout, "oracle [path]: "); scalar_t sum = pathq_execute(pathq); scalar_t *vsum = pathq->vsum; // Support size index_t support_size = 0; #ifdef BUILD_PARALLEL index_t nt = num_threads(); index_t block_size = i_n/nt; index_t ts_size[MAX_THREADS]; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { ts_size[th] = 0; index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { if(vsum[u] != 0) ts_size[th]++; } } for(index_t th = 0; th < nt; th++){ support_size += ts_size[th]; } #else for(index_t u = 0; u < i_n; u++) { if(vsum[u] != 0) support_size++; } #endif fprintf(stdout, " -- %s [%ld]\n", sum!=0?"true":"false", support_size); fflush(stdout); // update master sum master_sum = (master_sum!=0 ? master_sum : sum); // update master vsum #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) master_vsum[u] = (master_vsum[u]!=0 ? master_vsum[u] : vsum[u]); } // free memory pathq_free(pathq); //for(index_t u = 0; u < i_n; u++) // fprintf(stdout, "%4ld:"SCALAR_FORMAT_STRING"\n", u+1, master_vsum[u]); // retain vertices which are incident to at least one match push_time(); // input-to-output vertex map index_t *v_map_i2o = (index_t *) MALLOC(sizeof(index_t)*i_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) v_map_i2o[u] = UNDEFINED; index_t v_cnt = 0; #ifdef BUILD_PARALLEL // parallely construct input-to-output vertex map index_t block_size = i_n/nt; index_t t_vcnt[nt]; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); t_vcnt[th] = 0; for(index_t u = start; u <= stop; u++) { if(master_vsum[u]) v_map_i2o[u] = t_vcnt[th]++; } } // prefix sum for(index_t th = 1; th < nt; th++) t_vcnt[th] += t_vcnt[th-1]; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); index_t tsum = (th==0 ? 0 : t_vcnt[th-1]); for(index_t u = start; u <= stop; u++) { if(master_vsum[u]) v_map_i2o[u] += tsum; } } v_cnt = t_vcnt[nt-1]; #else // serially construct input-to-output vertex map for(index_t u = 0; u < i_n; u++) { if(master_vsum[u]) v_map_i2o[u] = v_cnt++; } #endif // output-to-input vertex map // required to reconstruct solution in original graph index_t o_n = v_cnt; index_t *v_map_o2i = (index_t *) MALLOC(sizeof(index_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) { index_t o_u = v_map_i2o[u]; if(o_u != UNDEFINED) v_map_o2i[o_u] = u; } fprintf(stdout, "query pre [2]: "); fprintf(stdout, "[map: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output position list index_t *o_pos = alloc_idxtab(o_n*tmax); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_pos[u] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_pos_t[o_u]++; } } } } index_t o_m = parallelsum(o_n*tmax, o_pos); index_t run = prefixsum(o_n*tmax, o_pos, 1); assert(run == (o_n*tmax+o_m)); fprintf(stdout, "[pos: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output adjacency list index_t *o_adj = alloc_idxtab(o_n*tmax + o_m); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_adj[o_pos[u]] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; index_t o_pu = o_pos_t[o_u]; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_adj[o_pu + 1 + o_adj[o_pu]++] = o_v; } } } } fprintf(stdout, "[adj: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output shade map shade_map_t *o_shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel #endif for(index_t u = 0; u < i_n; u++) { index_t o_u = v_map_i2o[u]; if(o_u != UNDEFINED) o_shade[o_u] = i_shade[u]; } fprintf(stdout, "[shade: %.2lf ms] ", pop_time()); fprintf(stdout, "done. [%.2lf ms] ", pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); temppathq_t *out = (temppathq_t *) MALLOC(sizeof(temppathq_t)); out->is_stub = 0; out->n = o_n; out->k = k; out->tmax = tmax; out->pos = o_pos; out->adj = o_adj; out->nl = 0; out->l = (index_t *) MALLOC(sizeof(index_t)*out->nl); out->ns = ns; out->shade = o_shade; out->vert_loc = in->vert_loc; out->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*out->n); *out_q = out; *out_map = v_map_o2i; FREE(master_vsum); FREE(v_map_i2o); } void query_post_mk1(index_t *uu, temppathq_t *in, temppathq_t **out_q, index_t **out_map) { push_memtrack(); index_t nt = num_threads(); index_t i_n = in->n; index_t k = in->k; index_t tmax = in->tmax; index_t *i_pos = in->pos; index_t *i_adj = in->adj; index_t ns = in->ns; shade_map_t *i_shade = in->shade; // output graph index_t o_n = k; push_time(); fprintf(stdout, "subgraph: "); fflush(stdout); shellsort(k, uu); push_time(); // input-to-output vertex map index_t *v_map_i2o = (index_t *) MALLOC(sizeof(index_t)*i_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < i_n; u++) v_map_i2o[u] = UNDEFINED; // serially construct input-to-output vertex map for(index_t i = 0; i < k; i++) v_map_i2o[uu[i]] = i; // output-to-input vertex map // required to reconstruct solution in original graph index_t *v_map_o2i = (index_t *) MALLOC(sizeof(index_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < o_n; i++) { v_map_o2i[i] = uu[i]; } fprintf(stdout, "[map: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output position list index_t *o_pos = alloc_idxtab(o_n*tmax); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_pos[u] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_pos_t[o_u]++; } } } } index_t o_m = parallelsum(o_n*tmax, o_pos); index_t run = prefixsum(o_n*tmax, o_pos, 1); assert(run == (o_n*tmax+o_m)); fprintf(stdout, "[pos: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output adjacency list index_t *o_adj = alloc_idxtab(o_n*tmax + o_m); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < o_n*tmax; u++) o_adj[o_pos[u]] = 0; for(index_t t = 0; t < tmax; t++) { index_t *o_pos_t = o_pos + o_n*t; index_t *i_pos_t = i_pos + i_n*t; index_t block_size = i_n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? i_n-1 : (start+block_size-1); for(index_t u = start; u <= stop; u++) { index_t o_u = v_map_i2o[u]; if(o_u == UNDEFINED) continue; index_t i_pu = i_pos_t[u]; index_t i_nu = i_adj[i_pu]; index_t *i_adj_u = i_adj + i_pu; index_t o_pu = o_pos_t[o_u]; for(index_t j = 1; j <= i_nu; j++) { index_t v = i_adj_u[j]; index_t o_v = v_map_i2o[v]; if(o_v == UNDEFINED) continue; o_adj[o_pu + 1 + o_adj[o_pu]++] = o_v; } } } } fprintf(stdout, "[adj: %.2lf ms] ", pop_time()); fflush(stdout); push_time(); // output shade map shade_map_t *o_shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*o_n); #ifdef BUILD_PARALLEL #pragma omp parallel #endif for(index_t u = 0; u < i_n; u++) { index_t o_u = v_map_i2o[u]; if(o_u != UNDEFINED) o_shade[o_u] = i_shade[u]; } fprintf(stdout, "[shade: %.2lf ms] ", pop_time()); fflush(stdout); temppathq_t *out = (temppathq_t *) MALLOC(sizeof(temppathq_t)); out->is_stub = 0; out->n = o_n; out->k = k; out->tmax = tmax; out->pos = o_pos; out->adj = o_adj; out->nl = 0; out->l = (index_t *) MALLOC(sizeof(index_t)*out->nl); out->ns = ns; out->shade = o_shade; out->vert_loc = in->vert_loc; out->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*out->n); *out_q = out; *out_map = v_map_o2i; FREE(v_map_i2o); fprintf(stdout, "done. [%.2lf ms] ", pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); } /****************************************************** Input reader (ASCII). */ void skipws(FILE *in) { int c; do { c = fgetc(in); if(c == '#') { do { c = fgetc(in); } while(c != EOF && c != '\n'); } } while(c != EOF && isspace(c)); if(c != EOF) ungetc(c, in); } #define CMD_NOP 0 #define CMD_TEST_UNIQUE 1 #define CMD_TEST_COUNT 2 #define CMD_LIST_FIRST 3 #define CMD_LIST_HYBRID 4 #define CMD_RUN_ORACLE 5 #define CMD_LIST_ALL 6 char *cmd_legend[] = { "no operation", "test unique", "test count", "list first", "list hybrid", "run oracle", "list all" }; void reader_ascii(FILE *in, graph_t **g_out, index_t *k_out, index_t **kk_out, index_t *cmd_out, index_t **cmd_args_out) { push_time(); push_memtrack(); index_t n = 0; index_t m = 0; index_t tmax = 0; index_t is_dir = 0; graph_t *g = (graph_t *) 0; index_t *kk = (index_t *) 0; index_t cmd = CMD_NOP; index_t *cmd_args = (index_t *) 0; index_t i, j, d, k, t; skipws(in); while(!feof(in)) { skipws(in); int c = fgetc(in); switch(c) { case 'p': if(g != (graph_t *) 0) ERROR("duplicate parameter line"); skipws(in); if(fscanf(in, "motif %ld %ld %ld %ld", &n, &m, &tmax, &is_dir) != 4) ERROR("invalid parameter line"); if(n <= 0 || m < 0 ) { ERROR("invalid input parameters (n = %ld, m = %ld, tmax = %ld)", n, m, tmax); } g = graph_alloc(n); graph_set_is_directed(g, is_dir); graph_set_max_time(g, tmax); break; case 'e': if(g == (graph_t *) 0) ERROR("parameter line must be given before edges"); skipws(in); if(fscanf(in, "%ld %ld %ld", &i, &j, &t) != 3) ERROR("invalid edge line"); //if(i < 1 || i > n || j < 1 || j > n || t < 1 || t > tmax) { // ERROR("invalid edge (i = %ld, j = %ld t = %ld with n = %ld, tmax = %ld)", // i, j, t, n, tmax); //} graph_add_edge(g, i-1, j-1, t-1); break; case 'n': if(g == (graph_t *) 0) ERROR("parameter line must be given before vertex colors"); skipws(in); if(fscanf(in, "%ld %ld", &i, &d) != 2) ERROR("invalid color line"); if(i < 1 || i > n || d < 1) ERROR("invalid color line (i = %ld, d = %ld with n = %ld)", i, d, n); graph_set_color(g, i-1, d-1); break; case 'k': if(g == (graph_t *) 0) ERROR("parameter line must be given before motif"); skipws(in); if(fscanf(in, "%ld", &k) != 1) ERROR("invalid motif line"); if(k < 1 || k > n) ERROR("invalid motif line (k = %ld with n = %d)", k, n); kk = alloc_idxtab(k); for(index_t u = 0; u < k; u++) { skipws(in); if(fscanf(in, "%ld", &i) != 1) ERROR("error parsing motif line"); if(i < 1) ERROR("invalid color on motif line (i = %ld)", i); kk[u] = i-1; } break; case 't': if(g == (graph_t *) 0 || kk == (index_t *) 0) ERROR("parameter and motif lines must be given before test"); skipws(in); { char cmdstr[128]; if(fscanf(in, "%100s", cmdstr) != 1) ERROR("invalid test command"); if(!strcmp(cmdstr, "unique")) { cmd_args = alloc_idxtab(k); for(index_t u = 0; u < k; u++) { skipws(in); if(fscanf(in, "%ld", &i) != 1) ERROR("error parsing test line"); if(i < 1 || i > n) ERROR("invalid test line entry (i = %ld)", i); cmd_args[u] = i-1; } heapsort_indext(k, cmd_args); for(index_t u = 1; u < k; u++) if(cmd_args[u-1] >= cmd_args[u]) ERROR("test line contains duplicate entries"); cmd = CMD_TEST_UNIQUE; } else { if(!strcmp(cmdstr, "count")) { cmd_args = alloc_idxtab(1); skipws(in); if(fscanf(in, "%ld", &i) != 1) ERROR("error parsing test line"); if(i < 0) ERROR("count on test line cannot be negative"); cmd = CMD_TEST_COUNT; cmd_args[0] = i; } else { ERROR("unrecognized test command \"%s\"", cmdstr); } } } break; case EOF: break; default: ERROR("parse error"); } } if(g == (graph_t *) 0) ERROR("no graph given in input"); if(kk == (index_t *) 0) ERROR("no motif given in input"); for(index_t i = 0; i < n; i++) { if(g->colors[i] == -1) ERROR("no color assigned to vertex i = %ld", i); } double time = pop_time(); fprintf(stdout, "input: n = %ld, m = %ld, k = %ld, t = %ld [%.2lf ms] ", g->num_vertices, g->num_edges, k, g->max_time, time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); *g_out = g; *k_out = k; *kk_out = kk; *cmd_out = cmd; *cmd_args_out = cmd_args; } /***************************************************** Input reader (binary). */ #define BIN_MAGIC 0x1234567890ABCDEFUL void reader_bin(FILE *in, graph_t **g_out, index_t *k_out, index_t **kk_out, index_t *cmd_out, index_t **cmd_args_out) { push_time(); push_memtrack(); index_t magic = 0; index_t n = 0; index_t m = 0; graph_t *g = (graph_t *) 0; index_t k = 0; index_t has_target = 0; index_t *kk = (index_t *) 0; index_t cmd = CMD_NOP; index_t *cmd_args = (index_t *) 0; if(fread(&magic, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); if(magic != BIN_MAGIC) ERROR("error reading input"); if(fread(&n, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); if(fread(&m, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); assert(n >= 0 && m >= 0 && m%2 == 0); g = graph_alloc(n); index_t *e = graph_edgebuf(g, m/2); if(fread(e, sizeof(index_t), m, in) != m) ERROR("error reading input"); if(fread(g->colors, sizeof(index_t), n, in) != n) ERROR("error reading input"); if(fread(&has_target, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); assert(has_target == 0 || has_target == 1); if(has_target) { if(fread(&k, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); assert(k >= 0); kk = alloc_idxtab(k); if(fread(kk, sizeof(index_t), k, in) != k) ERROR("error reading input"); if(fread(&cmd, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); switch(cmd) { case CMD_NOP: break; case CMD_TEST_UNIQUE: cmd_args = alloc_idxtab(k); if(fread(cmd_args, sizeof(index_t), k, in) != k) ERROR("error reading input"); shellsort(k, cmd_args); break; case CMD_TEST_COUNT: cmd_args = alloc_idxtab(1); if(fread(cmd_args, sizeof(index_t), 1UL, in) != 1UL) ERROR("error reading input"); break; default: ERROR("invalid command in binary input stream"); break; } } double time = pop_time(); fprintf(stdout, "input: n = %ld, m = %ld, k = %ld [%.2lf ms] ", g->num_vertices, g->num_edges, k, time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); *g_out = g; *k_out = k; *kk_out = kk; *cmd_out = cmd; *cmd_args_out = cmd_args; } /************************************************************ Temporal DFS. */ index_t temp_dfs(index_t n, index_t k, index_t tmax, index_t *pos, index_t *adj, index_t *in_stack, stk_t *s) { stack_node_t e; stack_top(s, &e); index_t u = e.u; index_t l = e.l; index_t tmin = e.t; // reached depth 'k' if(s->n == k) // TODO: fix this to s->n == k return 1; for(index_t t = tmin; t < tmax; t++) { index_t *pos_t = pos + t*n; index_t pu = pos_t[u]; index_t nu = adj[pu]; if(nu == 0) continue; index_t *adj_u = adj + pu; for(index_t i = 1; i <= nu; i++) { index_t v = adj_u[i]; if(in_stack[v]) continue; stack_node_t e; e.u = v; e.l = l+1; e.t = t+1; stack_push(s, &e); in_stack[v] = 1; if(temp_dfs(n, k, tmax, pos, adj, in_stack, s)) return 1; stack_pop(s, &e); in_stack[v] = 0; } } return 0; // not found } index_t find_temppath(temppathq_t *root, index_t *uu, index_t *tt) { index_t n = root->n; index_t k = root->k; index_t tmax = root->tmax; index_t *pos = root->pos; index_t *adj = root->adj; // alloc memory index_t *v_rand = alloc_idxtab(n); // random permutation of vertices index_t seed = irand(); randperm(n, seed, v_rand); index_t *in_stack = alloc_idxtab(n); stk_t *s = stack_alloc(k); for(index_t j = 0; j < n; j++) { for(index_t i = 0; i < n; i++) in_stack[i] = 0; index_t u = v_rand[j]; stack_node_t e; e.u = u; e.l = 1; e.t = 0; stack_push(s, &e); in_stack[u] = 1; if(temp_dfs(n, k, tmax, pos, adj, in_stack, s)) { index_t cnt = 0; while(s->n) { stack_node_t e; stack_pop(s, &e); index_t u = e.u; index_t t = e.t; uu[cnt] = u; tt[cnt] = t; cnt++; } break; } else { stack_empty(s); } } FREE(v_rand); FREE(in_stack); stack_free(s); return 1; } /********************************************************** temporal rev-DFS. */ // index_t temp_revdfs(index_t n, index_t k, index_t tmax, index_t *pos, index_t *adj, index_t *color, index_t *kk_in, index_t *in_stack, stk_t *s, index_t *uu_out, index_t *tt_out, index_t *t_opt) { if(s->n >= k) { // reached depth k assert(s->n <= k); // allocate memory index_t *uu_sol = (index_t *) malloc(k*sizeof(index_t)); index_t *kk_sol = (index_t *) malloc(k*sizeof(index_t)); index_t *tt_sol = (index_t *) malloc(k*sizeof(index_t)); // get vertices in stack stack_get_vertices(s, uu_sol); stack_get_timestamps(s, tt_sol); // get vertex colors for(index_t i = 0; i < k; i++) kk_sol[i] = color[uu_sol[i]]; shellsort(k, kk_sol); // check if colors match index_t is_motif = 1; for(index_t i = 0; i < k; i++) { if(kk_sol[i] != kk_in[i]) { is_motif = 0; break; } } // match found if(is_motif) { stack_node_t e; stack_top(s, &e); if(*t_opt > e.t) { // copy solution vertices for(index_t i = 0; i < k; i++) uu_out[i] = uu_sol[i]; // copy solution timestamps for(index_t i = 0; i < k; i++) tt_out[i] = tt_sol[i]; *t_opt = e.t; } } // free memory free(uu_sol); free(kk_sol); free(tt_sol); return 1; } else { stack_node_t e; stack_top(s, &e); index_t u = e.u; //index_t l = e.l; index_t t_start = e.t; index_t t_end = 0; for(index_t t = t_start-1; t >= t_end; t--) { index_t *pos_t = pos + t*n; index_t pu = pos_t[u]; index_t nu = adj[pu]; if(nu == 0) continue; index_t *adj_u = adj + pu; for(index_t i = 1; i <= nu; i++) { index_t v = adj_u[i]; if(in_stack[v]) continue; stack_node_t e; e.u = v; //e.l = l+1; e.t = t; stack_push(s, &e); in_stack[v] = 1; // recursive call to depth k temp_revdfs(n, k, tmax, pos, adj, color, kk_in, in_stack, s, uu_out, tt_out, t_opt); stack_pop(s, &e); in_stack[v] = 0; } } } return 1; // not found } index_t exhaustive_search(temppathq_t *root, index_t *kk, index_t *color, index_t *uu_out, index_t *tt_out) { push_time(); push_memtrack(); index_t nt = num_threads(); index_t n = root->n; index_t k = root->k; index_t tmax = root->tmax; index_t *pos = root->pos; index_t *adj = root->adj; scalar_t *vsum = root->vsum; index_t *vsum_cnt_nt = alloc_idxtab(nt+1); push_time(); index_t block_size = n/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); index_t cnt = 0; for(index_t i = start; i <= stop; i++) cnt += (vsum[i] ? 1 : 0); vsum_cnt_nt[th] = cnt; } // cosolidate thread counts vsum_cnt_nt[nt] = 0; prefixsum(nt+1, vsum_cnt_nt, 0); index_t vsum_cnt = vsum_cnt_nt[nt]; // get vertices with non-zero value in `vsum` index_t *vsum_vertices = alloc_idxtab(vsum_cnt); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); index_t j = vsum_cnt_nt[th]; for(index_t i = start; i <= stop; i++) { if(vsum[i]) vsum_vertices[j++] = i; } } index_t *v_seq = alloc_idxtab(vsum_cnt); index_t seed = irand(); randperm(vsum_cnt, seed, v_seq); double init_time = pop_time(); push_time(); index_t *uu_sol_nt = alloc_idxtab(k*nt); index_t *tt_sol_nt = alloc_idxtab(k*nt); index_t *in_stack_nt = alloc_idxtab(n*nt); index_t *t_opt_nt = alloc_idxtab(nt); block_size = vsum_cnt/nt; volatile index_t found = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for shared(found) #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? vsum_cnt-1 : (start+block_size-1); index_t *uu_sol = uu_sol_nt + th*k; index_t *tt_sol = tt_sol_nt + th*k; index_t *in_stack = in_stack_nt +th*n; index_t t_opt = MATH_INF; stk_t *s = stack_alloc(k); for(index_t j = start; j <= stop; j++) { if(found) break; index_t u = vsum_vertices[v_seq[j]]; for(index_t i = 0; i < n; i++) in_stack[i] = 0; stack_node_t e; e.u = u; //e.l = k; e.t = tmax; stack_push(s, &e); in_stack[u] = 1; temp_revdfs(n, k, tmax, pos, adj, color, kk, in_stack, s, uu_sol, tt_sol, &t_opt); if(t_opt != MATH_INF) { found = th+1; } stack_empty(s); } stack_free(s); } if(found) { index_t th = found-1; index_t *uu_sol = uu_sol_nt + th*k; index_t *tt_sol = tt_sol_nt + th*k; for(index_t i = 0; i < k; i++) uu_out[i] = uu_sol[i]; for(index_t i = 0; i < k; i++) tt_out[i] = tt_sol[i]; } double dfs_time = pop_time(); FREE(vsum_cnt_nt); FREE(uu_sol_nt); FREE(tt_sol_nt); FREE(in_stack_nt); FREE(t_opt_nt); FREE(v_seq); FREE(vsum_vertices); fprintf(stdout, "exhaustive-search: [init: %.2lfms] [dfs: %.2lfms] done." " [%.2lfms] ", init_time, dfs_time, pop_time()); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, " -- %s\n", found?"true":"false"); fflush(stdout); return (found ? 1 : 0); } /******************************************************* Program entry point. */ #define PRE_NOP 0 #define PRE_MK1 1 #define PRE_MK2 2 #define PRE_MK3 3 int main(int argc, char **argv) { GF_PRECOMPUTE; push_time(); push_memtrack(); index_t precomp = PRE_NOP; index_t arg_cmd = CMD_NOP; index_t have_seed = 0; index_t have_input = 0; index_t find_optimal = 0; index_t seed = 123456789; char *filename = (char *) 0; for(index_t f = 1; f < argc; f++) { if(argv[f][0] == '-') { if(!strcmp(argv[f], "-bin")) { flag_bin_input = 1; } if(!strcmp(argv[f], "-ascii")) { flag_bin_input = 0; } if(!strcmp(argv[f], "-pre")) { if(f == argc -1) ERROR("preprocessing argument missing from command line"); precomp = atol(argv[++f]); } if(!strcmp(argv[f], "-optimal")) { find_optimal = 1; } if(!strcmp(argv[f], "-oracle")) { arg_cmd = CMD_RUN_ORACLE; } if(!strcmp(argv[f], "-first")) { arg_cmd = CMD_LIST_FIRST; } if(!strcmp(argv[f], "-hybrid")) { arg_cmd = CMD_LIST_HYBRID; } if(!strcmp(argv[f], "-all")) { arg_cmd = CMD_LIST_ALL; } if(!strcmp(argv[f], "-seed")) { if(f == argc - 1) ERROR("random seed missing from command line"); seed = atol(argv[++f]); have_seed = 1; } if(!strcmp(argv[f], "-in")) { if(f == argc - 1) ERROR("input file missing from command line"); have_input = 1; filename = argv[++f]; } } } fprintf(stdout, "invoked as:"); for(index_t f = 0; f < argc; f++) fprintf(stdout, " %s", argv[f]); fprintf(stdout, "\n"); if(have_seed == 0) { fprintf(stdout, "no random seed given, defaulting to %ld\n", seed); } fprintf(stdout, "random seed = %ld\n", seed); FILE *in = stdin; if(have_input) { in = fopen(filename, "r"); if(in == NULL) ERROR("unable to open file '%s'", filename); } else { fprintf(stdout, "no input file specified, defaulting to stdin\n"); } fflush(stdout); srand(seed); graph_t *g; index_t k; index_t *kk; index_t input_cmd; index_t *cmd_args; if(flag_bin_input) { reader_bin(in, &g, &k, &kk, &input_cmd, &cmd_args); } else { reader_ascii(in, &g, &k, &kk, &input_cmd, &cmd_args); } index_t cmd = input_cmd; // by default execute command in input stream if(arg_cmd != CMD_NOP) cmd = arg_cmd; // override command in input stream // build root query index_t is_dir = 0; temppathq_t *root = (temppathq_t *) 0; if(g->is_directed) { is_dir = 1; root = build_temppathq_dir(g, k, kk); } else { root = build_temppathq(g, k, kk); } // keep a copy of colors index_t *color = (index_t *) 0; if(cmd == CMD_LIST_HYBRID) { color = alloc_idxtab(root->n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < root->n; u++) color[u] = g->colors[u]; } //free graph graph_free(g); push_time(); push_time(); // preprocess query index_t *v_map_pre1; index_t *v_map_pre2; switch(precomp) { case PRE_NOP: { // no precomputation fprintf(stdout, "no preprocessing, default execution\n"); break; } case PRE_MK1: { // preprocess: remove vertices with no matching colors temppathq_t *root_pre; query_pre_mk1(root, &root_pre, &v_map_pre1); temppathq_free(root); root = root_pre; // preprocessed graph statistics index_t o_n = root->n; index_t tmax = root->tmax; index_t *o_pos = root->pos; index_t *o_adj = root->adj; index_t o_m = (o_pos[o_n*(tmax-1) + o_n-1] + o_adj[o_pos[o_n*(tmax-1) + o_n-1]] - (o_n*tmax) + 1)/2; fprintf(stdout, "output pre [1]: n = %ld, m = %ld, k = %ld \n", o_n, o_m, k); // required for reconstruction of solution in original graph //FREE(v_map_pre1); break; } case PRE_MK2: { // preprocess: constructing vertex localised sieve in static graph temppathq_t *root_pre; query_pre_mk2(is_dir, root, &root_pre, &v_map_pre2); temppathq_free(root); root= root_pre; // preprocessed graph statistics index_t o_n = root->n; index_t tmax = root->tmax; index_t *o_pos = root->pos; index_t *o_adj = root->adj; index_t o_m = (o_pos[o_n*(tmax-1) + o_n-1] + o_adj[o_pos[o_n*(tmax-1) + o_n-1]] - (o_n*tmax)+1)/2; fprintf(stdout, "output pre [2]: n = %ld, m = %ld, k = %ld \n", o_n, o_m, k); // required for reconstruction of solution in original graph //FREE(v_map_pre2); break; } case PRE_MK3: { // -- execute all preprocessing steps -- // // preprocess: remove vertices with no matching colors temppathq_t *root_pre1; query_pre_mk1(root, &root_pre1, &v_map_pre1); temppathq_free(root); root = root_pre1; // preprocessed graph statistics index_t o_n = root->n; index_t tmax = root->tmax; index_t *o_pos = root->pos; index_t *o_adj = root->adj; index_t o_m = (o_pos[o_n*(tmax-1) + o_n-1] + o_adj[o_pos[o_n*(tmax-1) + o_n-1]] - (o_n*tmax)+1)/2; fprintf(stdout, "output pre [1]: n = %ld, m = %ld, k = %ld \n", o_n, o_m, k); // preprocess: constructing vertex localised sieve in static graph temppathq_t *root_pre2; query_pre_mk2(is_dir, root, &root_pre2, &v_map_pre2); temppathq_free(root); root= root_pre2; // preprocessed graph statistics o_n = root->n; o_pos = root->pos; o_adj = root->adj; o_m = (o_pos[o_n*(tmax-1) + o_n-1] + o_adj[o_pos[o_n*(tmax-1) + o_n-1]] - (o_n*tmax)+1)/2; fprintf(stdout, "output pre [2]: n = %ld, m = %ld, k = %ld \n", o_n, o_m, k); // required for reconstruction of solution in original graph //FREE(v_map_pre1); //FREE(v_map_pre2); break; } default: break; } double precomp_time = pop_time(); push_time(); index_t SOLUTION_EXISTS = 1; // default assume solution exists // find optimal solution if(find_optimal) { // --- optimal solution --- // // check if the solution exists fprintf(stdout, "optimal : %ld\n", root->tmax); fprintf(stdout, "%13ld [%ld:%ld]\t\t", root->tmax, (index_t) (1), root->tmax); if(temppathq_execute(root)) { fprintf(stdout, " -- true\n"); fflush(stdout); // binary search: obtain optimal value of `t` index_t t_opt = root->tmax; index_t tmax = root->tmax; index_t low = k-1; index_t high = tmax; while(low < high) { index_t mid = (low+high)/2; root->tmax = mid; fprintf(stdout, "%13ld [%ld:%ld]\t\t", mid, low, high); if(temppathq_execute(root)) { if(t_opt > root->tmax) t_opt = root->tmax; high = mid; fprintf(stdout, " -- true\n"); fflush(stdout); } else { low = mid + 1; fprintf(stdout, " -- false\n"); fflush(stdout); } } root->tmax = t_opt; SOLUTION_EXISTS = 1; } else { fprintf(stdout, " -- false\n"); fflush(stdout); temppathq_free(root); SOLUTION_EXISTS = 0; } } double opt_time = pop_time(); fprintf(stdout, "command: %s\n", cmd_legend[cmd]); fflush(stdout); push_time(); // execute command switch(cmd) { case CMD_NOP: { // no operation temppathq_free(root); break; } case CMD_TEST_UNIQUE: { if(!SOLUTION_EXISTS) break; // ---- test unique --- // // check if the solution is unique index_t n = root->n; index_t k = root->k; lister_t *t = lister_alloc(n, k, root); index_t *get = alloc_idxtab(k); index_t ct = 0; while(lister_run(t, get)) { assert(ct == 0); fprintf(stdout, "found %ld: ", ct); for(index_t i = 0; i < k; i++) fprintf(stdout, "%ld%s", get[i], i == k-1 ? "\n" : " "); for(index_t l = 0; l < k; l++) assert(get[l] == cmd_args[l]); ct++; } assert(ct == 1); FREE(get); lister_free(t); } break; case CMD_LIST_FIRST: { if(!SOLUTION_EXISTS) break; // --- list first solution --- // // list vertices: obtain `k` vertices satisfying our constraints index_t n = root->n; index_t k = root->k; lister_t *t = lister_alloc(n, k, root); index_t *get = alloc_idxtab(k); index_t ct = 0; if(lister_run(t, get)) { fprintf(stdout, "found %ld: ", ct); switch(precomp) { case PRE_NOP: for(index_t i = 0; i < k; i++) fprintf(stdout, "%ld%s", get[i]+1, i == k-1 ? "\n" : " "); break; case PRE_MK1: for(index_t i = 0; i < k; i++) fprintf(stdout, "%ld%s", v_map_pre1[get[i]]+1, i == k-1 ? "\n" : " "); break; case PRE_MK2: for(index_t i = 0; i < k; i++) fprintf(stdout, "%ld%s", v_map_pre2[get[i]]+1, i == k-1 ? "\n" : " "); break; case PRE_MK3: for(index_t i = 0; i < k; i++) fprintf(stdout, "%ld%s", v_map_pre1[v_map_pre2[get[i]]]+1, i == k-1 ? "\n" : " "); break; default: break; } ct++; //if(cmd == CMD_LIST_FIRST || CMD_LIST_OPT) // break; } // post-processing: obtain vertex-induced subgraph using // k-vertices of previous step if(ct) { push_time(); index_t *v_map_post = (index_t *) 0; temppathq_t *root_post = (temppathq_t *) 0; query_post_mk1(get, root, &root_post, &v_map_post); // final vertex map index_t *v_map = alloc_idxtab(k); switch(precomp) { case PRE_NOP: for(index_t i = 0; i < k; i++) v_map[i] = v_map_post[i]; break; case PRE_MK1: for(index_t i = 0; i < k; i++) v_map[i] = v_map_pre1[v_map_post[i]]; break; case PRE_MK2: for(index_t i = 0; i < k; i++) v_map[i] = v_map_pre2[v_map_post[i]]; break; case PRE_MK3: for(index_t i = 0; i < k; i++) v_map[i] = v_map_pre1[v_map_pre2[v_map_post[i]]]; break; default: break; } // find itenary: temporal-DFS to get travel itenary index_t *uu_sol = alloc_idxtab(k); index_t *tt_sol = alloc_idxtab(k); find_temppath(root_post, uu_sol, tt_sol) ; fprintf(stdout, "solution [%ld, %.2lfms]: ", tt_sol[0], pop_time()); for(index_t i = k-1; i > 0; i--) { index_t u = v_map[uu_sol[i]]; index_t v = v_map[uu_sol[i-1]]; index_t t = tt_sol[i-1]; fprintf(stdout, "[%ld, %ld, %ld]%s", u+1, v+1, t, i==1?"\n":" "); } FREE(v_map_post); FREE(v_map); FREE(uu_sol); FREE(tt_sol); temppathq_free(root_post); } FREE(get); lister_free(t); } break; case CMD_LIST_HYBRID: { push_time(); fprintf(stdout, "oracle [temppath]: "); fflush(stdout); root->vert_loc = 1; if(SOLUTION_EXISTS && temppathq_execute(root)) { fprintf(stdout, " -- true\n"); index_t n = root->n; index_t *v_map = alloc_idxtab(n); // build vertex map switch(precomp) { case PRE_NOP: { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) v_map[i] = i; } break; case PRE_MK1: { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) v_map[i] = v_map_pre1[i]; } break; case PRE_MK2: { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) v_map[i] = v_map_pre2[i]; } break; case PRE_MK3: { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) v_map[i] = v_map_pre1[v_map_pre2[i]]; } break; default: break; } // build color map index_t *color_map = alloc_idxtab(n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < n; i++) color_map[i] = color[v_map[i]]; index_t *uu_sol = alloc_idxtab(k); index_t *tt_sol = alloc_idxtab(k); exhaustive_search(root, kk, color_map, uu_sol, tt_sol); fprintf(stdout, "solution [%ld, %.2lfms]: ", tt_sol[0], pop_time()); for(index_t i = k-1; i > 0; i--) { index_t u = v_map[uu_sol[i]]; index_t v = v_map[uu_sol[i-1]]; index_t t = tt_sol[i-1]; fprintf(stdout, "[%ld, %ld, %ld]%s", u+1, v+1, t, i==1?"\n":" "); } FREE(v_map); FREE(color_map); FREE(uu_sol); FREE(tt_sol); } else { fprintf(stdout, " -- false\n"); } FREE(color); temppathq_free(root); } break; case CMD_RUN_ORACLE: { if(!SOLUTION_EXISTS) break; // --- run oracle --- fprintf(stdout, "oracle [temppath]: "); fflush(stdout); if(temppathq_execute(root)) fprintf(stdout, " -- true\n"); else fprintf(stdout, " -- false\n"); temppathq_free(root); } break; default: assert(0); break; } // free vertex map if(precomp == PRE_MK1) FREE(v_map_pre1); if(precomp == PRE_MK2) FREE(v_map_pre2); if(precomp == PRE_MK3) { FREE(v_map_pre1); FREE(v_map_pre2); } FREE(kk); double cmd_time = pop_time(); double time = pop_time(); fprintf(stdout, "command done [%.2lf ms %.2lfms %.2lf ms %.2lf ms]\n", precomp_time, opt_time, cmd_time, time); if(input_cmd != CMD_NOP) FREE(cmd_args); time = pop_time(); fprintf(stdout, "grand total [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, "\n"); fprintf(stdout, "host: %s\n", sysdep_hostname()); fprintf(stdout, "build: %s, %s, %s, %ld x %s\n", #ifdef BUILD_PARALLEL "multithreaded", #else "single thread", #endif #ifdef BUILD_PREFETCH "prefetch", #else "no prefetch", #endif GENF_TYPE, LIMBS_IN_LINE, LIMB_TYPE); fprintf(stdout, "compiler: gcc %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); fflush(stdout); assert(malloc_balance == 0); assert(memtrack_stack_top < 0); return 0; }
hst_compiler_explorer.c
// TODO Mark regions #include <assert.h> #include <getopt.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <omp.h> #include "../../support/common.h" #include "../../support/timer.h" // Pointer declaration static T *A; static unsigned int *histo_host; typedef struct Params { unsigned int input_size; unsigned int bins; int n_warmup; int n_reps; const char *file_name; int exp; int n_threads; } Params; /** * @brief creates input arrays * @param nr_elements how many elements in input arrays */ static void read_input(T *A, const Params p) { char dctFileName[100]; FILE *File = NULL; // Open input file unsigned short temp; sprintf(dctFileName, p.file_name); if ((File = fopen(dctFileName, "rb")) != NULL) { for (unsigned int y = 0; y < p.input_size; y++) { fread(&temp, sizeof(unsigned short), 1, File); A[y] = (unsigned int)ByteSwap16(temp); if (A[y] >= 4096) A[y] = 4095; } fclose(File); } else { printf("%s does not exist\n", dctFileName); exit(1); } } /** * @brief compute output in the host */ static void histogram_host(unsigned int *histo, T *A, unsigned int bins, unsigned int nr_elements, int exp, unsigned int nr_of_dpus, int t) { omp_set_num_threads(t); if (!exp) { #pragma omp parallel for for (unsigned int i = 0; i < nr_of_dpus; i++) { for (unsigned int j = 0; j < nr_elements; j++) { T d = A[j]; histo[i * bins + ((d * bins) >> DEPTH)] += 1; } } } else { #pragma omp parallel for for (unsigned int j = 0; j < nr_elements; j++) { T d = A[j]; #pragma omp atomic update histo[(d * bins) >> DEPTH] += 1; } } } // Params --------------------------------------------------------------------- void usage() { fprintf(stderr, "\nUsage: ./program [options]" "\n" "\nGeneral options:" "\n -h help" "\n -w <W> # of untimed warmup iterations (default=1)" "\n -e <E> # of timed repetition iterations (default=3)" "\n -t <T> # of threads (default=8)" "\n -x <X> Weak (0) or strong (1) scaling (default=0)" "\n" "\nBenchmark-specific options:" "\n -i <I> input size (default=1536*1024 elements)" "\n -b <B> histogram size (default=256 bins)" "\n -f <F> input image file (default=../input/image_VanHateren.iml)" "\n"); } struct Params input_params(int argc, char **argv) { struct Params p; p.input_size = 1536 * 1024; p.bins = 256; p.n_warmup = 1; p.n_reps = 3; p.n_threads = 8; p.exp = 1; p.file_name = "../../input/image_VanHateren.iml"; int opt; while ((opt = getopt(argc, argv, "hi:b:w:e:f:x:t:")) >= 0) { switch (opt) { case 'h': usage(); exit(0); break; case 'i': p.input_size = atoi(optarg); break; case 'b': p.bins = atoi(optarg); break; case 'w': p.n_warmup = atoi(optarg); break; case 'e': p.n_reps = atoi(optarg); break; case 'f': p.file_name = optarg; break; case 'x': p.exp = atoi(optarg); break; case 't': p.n_threads = atoi(optarg); break; default: fprintf(stderr, "\nUnrecognized option!\n"); usage(); exit(0); } } assert(p.n_threads > 0 && "Invalid # of ranks!"); return p; } /** * @brief Main of the Host Application. */ int main() { struct Params p = input_params(argc, argv); uint32_t nr_of_dpus; const unsigned int input_size = p.input_size; // Size of input image if (!p.exp) assert(input_size % p.n_threads == 0 && "Input size!"); else assert(input_size % p.n_threads == 0 && "Input size!"); // Input/output allocation A = malloc(input_size * sizeof(T)); T *bufferA = A; if (!p.exp) histo_host = malloc(nr_of_dpus * p.bins * sizeof(unsigned int)); else histo_host = malloc(p.bins * sizeof(unsigned int)); // Create an input file with arbitrary data. read_input(A, p); Timer timer; start(&timer, 0, 0); if (!p.exp) memset(histo_host, 0, nr_of_dpus * p.bins * sizeof(unsigned int)); else memset(histo_host, 0, p.bins * sizeof(unsigned int)); histogram_host(histo_host, A, p.bins, input_size, p.exp, nr_of_dpus, p.n_threads); stop(&timer, 0); printf("Kernel "); print(&timer, 0, 1); printf("\n"); return 0; }
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 8; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
Par-09-ParallelConsecutiveForLoops.c
int main(int argc, char **argv) { int a[4] = {1,2,3,4}; int b[4] = {0, 0, 0, 0}; #pragma omp parallel { #pragma omp for for (int i = 0; i < 4; ++i) { a[i] = 3*a[i]; } #pragma omp for for (int j = 0; j < 4; ++j) { b[j] = a[j]; } } return 0; }
omp_func.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int nthreads, tid, procs, maxt, inpar, dynamic, nested; // start parallel region #pragma omp parallel private(nthreads, tid) { // obtain thread number tid = omp_get_thread_num(); // only master thread does this if(tid == 0) { printf("Thread %d getting environment info...\n", tid); //getting environment information procs = omp_get_num_procs(); nthreads = omp_get_num_threads(); maxt = omp_get_max_threads(); inpar = omp_in_parallel(); dynamic = omp_get_dynamic(); nested = omp_get_nested(); // print environment information printf("Number of processors = %d\n", procs); printf("Number of threads = %d\n", threads); printf("Max threads = %d\n", maxt); printf("In parallel? = %d\n", inpar); printf("Dynamic threads enabled? = %d\n", dynamic); printf("Nested parallelism enabled? = %d\n", nested); } } }
crop_and_resize.c
#include <TH/TH.h> #include <stdio.h> #include <math.h> void CropAndResizePerBox( const float * image_data, const int batch_size, const int depth, const int image_height, const int image_width, const float * boxes_data, const int * box_index_data, const int start_box, const int limit_box, float * corps_data, const int crop_height, const int crop_width, const float extrapolation_value ) { const int image_channel_elements = image_height * image_width; const int image_elements = depth * image_channel_elements; const int channel_elements = crop_height * crop_width; const int crop_elements = depth * channel_elements; int b; #pragma omp parallel for for (b = start_box; b < limit_box; ++b) { const float * box = boxes_data + b * 4; const float y1 = box[0]; const float x1 = box[1]; const float y2 = box[2]; const float x2 = box[3]; const int b_in = box_index_data[b]; if (b_in < 0 || b_in >= batch_size) { printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size); exit(-1); } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; for (int y = 0; y < crop_height; ++y) { const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { for (int x = 0; x < crop_width; ++x) { for (int d = 0; d < depth; ++d) { // crops(b, y, x, d) = extrapolation_value; corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = extrapolation_value; } } continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; for (int x = 0; x < crop_width; ++x) { const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { for (int d = 0; d < depth; ++d) { corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = extrapolation_value; } continue; } const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; for (int d = 0; d < depth; ++d) { const float *pimage = image_data + b_in * image_elements + d * image_channel_elements; const float top_left = pimage[top_y_index * image_width + left_x_index]; const float top_right = pimage[top_y_index * image_width + right_x_index]; const float bottom_left = pimage[bottom_y_index * image_width + left_x_index]; const float bottom_right = pimage[bottom_y_index * image_width + right_x_index]; const float top = top_left + (top_right - top_left) * x_lerp; const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp; corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = top + (bottom - top) * y_lerp; } } // end for x } // end for y } // end for b } void crop_and_resize_forward( THFloatTensor * image, THFloatTensor * boxes, // [y1, x1, y2, x2] THIntTensor * box_index, // range in [0, batch_size) const float extrapolation_value, const int crop_height, const int crop_width, THFloatTensor * crops ) { const int batch_size = THFloatTensor_size(image, 0); const int depth = THFloatTensor_size(image, 1); const int image_height = THFloatTensor_size(image, 2); const int image_width = THFloatTensor_size(image, 3); const int num_boxes = THFloatTensor_size(boxes, 0); // init output space THFloatTensor_resize4d(crops, num_boxes, depth, crop_height, crop_width); THFloatTensor_zero(crops); // crop_and_resize for each box CropAndResizePerBox( THFloatTensor_data(image), batch_size, depth, image_height, image_width, THFloatTensor_data(boxes), THIntTensor_data(box_index), 0, num_boxes, THFloatTensor_data(crops), crop_height, crop_width, extrapolation_value ); } void crop_and_resize_backward( THFloatTensor * grads, THFloatTensor * boxes, // [y1, x1, y2, x2] THIntTensor * box_index, // range in [0, batch_size) THFloatTensor * grads_image // resize to [bsize, c, hc, wc] ) { // shape const int batch_size = THFloatTensor_size(grads_image, 0); const int depth = THFloatTensor_size(grads_image, 1); const int image_height = THFloatTensor_size(grads_image, 2); const int image_width = THFloatTensor_size(grads_image, 3); const int num_boxes = THFloatTensor_size(grads, 0); const int crop_height = THFloatTensor_size(grads, 2); const int crop_width = THFloatTensor_size(grads, 3); // n_elements const int image_channel_elements = image_height * image_width; const int image_elements = depth * image_channel_elements; const int channel_elements = crop_height * crop_width; const int crop_elements = depth * channel_elements; // init output space THFloatTensor_zero(grads_image); // data pointer const float * grads_data = THFloatTensor_data(grads); const float * boxes_data = THFloatTensor_data(boxes); const int * box_index_data = THIntTensor_data(box_index); float * grads_image_data = THFloatTensor_data(grads_image); for (int b = 0; b < num_boxes; ++b) { const float * box = boxes_data + b * 4; const float y1 = box[0]; const float x1 = box[1]; const float y2 = box[2]; const float x2 = box[3]; const int b_in = box_index_data[b]; if (b_in < 0 || b_in >= batch_size) { printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size); exit(-1); } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; for (int y = 0; y < crop_height; ++y) { const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; for (int x = 0; x < crop_width; ++x) { const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { continue; } const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; for (int d = 0; d < depth; ++d) { float *pimage = grads_image_data + b_in * image_elements + d * image_channel_elements; const float grad_val = grads_data[crop_elements * b + channel_elements * d + y * crop_width + x]; const float dtop = (1 - y_lerp) * grad_val; pimage[top_y_index * image_width + left_x_index] += (1 - x_lerp) * dtop; pimage[top_y_index * image_width + right_x_index] += x_lerp * dtop; const float dbottom = y_lerp * grad_val; pimage[bottom_y_index * image_width + left_x_index] += (1 - x_lerp) * dbottom; pimage[bottom_y_index * image_width + right_x_index] += x_lerp * dbottom; } // end d } // end x } // end y } // end b }
comm.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * Copyright (c) 2015 by Contributors */ #ifndef MXNET_KVSTORE_COMM_H_ #define MXNET_KVSTORE_COMM_H_ #include <dmlc/omp.h> #include <string> #include <algorithm> #include <utility> #include <limits> #include <vector> #include <tuple> #include <thread> #include "mxnet/ndarray.h" #include "gradient_compression.h" #include "../ndarray/ndarray_function.h" #include "../operator/tensor/sparse_retain-inl.h" #include "./kvstore_utils.h" namespace mxnet { namespace kvstore { /** * \brief multiple device commmunication */ class Comm { public: Comm() { pinned_ctx_ = Context::CPUPinned(0); } virtual ~Comm() { } /** * \brief init key with the data shape and storage shape */ virtual void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) = 0; /** * \brief returns src[0] + .. + src[src.size()-1] */ virtual const NDArray& Reduce( int key, const std::vector<NDArray>& src, int priority) = 0; /** * \brief copy from src to dst[i] for every i */ virtual void Broadcast( int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) = 0; /** * \brief broadcast src to dst[i] with target row_ids for every i * \param key the identifier key for the stored ndarray * \param src the source row_sparse ndarray to broadcast * \param dst a list of destination row_sparse NDArray and its target row_ids to broadcast, where the row_ids are expected to be unique and sorted in row_id.data() * \param priority the priority of the operation */ virtual void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) = 0; /** * \brief return a pinned contex */ Context pinned_ctx() const { return pinned_ctx_; } /** * \brief Sets gradient compression parameters to be able to * perform reduce with compressed gradients */ void SetGradientCompression(std::shared_ptr<GradientCompression> gc) { gc_ = gc; } protected: Context pinned_ctx_; std::shared_ptr<GradientCompression> gc_; }; /** * \brief an implemention of Comm that first copy data to CPU memeory, and then * reduce there */ class CommCPU : public Comm { public: CommCPU() { nthread_reduction_ = dmlc::GetEnv("MXNET_KVSTORE_REDUCTION_NTHREADS", 4); bigarray_bound_ = dmlc::GetEnv("MXNET_KVSTORE_BIGARRAY_BOUND", 1000 * 1000); // TODO(junwu) delete the following data member, now for benchmark only is_serial_push_ = dmlc::GetEnv("MXNET_KVSTORE_SERIAL_PUSH", 0); } virtual ~CommCPU() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int type = mshadow::kFloat32) override { // Delayed allocation - the dense merged buffer might not be used at all if push() // only sees sparse arrays bool delay_alloc = true; merge_buf_[key].merged = NDArray(shape, pinned_ctx_, delay_alloc, type); } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { auto& buf = merge_buf_[key]; const auto stype = src[0].storage_type(); // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { if (stype == kDefaultStorage) { return src[0]; } else { // With 'local' kvstore, we could store the weight on CPU while compute // the gradient on GPU when the weight is extremely large. // To avoiding copying the weight to the same context of the gradient, // we always copy the gradient to merged buf. NDArray& merged = buf.merged_buf(stype); CopyFromTo(src[0], &merged, priority); return merged; } } NDArray& buf_merged = buf.merged_buf(stype); // normal dense reduce if (stype == kDefaultStorage) { std::vector<Engine::VarHandle> const_vars(src.size() - 1); std::vector<NDArray> reduce(src.size()); CopyFromTo(src[0], &buf_merged, priority); reduce[0] = buf_merged; if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()-1); for (size_t j = 0; j < src.size() - 1; ++j) { // allocate copy buffer buf.copy_buf[j] = NDArray( src[0].shape(), pinned_ctx_, false, src[0].dtype()); } } CHECK(stype == buf.copy_buf[0].storage_type()) << "Storage type mismatch detected. " << stype << "(src) vs. " << buf.copy_buf[0].storage_type() << "(buf.copy_buf)"; for (size_t i = 1; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i-1]), priority); reduce[i] = buf.copy_buf[i-1]; const_vars[i-1] = reduce[i].var(); } Engine::Get()->PushAsync( [reduce, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { ReduceSumCPU(reduce); on_complete(); }, Context::CPU(), const_vars, {reduce[0].var()}, FnProperty::kCPUPrioritized, priority, "KVStoreReduce"); } else { // sparse reduce std::vector<Engine::VarHandle> const_vars(src.size()); std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray( src[0].storage_type(), src[0].shape(), pinned_ctx_, true, src[0].dtype()); } } CHECK(stype == buf.copy_buf[0].storage_type()) << "Storage type mismatch detected. " << stype << "(src) vs. " << buf.copy_buf[0].storage_type() << "(buf.copy_buf)"; for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; const_vars[i] = reduce[i].var(); } Resource rsc = ResourceManager::Get()->Request(buf_merged.ctx(), ResourceRequest(ResourceRequest::kTempSpace)); Engine::Get()->PushAsync( [reduce, buf_merged, rsc, this](RunContext rctx, Engine::CallbackOnComplete on_complete) { NDArray out = buf_merged; is_serial_push_? ReduceSumCPUExSerial(reduce, &out) : mxnet::ndarray::ElementwiseSum(rctx.get_stream<cpu>(), rsc, reduce, &out); on_complete(); }, Context::CPU(), const_vars, {buf_merged.var(), rsc.var}, FnProperty::kCPUPrioritized, priority, "KVStoreReduce"); } return buf_merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { int mask = src.ctx().dev_mask(); if (mask == Context::kCPU) { for (auto d : dst) CopyFromTo(src, d, priority); } else { // First copy data to pinned_ctx, then broadcast. // Note that kv.init initializes the data on pinned_ctx. // This branch indicates push() with ndarrays on gpus were called, // and the source is copied to gpu ctx. // Also indicates that buffers are already initialized during push(). auto& buf = merge_buf_[key].merged_buf(src.storage_type()); CopyFromTo(src, &buf, priority); for (auto d : dst) CopyFromTo(buf, d, priority); } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) override { using namespace mshadow; CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; CHECK_EQ(src.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with src on gpu context not supported"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; CHECK_EQ(row_id.ctx().dev_mask(), Context::kCPU) << "BroadcastRowSparse with row_indices on gpu context not supported"; // retain according to unique indices const bool is_same_ctx = out->ctx() == src.ctx(); const bool is_diff_var = out->var() != src.var(); NDArray retained_cpu = (is_same_ctx && is_diff_var) ? *out : NDArray(kRowSparseStorage, src.shape(), src.ctx(), true, src.dtype(), src.aux_types()); if (!is_diff_var) { common::LogOnce("The output of row_sparse_pull() on key " + std::to_string(key) + "refers to the same NDArray as the one stored in KVStore." "Performing row_sparse_pull() with such output is going to change the " "data stored in KVStore. Incorrect result may be generated " "next time row_sparse_pull() is called. To avoid such an issue," "consider create a new NDArray buffer to store the output."); } Engine::Get()->PushAsync( [=](RunContext rctx, Engine::CallbackOnComplete on_complete) { const TBlob& indices = row_id.data(); NDArray temp = retained_cpu; // get rid the of const qualifier op::SparseRetainOpForwardRspImpl<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); on_complete(); }, Context::CPU(), {src.var(), row_id.var()}, {retained_cpu.var()}, FnProperty::kNormal, priority, "KVStoreSparseRetain"); // if retained_cpu == out, CopyFromTo will ignore the copy operation CopyFromTo(retained_cpu, out, priority); } } private: // reduce sum into val[0] inline void ReduceSumCPU(const std::vector<NDArray> &in_data) { MSHADOW_TYPE_SWITCH(in_data[0].dtype(), DType, { std::vector<DType*> dptr(in_data.size()); for (size_t i = 0; i < in_data.size(); ++i) { TBlob data = in_data[i].data(); CHECK(data.CheckContiguous()); dptr[i] = data.FlatTo2D<cpu, DType>().dptr_; } size_t total = in_data[0].shape().Size(); ReduceSumCPUImpl(dptr, total); }); } // serial implementation of reduce sum for row sparse NDArray. inline void ReduceSumCPUExSerial(const std::vector<NDArray> &in, NDArray *out) { using namespace rowsparse; using namespace mshadow; auto stype = out->storage_type(); CHECK_EQ(stype, kRowSparseStorage) << "Unexpected storage type " << stype; size_t total_num_rows = 0; size_t num_in = in.size(); // skip the ones with empty indices and values std::vector<bool> skip(num_in, false); // the values tensor of the inputs MSHADOW_TYPE_SWITCH(out->dtype(), DType, { MSHADOW_IDX_TYPE_SWITCH(out->aux_type(kIdx), IType, { std::vector<Tensor<cpu, 2, DType>> in_vals(num_in); std::vector<Tensor<cpu, 1, IType>> in_indices(num_in); // offset to the values tensor of all inputs std::vector<size_t> offsets(num_in, 0); std::vector<size_t> num_rows(num_in, 0); for (size_t i = 0; i < num_in; i++) { if (!in[i].storage_initialized()) { skip[i] = true; continue; } auto size = in[i].aux_shape(kIdx).Size(); num_rows[i] = size; total_num_rows += size; in_vals[i] = in[i].data().FlatTo2D<cpu, DType>(); in_indices[i] = in[i].aux_data(kIdx).FlatTo1D<cpu, IType>(); } std::vector<IType> indices; indices.reserve(total_num_rows); // gather indices from all inputs for (size_t i = 0; i < num_in; i++) { for (size_t j = 0; j < num_rows[i]; j++) { indices.emplace_back(in_indices[i][j]); } } CHECK_EQ(indices.size(), total_num_rows); // dedup indices std::sort(indices.begin(), indices.end()); indices.resize(std::unique(indices.begin(), indices.end()) - indices.begin()); // the one left are unique non-zero rows size_t nnr = indices.size(); // allocate memory for output out->CheckAndAlloc({Shape1(nnr)}); auto idx_data = out->aux_data(kIdx).FlatTo1D<cpu, IType>(); auto val_data = out->data().FlatTo2D<cpu, DType>(); for (size_t i = 0; i < nnr; i++) { // copy indices back idx_data[i] = indices[i]; bool zeros = true; for (size_t j = 0; j < num_in; j++) { if (skip[j]) continue; size_t offset = offsets[j]; if (offset < num_rows[j]) { if (indices[i] == in_indices[j][offset]) { if (zeros) { Copy(val_data[i], in_vals[j][offset], nullptr); zeros = false; } else { val_data[i] += in_vals[j][offset]; } offsets[j] += 1; } } } } }); }); } template<typename DType> inline static void ReduceSumCPU( const std::vector<DType*> &dptr, size_t offset, index_t size) { using namespace mshadow; // NOLINT(*) Tensor<cpu, 1, DType> in_0(dptr[0] + offset, Shape1(size)); for (size_t i = 1; i < dptr.size(); i+=4) { switch (dptr.size() - i) { case 1: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); in_0 += in_1; break; } case 2: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); in_0 += in_1 + in_2; break; } case 3: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3; break; } default: { Tensor<cpu, 1, DType> in_1(dptr[i] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_2(dptr[i+1] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_3(dptr[i+2] + offset, Shape1(size)); Tensor<cpu, 1, DType> in_4(dptr[i+3] + offset, Shape1(size)); in_0 += in_1 + in_2 + in_3 + in_4; break; } } } } template<typename DType> inline void ReduceSumCPUImpl(std::vector<DType*> dptr, size_t total) { const size_t step = std::min(bigarray_bound_, static_cast<size_t>(4 << 10)); long ntask = (total + step - 1) / step; // NOLINT(*) if (total < bigarray_bound_ || nthread_reduction_ <= 1) { ReduceSumCPU(dptr, 0, total); } else { #pragma omp parallel for schedule(static) num_threads(nthread_reduction_) for (long j = 0; j < ntask; ++j) { // NOLINT(*) size_t k = static_cast<size_t>(j); size_t begin = std::min(k * step, total); size_t end = std::min((k + 1) * step, total); if (j == ntask - 1) CHECK_EQ(end, total); ReduceSumCPU(dptr, begin, static_cast<index_t>(end - begin)); } } } /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the merged value NDArray merged; /// \brief the cpu buffer for gpu data std::vector<NDArray> copy_buf; /// \brief the merged buffer for the given storage type inline NDArray& merged_buf(NDArrayStorageType stype) { if (stype == kDefaultStorage) { return merged; } CHECK(stype == kRowSparseStorage) << "unexpected storage type " << stype; // check if sparse_merged is initialized if (sparse_merged.is_none()) { CHECK(!merged.is_none()); sparse_merged = NDArray(kRowSparseStorage, merged.shape(), merged.ctx(), true, merged.dtype()); } return sparse_merged; } private: /// \brief the sparse merged value NDArray sparse_merged; }; std::unordered_map<int, BufferEntry> merge_buf_; size_t bigarray_bound_; int nthread_reduction_; bool is_serial_push_; }; /** * \brief an implementation of Comm that performs reduction on device * directly. * * It is faster if the total device-to-device bandwidths is larger than * device-to-cpu, which is often true for 4 or 8 GPUs. But it uses more device * memory. */ class CommDevice : public Comm { public: CommDevice() { inited_ = false; } virtual ~CommDevice() { } void Init(int key, const NDArrayStorageType stype, const TShape& shape, int dtype = mshadow::kFloat32) override { sorted_key_attrs_.emplace_back(key, shape, dtype); } void InitBuffersAndComm(const std::vector<NDArray>& src) { if (!inited_) { std::vector<Context> devs; for (const auto& a : src) { devs.push_back(a.ctx()); } InitMergeBuffer(devs); if (dmlc::GetEnv("MXNET_ENABLE_GPU_P2P", 1)) { EnableP2P(devs); } } } const NDArray& Reduce(int key, const std::vector<NDArray>& src, int priority) override { // when this reduce is called from kvstore_dist, gc is not set // we don't do compression twice in dist_sync_device if ((gc_ != nullptr) && (gc_->get_type() != CompressionType::kNone)) { return ReduceCompressed(key, src, priority); } // avoid extra copy for single device, but it may bring problems for // abnormal usage of kvstore if (src.size() == 1) { return src[0]; } InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); const NDArrayStorageType stype = src[0].storage_type(); NDArray& buf_merged = buf.merged_buf(stype); // normal dense reduce if (stype == kDefaultStorage) { CopyFromTo(src[0], &buf_merged, priority); reduce[0] = buf_merged; if (buf.copy_buf.empty()) { // TODO(mli) this results in large device memory usage for huge ndarray, // such as the largest fullc in VGG. consider to do segment reduce with // NDArray.Slice or gpu direct memory access. for the latter, we need to // remove some ctx check, and also it reduces 20% perf buf.copy_buf.resize(src.size()-1); for (size_t i = 0; i < src.size()-1; ++i) { buf.copy_buf[i] = NDArray( buf_merged.shape(), buf_merged.ctx(), false, buf_merged.dtype()); } } for (size_t i = 0; i < src.size()-1; ++i) { CopyFromTo(src[i+1], &(buf.copy_buf[i]), priority); reduce[i+1] = buf.copy_buf[i]; } } else { // sparse reduce if (buf.copy_buf.empty()) { // initialize buffer for copying during reduce buf.copy_buf.resize(src.size()); for (size_t j = 0; j < src.size(); ++j) { buf.copy_buf[j] = NDArray(stype, src[0].shape(), buf_merged.ctx(), true, src[0].dtype()); } } CHECK(src[0].storage_type() == buf.copy_buf[0].storage_type()) << "Storage type mismatch detected. " << src[0].storage_type() << "(src) vs. " << buf.copy_buf[0].storage_type() << "(buf.copy_buf)"; for (size_t i = 0; i < src.size(); ++i) { CopyFromTo(src[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } } ElementwiseSum(reduce, &buf_merged, priority); return buf_merged; } const NDArray& ReduceCompressed(int key, const std::vector<NDArray>& src, int priority) { InitBuffersAndComm(src); auto& buf = merge_buf_[key]; std::vector<NDArray> reduce(src.size()); if (buf.copy_buf.empty()) { // one buf for each context buf.copy_buf.resize(src.size()); buf.compressed_recv_buf.resize(src.size()); buf.compressed_send_buf.resize(src.size()); buf.residual.resize(src.size()); for (size_t i = 0; i < src.size(); ++i) { buf.copy_buf[i] = NDArray(buf.merged.shape(), buf.merged.ctx(), false, buf.merged.dtype()); buf.residual[i] = NDArray(buf.merged.shape(), src[i].ctx(), false, buf.merged.dtype()); buf.residual[i] = 0; int64_t small_size = gc_->GetCompressedSize(buf.merged.shape().Size()); buf.compressed_recv_buf[i] = NDArray(TShape{small_size}, buf.merged.ctx(), false, buf.merged.dtype()); buf.compressed_send_buf[i] = NDArray(TShape{small_size}, src[i].ctx(), false, buf.merged.dtype()); } } for (size_t i = 0; i < src.size(); ++i) { // compress before copy // this is done even if the data is on same context as copy_buf because // we don't want the training to be biased towards data on this GPU gc_->Quantize(src[i], &(buf.compressed_send_buf[i]), &(buf.residual[i]), priority); if (buf.compressed_send_buf[i].ctx() != buf.compressed_recv_buf[i].ctx()) { CopyFromTo(buf.compressed_send_buf[i], &(buf.compressed_recv_buf[i]), priority); } else { // avoid memory copy when they are on same context buf.compressed_recv_buf[i] = buf.compressed_send_buf[i]; } gc_->Dequantize(buf.compressed_recv_buf[i], &(buf.copy_buf[i]), priority); reduce[i] = buf.copy_buf[i]; } ElementwiseSum(reduce, &buf.merged); return buf.merged; } void Broadcast(int key, const NDArray& src, const std::vector<NDArray*> dst, int priority) override { if (!inited_) { // copy to a random device first int dev_id = key % dst.size(); CopyFromTo(src, dst[dev_id], priority); for (size_t i = 0; i < dst.size(); ++i) { if (i != static_cast<size_t>(dev_id)) { CopyFromTo(*dst[dev_id], dst[i], priority); } } } else { auto& buf_merged = merge_buf_[key].merged_buf(src.storage_type()); CopyFromTo(src, &buf_merged, priority); for (auto d : dst) { CopyFromTo(buf_merged, d, priority); } } } void BroadcastRowSparse(int key, const NDArray& src, const std::vector<std::pair<NDArray*, NDArray>>& dst, const int priority) override { CHECK_EQ(src.storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row-sparse src NDArray"; for (size_t i = 0; i < dst.size(); ++i) { NDArray* out = dst[i].first; NDArray row_id = dst[i].second; CHECK_EQ(out->storage_type(), kRowSparseStorage) << "BroadcastRowSparse expects row_sparse dst NDArray"; CHECK_EQ(row_id.ctx(), src.ctx()) << "row_id and src are expected to be on the same context"; // retain according to indices const bool is_same_ctx = out->ctx() == src.ctx(); const bool is_diff_var = out->var() != src.var(); NDArray retained_gpu = (is_same_ctx && is_diff_var) ? *out : NDArray(kRowSparseStorage, out->shape(), src.ctx(), true, out->dtype(), out->aux_types()); if (!is_diff_var) { common::LogOnce("The output of row_sparse_pull() on key " + std::to_string(key) + "refers to the same NDArray as the one stored in KVStore." "Performing row_sparse_pull() with such output is going to change the " "data stored in KVStore. Incorrect result may be generated " "next time row_sparse_pull() is called. To avoid such an issue," "consider create a new NDArray buffer to store the output."); } bool is_gpu = retained_gpu.ctx().dev_mask() == gpu::kDevMask; Engine::Get()->PushAsync([=](RunContext rctx, Engine::CallbackOnComplete on_complete) { const TBlob& indices = row_id.data(); using namespace mxnet::common; NDArray temp = retained_gpu; switch (temp.ctx().dev_mask()) { case cpu::kDevMask: { SparseRetainOpForwardRspWrapper<cpu>(rctx.get_stream<cpu>(), src, indices, kWriteTo, &temp); break; } #if MXNET_USE_CUDA case gpu::kDevMask: { SparseRetainOpForwardRspWrapper<gpu>(rctx.get_stream<gpu>(), src, indices, kWriteTo, &temp); // wait for GPU operations to complete rctx.get_stream<gpu>()->Wait(); break; } #endif default: LOG(FATAL) << MXNET_GPU_NOT_ENABLED_ERROR; } on_complete(); }, retained_gpu.ctx(), {src.var(), row_id.var()}, {retained_gpu.var()}, is_gpu ? FnProperty::kGPUPrioritized : FnProperty::kCPUPrioritized, priority, "KVStoreSparseRetain"); CopyFromTo(retained_gpu, out, priority); } } private: void EnableP2P(const std::vector<Context>& devs) { #if MXNET_USE_CUDA std::vector<int> gpus; for (const auto& d : devs) { if (d.dev_mask() == gpu::kDevMask) { gpus.push_back(d.dev_id); } } int n = static_cast<int>(gpus.size()); int enabled = 0; std::vector<int> p2p(n*n); for (int i = 0; i < n; ++i) { cudaSetDevice(gpus[i]); for (int j = 0; j < n; j++) { int access; cudaDeviceCanAccessPeer(&access, gpus[i], gpus[j]); if (access) { cudaError_t e = cudaDeviceEnablePeerAccess(gpus[j], 0); if (e == cudaSuccess || e == cudaErrorPeerAccessAlreadyEnabled) { ++enabled; p2p[i*n+j] = 1; } } } } if (enabled != n*(n-1)) { // print warning info if not fully enabled LOG(WARNING) << "only " << enabled << " out of " << n*(n-1) << " GPU pairs are enabled direct access. " << "It may affect the performance. " << "You can set MXNET_ENABLE_GPU_P2P=0 to turn it off"; std::string access(n, '.'); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { access[j] = p2p[i*n+j] ? 'v' : '.'; } LOG(WARNING) << access; } } #endif } using KeyAttrs = std::tuple<int, TShape, int>; // try to allocate buff on device evenly void InitMergeBuffer(const std::vector<Context>& devs) { std::sort(sorted_key_attrs_.begin(), sorted_key_attrs_.end(), []( const KeyAttrs& a, const KeyAttrs& b) { return std::get<1>(a).Size() > std::get<1>(b).Size(); }); std::unordered_map<int, std::pair<Context, size_t>> ctx_info; for (auto d : devs) { ctx_info[d.dev_id] = std::make_pair(d, 0); } for (size_t i = 0; i < sorted_key_attrs_.size(); ++i) { const int key = std::get<0>(sorted_key_attrs_[i]); const TShape& shape = std::get<1>(sorted_key_attrs_[i]); const int type = std::get<2>(sorted_key_attrs_[i]); auto& buf = merge_buf_[key]; Context ctx; size_t min_size = std::numeric_limits<size_t>::max(); for (auto it = ctx_info.begin(); it != ctx_info.end(); ++it) { size_t size = it->second.second; if (size <= min_size) { ctx = it->second.first; min_size = size; } } // Delayed allocation - as the dense merged buffer might not be used at all if push() // only sees sparse arrays bool delay_alloc = true; buf.merged = NDArray(shape, ctx, delay_alloc, type); ctx_info[ctx.dev_id].second += shape.Size(); } inited_ = true; } std::vector<KeyAttrs> sorted_key_attrs_; /// \brief temporal space for pushing and pulling struct BufferEntry { /// \brief the dense merged value for reduce and broadcast operations NDArray merged; /// \brief the gpu buffer for copy during reduce operation std::vector<NDArray> copy_buf; /// \brief the residual buffer for gradient compression std::vector<NDArray> residual; /// \brief the small buffer for compressed data in sender std::vector<NDArray> compressed_send_buf; /// \brief the small buffer for compressed data in receiver std::vector<NDArray> compressed_recv_buf; /// \brief the merged buffer for the given storage type (could be either dense or row_sparse) inline NDArray& merged_buf(NDArrayStorageType stype) { if (stype == kDefaultStorage) { CHECK(!merged.is_none()) << "unintialized merge buffer detected"; return merged; } CHECK(stype == kRowSparseStorage) << "unexpected storage type " << stype; // check if sparse_merged is initialized if (sparse_merged.is_none()) { CHECK(!merged.is_none()); sparse_merged = NDArray(kRowSparseStorage, merged.shape(), merged.ctx(), true, merged.dtype()); } return sparse_merged; } private: /// \brief the sparse merged value for reduce and rowsparse broadcast operations NDArray sparse_merged; }; std::unordered_map<int, BufferEntry> merge_buf_; bool inited_; }; } // namespace kvstore } // namespace mxnet #endif // MXNET_KVSTORE_COMM_H_
rt_dtrsm.c
#include "runtime.h" #ifdef PLASMA_WITH_SMP #pragma omp target device (smp) copy_deps #pragma omp task in([lda*m]A) inout([ldb*n]B) label(ldtrsm_smp) void CORE_ldtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { CORE_dtrsm(PlasmaLeft, uplo, transA, diag, m, n, alpha, A, lda, B, ldb); } #pragma omp target device (smp) copy_deps #pragma omp task in([lda*n]A) inout([ldb*n]B) label(rdtrsm_smp) void CORE_rdtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { CORE_dtrsm(PlasmaRight, uplo, transA, diag, m, n, alpha, A, lda, B, ldb); } #endif #ifdef PLASMA_WITH_CUDA_HYBRID #pragma omp target device (smp) copy_deps #pragma omp task in([lda*m]A) inout([ldb*n]B) label(ldtrsm_hyb_smp) void CORE_ldtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { CORE_dtrsm(PlasmaLeft, uplo, transA, diag, m, n, alpha, A, lda, B, ldb); } #pragma omp target device (smp) copy_deps #pragma omp task in([lda*n]A) inout([ldb*n]B) label(rdtrsm_hyb_smp) void CORE_rdtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { CORE_dtrsm(PlasmaRight, uplo, transA, diag, m, n, alpha, A, lda, B, ldb); } //Alternative implementations #pragma omp target device (cuda) copy_deps implements(CORE_ldtrsm_ompss) #pragma omp task in([lda*m]A) inout([ldb*n]B) label(ldtrsm_hyb_cuda) void CORE_ldtrsm_cuda(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { cublasFillMode_t cuplo; cublasOperation_t cutrans; cublasDiagType_t cudiag; if ( uplo == PlasmaUpper ) cuplo = CUBLAS_FILL_MODE_UPPER; else cuplo = CUBLAS_FILL_MODE_LOWER; if ( transA == PlasmaNoTrans ) cutrans = CUBLAS_OP_N; else cutrans = CUBLAS_OP_T; if ( diag == PlasmaNonUnit ) cudiag = CUBLAS_DIAG_NON_UNIT; else cudiag = CUBLAS_DIAG_UNIT; cublasHandle_t handle = nanos_get_cublas_handle(); cudaStream_t stream = nanos_get_kernel_execution_stream(); cublasSetStream(handle, stream); cublasDtrsm(handle, CUBLAS_SIDE_LEFT, cuplo, cutrans, cudiag, m, n, &alpha, A, lda, B, ldb); } #pragma omp target device (cuda) copy_deps implements(CORE_rdtrsm_ompss) #pragma omp task in([lda*n]A) inout([ldb*n]B) label(rdtrsm_hyb_cuda) void CORE_rdtrsm_cuda(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { cublasFillMode_t cuplo; cublasOperation_t cutrans; cublasDiagType_t cudiag; if ( uplo == PlasmaUpper ) cuplo = CUBLAS_FILL_MODE_UPPER; else cuplo = CUBLAS_FILL_MODE_LOWER; if ( transA == PlasmaNoTrans ) cutrans = CUBLAS_OP_N; else cutrans = CUBLAS_OP_T; if ( diag == PlasmaNonUnit ) cudiag = CUBLAS_DIAG_NON_UNIT; else cudiag = CUBLAS_DIAG_UNIT; cublasHandle_t handle = nanos_get_cublas_handle(); cudaStream_t stream = nanos_get_kernel_execution_stream(); cublasSetStream(handle, stream); cublasDtrsm(handle, CUBLAS_SIDE_RIGHT, cuplo, cutrans, cudiag, m, n, &alpha, A, lda, B, ldb); } #endif #ifdef PLASMA_WITH_CUDA_PURE #pragma omp target device (cuda) copy_deps #pragma omp task in([lda*m]A) inout([ldb*n]B) label(ldtrsm_cuda) void CORE_ldtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { cublasFillMode_t cuplo; cublasOperation_t cutrans; cublasDiagType_t cudiag; if ( uplo == PlasmaUpper ) cuplo = CUBLAS_FILL_MODE_UPPER; else cuplo = CUBLAS_FILL_MODE_LOWER; if ( transA == PlasmaNoTrans ) cutrans = CUBLAS_OP_N; else cutrans = CUBLAS_OP_T; if ( diag == PlasmaNonUnit ) cudiag = CUBLAS_DIAG_NON_UNIT; else cudiag = CUBLAS_DIAG_UNIT; cublasHandle_t handle = nanos_get_cublas_handle(); cudaStream_t stream = nanos_get_kernel_execution_stream(); cublasSetStream(handle, stream); cublasDtrsm(handle, CUBLAS_SIDE_LEFT, cuplo, cutrans, cudiag, m, n, &alpha, A, lda, B, ldb); } #pragma omp target device (cuda) copy_deps #pragma omp task in([lda*n]A) inout([ldb*n]B) label(rdtrsm_cuda) void CORE_rdtrsm_ompss(PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, double alpha, double *A, int lda, double *B, int ldb, int nb) { cublasFillMode_t cuplo; cublasOperation_t cutrans; cublasDiagType_t cudiag; if ( uplo == PlasmaUpper ) cuplo = CUBLAS_FILL_MODE_UPPER; else cuplo = CUBLAS_FILL_MODE_LOWER; if ( transA == PlasmaNoTrans ) cutrans = CUBLAS_OP_N; else cutrans = CUBLAS_OP_T; if ( diag == PlasmaNonUnit ) cudiag = CUBLAS_DIAG_NON_UNIT; else cudiag = CUBLAS_DIAG_UNIT; cublasHandle_t handle = nanos_get_cublas_handle(); cudaStream_t stream = nanos_get_kernel_execution_stream(); cublasSetStream(handle, stream); cublasDtrsm(handle, CUBLAS_SIDE_RIGHT, cuplo, cutrans, cudiag, m, n, &alpha, A, lda, B, ldb); } #endif void RT_CORE_dtrsm(Quark *quark, Quark_Task_Flags *task_flags, PLASMA_enum side, PLASMA_enum uplo, PLASMA_enum transA, PLASMA_enum diag, int m, int n, int nb, double alpha, double *A, int lda, double *B, int ldb) { plasma_context_t *plasma; plasma = plasma_context_self(); if (plasma->runtime == PLASMA_QUARK) { QUARK_CORE_dtrsm( quark, task_flags, side, uplo, transA, diag, m, n, nb, alpha, A, lda, B, ldb); } else if (plasma->runtime == PLASMA_OMPSS) { // cublasSideMode_t cuside; if (side == PlasmaLeft){ CORE_ldtrsm_ompss(uplo, transA, diag, m, n, alpha, A, lda, B, ldb, nb); } else { CORE_rdtrsm_ompss(uplo, transA, diag, m, n, alpha, A, lda, B, ldb, nb); } } }
pi.c
#include <stdio.h> long long num_passos = 1000000000; double passo; int main(){ int i; double x, pi, soma=0.0; passo = 1.0/(double)num_passos; #pragma omp parallel for private(x) reduction(+:soma) for(i=0; i < num_passos; i++){ x = (i + 0.5)*passo; soma = soma + 4.0/(1.0 + (x)*(x)); } pi = soma*passo; printf("O valor de PI é: %f\n", pi); return 0; }
profiler.c
/// \file profiler.c /// \brief Performance profiler #ifdef PROFILER_ENABLE #include "profiler.h" #include "util.h" #include "dupio.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> //________________________________________________________________________________________________________________________ /// /// \brief Corresponding tag strings /// static const char *tag_strings[NUM_PROFILE_TAGS] = { "SVD basic", "SVD standard", "QR decomposition", "split matrix", "split reassemble", "compress virtual bonds", "allocate tensor", "transpose tensor", "multiply tensor", "split MPO tensor", "merge MPO tensor pair", "compress MPO tensors" }; //________________________________________________________________________________________________________________________ /// /// \brief Initialize profiler /// void InitProfiler(profiler_t *profiler) { memset(profiler->table, 0, sizeof(profiler->table)); profiler->main_start_tick = GetTimeTicks(); } //________________________________________________________________________________________________________________________ /// /// \brief Start a profiling block /// void StartProfilingBlock(profiler_t *profiler, const profile_tag_t tag) { #ifdef _OPENMP int thread_num = omp_get_thread_num(); if (thread_num >= MAX_PROFILE_THREADS) { duprintf("Warning: in 'StartProfilingBlock()': capping actual thread number %i to %i\n", thread_num, MAX_PROFILE_THREADS - 1); thread_num = MAX_PROFILE_THREADS - 1; } #pragma omp critical(profiler_critical) { profile_entry_t *p = &profiler->table[tag][thread_num]; if (p->start_tick == 0) { p->ncalls++; p->start_tick = GetTimeTicks(); } else { duprintf("Warning: in 'StartProfilingBlock()': nested function call for profiling tag '%s' and thread %i\n", tag_strings[tag], thread_num); } } #else profile_entry_t *p = &profiler->table[tag]; if (p->start_tick == 0) { p->ncalls++; p->start_tick = GetTimeTicks(); } else { duprintf("Warning: in 'StartProfilingBlock()': nested function call for profiling tag '%s'\n", tag_strings[tag]); } #endif } //________________________________________________________________________________________________________________________ /// /// \brief End a profiling block /// void EndProfilingBlock(profiler_t *profiler, const profile_tag_t tag) { #ifdef _OPENMP int thread_num = omp_get_thread_num(); if (thread_num >= MAX_PROFILE_THREADS) { duprintf("Warning: in 'EndProfilingBlock()': capping actual thread number %i to %i\n", thread_num, MAX_PROFILE_THREADS - 1); thread_num = MAX_PROFILE_THREADS - 1; } #pragma omp critical(profiler_critical) { profile_entry_t *p = &profiler->table[tag][thread_num]; if (p->start_tick != 0) { p->total += GetTimeTicks() - p->start_tick; p->start_tick = 0; // reset to 0 to indicate completion of a profiling block } else { duprintf("Warning: in 'EndProfilingBlock()': profile entry inactive for profiling tag '%s' and thread %i; EndProfilingBlock() called before StartProfilingBlock()?\n", tag_strings[tag], thread_num); } } #else profile_entry_t *p = &profiler->table[tag]; if (p->start_tick != 0) { p->total += GetTimeTicks() - p->start_tick; p->start_tick = 0; // reset to 0 to indicate completion of a profiling block } else { duprintf("Warning: in 'EndProfilingBlock()': profile entry inactive for profiling tag '%s'; EndProfilingBlock() called before StartProfilingBlock()?\n", tag_strings[tag]); } #endif // _OPENMP } //________________________________________________________________________________________________________________________ /// /// \brief Extended profile entry (temporary structure used for report) /// typedef struct { int64_t total; //!< total time ticks int ncalls; //!< number of calls profile_tag_t tag; //!< profile tag #ifdef _OPENMP int thread_num; //!< thread number #endif } profile_entry_ext_t; //________________________________________________________________________________________________________________________ /// /// \brief Sort profile entries by total time /// // static int CompareProfileEntries(const void *a, const void *b) { const profile_entry_ext_t *pa = (profile_entry_ext_t *)a; const profile_entry_ext_t *pb = (profile_entry_ext_t *)b; int64_t diff = pb->total - pa->total; return (diff > 0) ? 1 : ((diff < 0) ? -1 : 0); } //________________________________________________________________________________________________________________________ /// /// \brief Print profiler report /// void PrintProfilerReport(const profiler_t *profiler) { // get total wall time const int64_t main_total = GetTimeTicks() - profiler->main_start_tick; // get the tick resolution const double ticks_per_sec = (double)GetTimeResolution(); #ifdef _OPENMP // collect extended profile entries and sort by clock time profile_entry_ext_t entries[NUM_PROFILE_TAGS * MAX_PROFILE_THREADS]; int n = 0; profile_tag_t tag; for (tag = (profile_tag_t)0; tag < NUM_PROFILE_TAGS; tag++) { int j; for (j = 0; j < MAX_PROFILE_THREADS; j++) { if (profiler->table[tag][j].ncalls > 0) { if (profiler->table[tag][j].start_tick != 0) { duprintf("Warning: in 'PrintProfilerReport()': start_tick non-zero for tag '%s' and thread number %i\n", tag_strings[tag], j); } entries[n].total = profiler->table[tag][j].total; entries[n].ncalls = profiler->table[tag][j].ncalls; entries[n].tag = tag; entries[n].thread_num = j; n++; } } } qsort(entries, n, sizeof(profile_entry_ext_t), CompareProfileEntries); // print report duprintf("_______________________________________________________________________________\n"); duprintf("Profiling report:\n"); duprintf("%-26s%-7s%-8s%-10s%s\n", "name", "thread", "ncalls", "% of wall", "time per call (ms)"); int i; for (i = 0; i < n; i++) { duprintf("%-26s%-7d%-8d%-10g%-g\n", tag_strings[entries[i].tag], entries[i].thread_num, entries[i].ncalls, (100.0 * entries[i].total) / main_total, entries[i].total / (ticks_per_sec / 1000.0 * entries[i].ncalls)); } duprintf("\n"); duprintf("Wall clock time: %g seconds\n", main_total / ticks_per_sec); duprintf("_______________________________________________________________________________\n"); #else // _OPENMP // collect extended profile entries and sort by clock time profile_entry_ext_t entries[NUM_PROFILE_TAGS]; int n = 0; profile_tag_t tag; for (tag = (profile_tag_t)0; tag < NUM_PROFILE_TAGS; tag++) { if (profiler->table[tag].ncalls > 0) { if (profiler->table[tag].start_tick != 0) { duprintf("Warning: in 'PrintProfilerReport()': start_tick non-zero for tag '%s'\n", tag_strings[tag]); } entries[n].total = profiler->table[tag].total; entries[n].ncalls = profiler->table[tag].ncalls; entries[n].tag = tag; n++; } } qsort(entries, n, sizeof(profile_entry_ext_t), CompareProfileEntries); // print report duprintf("_______________________________________________________________________________\n"); duprintf("Profiling report:\n"); duprintf("%-26s%-8s%-10s%s\n", "name", "ncalls", "% of wall", "time per call (ms)"); int i; for (i = 0; i < n; i++) { duprintf("%-26s%-8d%-10g%-g\n", tag_strings[entries[i].tag], entries[i].ncalls, (100.0 * entries[i].total) / main_total, entries[i].total / (ticks_per_sec / 1000.0 * entries[i].ncalls)); } duprintf("\n"); duprintf("Wall clock time: %g seconds\n", main_total / ticks_per_sec); duprintf("_______________________________________________________________________________\n"); #endif } /// \brief Global standard profiler profiler_t std_profiler; #endif // PROFILER_ENABLE
openmp_reduction1.c
///TAFFO_TEST_ARGS -fopenmp #include <stdio.h> #define N (100) int main(int argc, char *argv[]) { float result __attribute__((annotate("target('result') scalar(range(0,20000) final)"))) = 0.0; float container[N] __attribute__((annotate("target('container') scalar(range(0,20000) final)"))); float container_result __attribute__((annotate("target('container_result') scalar(range(0,20000) final)"))) = 0.0; int i = 0; #pragma omp parallel for for (i = 0; i < N; i++) { container[i] = 0; } #pragma omp parallel for reduction(+:result) for (i = 0; i < N; i++) { result += i * 3.5; container[i] += i * 3.5; } for (i = 0; i < N; i++) container_result += container[i]; printf("result: %f\n", result); printf("container: %f\n", container_result); }
ops.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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 ******************************************************************************/ #pragma once #ifndef OPS_H_ #define OPS_H_ #include <op_boilerplate.h> #include <array/DataTypeUtils.h> #include <helpers/shape.h> #include <vector> #include <Environment.h> #include <loops/summarystatsreduce.h> #define MIN 1e-12 #define MAX_FLOAT 1e37 #define MIN_FLOAT 1e-37 #define MAX_INT 2147483647 #define MIN_CUTFOFF -3.79297773665f #define FLOAT_MIN_NORMAL 1.17549435e-38 #define EPS 1e-5 #define AFFINITY close #define DOUBLE_PI_T T(2.0 * 3.14159265358979323846) #define DOUBLE_PI_X X(2.0 * 3.14159265358979323846) #define no_op_exec_special_any static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special static const bool requiresSpecial = false; static void execSpecial(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, Z *extraParams, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_long static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #define no_op_exec_special_accumulation_same static const bool requiresSpecialAccumulation = false; static void execSpecial(X *x, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfoBuffer, int *dimension, int dimensionLength, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffset){} #ifdef __CUDACC__ #include <helpers/sharedmem.h> #define no_op_exec_special_any_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_bool_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, Z *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_same_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer, X *result, Nd4jLong *resultShapeBuffer, X *extraParams, int *allocationPointer, X *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_cuda static __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeBuffer,Z *result, Nd4jLong *resultShapeBuffer,Z *extraParams, int *allocationPointer, Z *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_same_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, X *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, X *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_long_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, X *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #define no_op_exec_special_accumulation_cuda static inline __device__ void execSpecialCuda(X *dx, Nd4jLong *xShapeInfo, Z *extraParams, Z *result, Nd4jLong *resultShapeInfo, int *dimension, int dimensionLength, Z *reductionBuffer, Nd4jLong *tadOnlyShapeInfo, Nd4jLong *tadOffsets) {} #else // hacky fix for isnan/being being out of scope //#ifdef IOS //#define isinf(x) 0 // this isn't right. But std::isinf fails //#define isnan(x) 0 //#else //#define isnan std::isnan //#define isinf std::isinf //#endif #define no_op_exec_special_cuda #define no_op_exec_special_accumulation_cuda #define no_op_exec_special_accumulation_same_cuda #define no_op_exec_special_accumulation_long_cuda #define no_op_exec_special_any_cuda #define no_op_exec_special_bool_cuda #define no_op_exec_special_same_cuda #define no_op_exec_special_accumulation_same_cuda #endif #define SELU_ALPHA 1.6732632423543772848170429916717 #define SELU_LAMBDA 1.0507009873554804934193349852946 #ifdef _OPENMP #pragma omp declare reduction(maxT : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_max(omp_in, omp_out) )\ initializer (omp_priv=-MAX_FLOAT) #pragma omp declare reduction(minT : float,double,float16,bfloat16 : \ omp_out = nd4j::math::nd4j_min(omp_in, omp_out) )\ initializer (omp_priv=MAX_FLOAT) #pragma omp declare reduction(sumT : float,double,float16,bfloat16,int,Nd4jLong,Nd4jULong,int8_t,uint8_t,bool,int16_t,uint16_t,uint32_t : \ omp_out = omp_in + omp_out)\ initializer (omp_priv=0) #endif namespace functions { namespace indexreduce { template <typename T> struct IndexValue { T value; Nd4jLong index; _CUDA_HD IndexValue() = default; _CUDA_HD IndexValue(const T val, const Nd4jLong ind): index(ind), value(val) {} }; } namespace summarystats { template <typename T> class SummaryStatsData; } } namespace simdOps { template <typename X, typename Y, typename Z> class Add { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 + d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 + params[0]); } op_def static X startingValue() { return static_cast<X>(0.f); } }; template <typename X, typename Y> class NewAdd { public: op_def static X op(X d1, Y d2, X *params) { return d1 + d2; } }; template <typename X, typename Y, typename Z> class Subtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 - d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 - params[0]); } }; template <typename X, typename Y, typename Z> class SquaredSubtract { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<Z, float, Z>(static_cast<Z>(d1 - d2), 2.f); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<Z, float, Z>(static_cast<Z>(d1 - d2), 2.f); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_pow<Z, float, Z>(static_cast<Z>(d1 - params[0]), 2.f); } }; template <typename X, typename Y, typename Z> class ReverseSubtract { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 - d1); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] - d1); } }; template <typename X, typename Y, typename Z> class LogPoisonLossFull { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc + (zz * nd4j::math::nd4j_log<X, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz))); } op_def static Z op(X z) { auto zz = static_cast<Z>(z); return (zz * nd4j::math::nd4j_log<Y, Z>(z) - zz + static_cast<Z>(0.5f) * nd4j::math::nd4j_log<Z, Z>(static_cast<Z>(DOUBLE_PI_X) * zz)); } // op for MetaOps op_def static X op(X z, Y *params) { return (nd4j::math::nd4j_exp<X, X>(params[0]) - z * params[0] + (z * nd4j::math::nd4j_log<X, Z>(z) - z + static_cast<X>(0.5f) * nd4j::math::nd4j_log<X, Z>(DOUBLE_PI_X * z))); } }; template <typename X, typename Y, typename Z> class LogPoisonLoss { public: op_def static Z op(X z, Y c) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z, Y c, Z *params) { auto zz = static_cast<Z>(z); auto zc = static_cast<Z>(c); return (nd4j::math::nd4j_exp<Y, Z>(c) - zz * zc); } op_def static Z op(X z) { return static_cast<Z>(z); } // op for MetaOps op_def static Z op(X z, Y *params) { return (nd4j::math::nd4j_exp<Y, Z>(params[0]) - static_cast<Z>(z) * static_cast<Z>(params[0])); } }; template <typename X, typename Y, typename Z> class Multiply { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 * d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 * params[0]); } op_def static X startingValue() { return static_cast<X>(1.f); } }; template <typename X, typename Y, typename Z> class Divide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1 / params[0]); } op_def static X startingValue() { return static_cast<X>(1); } }; template <typename X, typename Y, typename Z> class SafeDivide { public: op_def static Z op(X d1, Y d2) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1, Y d2, Z *params) { if(d2 == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { if(params[0] == static_cast<Y>(0)) return static_cast<Z>(0); return static_cast<Z>(d1 / params[0]); } }; template <typename X, typename Y, typename Z> class FloorDiv { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / d2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1)); } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_floor<Z,Z>(static_cast<Z>(d1 / params[0])); } }; template <typename X, typename Y, typename Z> class TruncateDiv { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 / i2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 / i2); } }; template <typename X, typename Y, typename Z> class TruncateMod { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1, Y d2, Z *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return static_cast<Z>(i1 % i2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(params[0]); return static_cast<Z>(i1 % i2); } }; template<typename X, typename Y, typename Z> class Remainder { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_remainder<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FMod { public: op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return nd4j::math::nd4j_fmod<X, Y, Z>(d1, params[0]); } }; template <typename X, typename Y, typename Z> class FloorMod { public: op_def static Z op(X d1, Y d2) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1, Y d2, Z *params) { auto m = nd4j::math::nd4j_fmod<X, Y, Z>(d1, d2); return (d1 < static_cast<X>(0.0f)) == (d2 < static_cast<Y>(0)) ? m : nd4j::math::nd4j_fmod<Z, Y, Z>(m + static_cast<Z>(d2), d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseDivide { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2 / d1); } op_def static Z op(X d1) { return static_cast<Z>(d1); } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(params[0] / d1); } }; template <typename X, typename Y, typename Z> class CopyPws { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X> class Copy { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X, typename Y, typename Z> class Copy2 { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } op_def static Z op(X d1, Y *params) { return static_cast<Z>(d1); } }; template <typename X, typename Y, typename Z> class Axpy { public: op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2 + d1); } op_def static Z op(X d1, Y d2, Z *params) { auto alpha = params[0]; return alpha * static_cast<Z>(d1) + static_cast<Z>(d2); } op_def static Z op(X d1) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class Assign { public: no_op_exec_special_any no_op_exec_special_any_cuda op_def static Z op(X d1, X *params) { return static_cast<Z>(d1); } }; template <typename X, typename Z> class And { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp && d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (b1 && b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Or { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return d1 != comp || d2 != comp ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return b1 || b2 ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, X *params) { return static_cast<Z>(119); } }; template <typename X, typename Z> class Xor { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return d2 + d1; } op_def static Z op(X d1, X d2, X *params) { if (params != nullptr) { auto comp = params[0]; return ((d1 == comp && d2 != comp) || (d1 != comp && d2 == comp)) ? static_cast<Z>(1) : static_cast<Z>(0); } else { auto b1 = static_cast<bool>(d1); auto b2 = static_cast<bool>(d2); return (!b1 && b2 )||(b1 && !b2) ? static_cast<Z>(1) : static_cast<Z>(0); } } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Z> class Not { public: no_op_exec_special_bool no_op_exec_special_bool_cuda op_def static Z op(X d1, X d2) { return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return d1 != d2 ? static_cast<Z>(1) : static_cast<Z>(0); } // this transform op should run only on boolean input op_def static Z op(X d1, X *params) { auto b1 = static_cast<bool>(d1); return !b1; } }; template <typename X, typename Y, typename Z> class LogicalNot { public: op_def static Z op(X d1, Y d2) { return !((int) d1 && (int) d2); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<X>(!(static_cast<int>(d1) && static_cast<int>(d2))); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class LogicalXor { public: op_def static Z op(X d1, Y d2) { auto i1 = static_cast<int>(d1); auto i2 = static_cast<int>(d2); return (i1 | i2) &~ (i1 & i2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalAnd { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) & static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(Y d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<Z>(119); } }; template <typename X, typename Y, typename Z> class LogicalOr { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) | static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return d1; } // op for MetaOps op_def static Z op(X d1, Y *params) { return static_cast<X>(119); } }; template <typename X, typename Y, typename Z> class Mod { public: /* // just a optional note, feel free to remove later op_def static half op(half d1, half d2, half *params) { return __float2half(simdOps::Mod<float>::op(__half2float(d1), __half2float(d2), nullptr)); } */ op_def static Z op(X d1, Y d2) { return static_cast<int>(d1) % static_cast<int>(d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X, typename Y, typename Z> class ReverseMod { public: op_def static Z op(X d1, Y d2) { return static_cast<int>(d2) % static_cast<int>(d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOp op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; /** * Whether 2 elements in an array * are epsilion equal */ template <typename X, typename Z> class Epsilon { public: op_def static Z op(X d1, X d2) { X diff = d1 - d2; X absDiff = nd4j::math::nd4j_abs<X>(diff); if (absDiff <= static_cast<X>(MIN)) return static_cast<Z>(1); return static_cast<Z>(0); } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class EqualTo { public: op_def static Z op(X d1, X d2) { return d1 == d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class NotEqualTo { public: op_def static Z op(X d1, X d2) { return d1 != d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 >= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class GreaterThan { public: op_def static Z op(X d1, X d2) { return d1 > d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } // FIXME: this signature clashes with MetaOp stuff op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThan { public: op_def static Z op(X d1, X d2) { return d1 < d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X, typename Z> class LessThanOrEqual { public: op_def static Z op(X d1, X d2) { return d1 <= d2; } op_def static Z op(X d1, X d2, X *params) { return op(d1, d2); } op_def static Z op(X d1, X *params) { return d1; } }; template <typename X> class Abs { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_abs<X>(d1); } }; template <typename X> class Ceiling { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_ceil<X,X>(d1); } }; template <typename X> class Cosine { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cos<X,X>(d1); } }; template <typename X> class Exp { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X> class HardTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return ((d1 >= static_cast<X>(-1.f) && d1 <= static_cast<X>(1.f)) ? static_cast<X>(1.f) : static_cast<X>(0.f)); } }; template <typename X> class HardTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 < static_cast<X>(-1)) return static_cast<X>(-1); else if (d1 > static_cast<X>(1)) return static_cast<X>(1); else return d1; } }; template <typename X> class Floor { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_floor<X,X>(d1); } }; template <typename X> class Log { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(d1); } }; template <typename X> class Log1p { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(1 + d1); } }; template <typename X, typename Y, typename Z> class LogX { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_log<X, Z>(d1) / nd4j::math::nd4j_log<Y, Z>(d2) ; } }; template <typename X> class StabilizeFP16 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return static_cast<X>(nd4j::DataTypeUtils::min<float16>()); else return d1; } }; template <typename X> class StabilizeX { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 <= static_cast<X>(0)) return nd4j::DataTypeUtils::min<X>(); else return d1; } }; template <typename X> class SpecialDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1.f) - d1); } }; template <typename X> class Neg { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return -d1; } }; template <typename X> class Erf { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erf<X,X>(d1); } }; template <typename X> class Erfc { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_erfc<X,X>(d1); } }; template <typename X> class Reciprocal { public: no_op_exec_special_same no_op_exec_special_same_cuda // op_def static T op(T d1) { // return (T(1.0f) / d1); // } // op for MetaOps op_def static X op(X d1, X *params) { return (static_cast<X>(1) / d1); } }; template <typename X, typename Z> class Sqr { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } op_def static Z op(X d1) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)); } }; template <typename X, typename Y, typename Z> class RelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_re<X>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X threshold = params[0]; return nd4j::math::nd4j_re<X>(d1, d2) > threshold ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class BinaryMinimumAbsoluteRelativeError { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, X *params) { X d2 = params[0]; X thresholdRelative = params[1]; X thresholdAbsolute = params[2]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1, Y d2, Z *params) { X thresholdRelative = params[0]; X thresholdAbsolute = params[1]; return nd4j::math::nd4j_re<X>(d1, d2) > thresholdRelative ? (nd4j::math::nd4j_abs<X>(d1 - static_cast<X>(d2)) < thresholdAbsolute ? static_cast<Z>(0) : static_cast<Z>(1)) : static_cast<Z>(0); } op_def static Z op(X d1) { return static_cast<Z>(0); } }; template <typename X, typename Y, typename Z> class Pow { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_pow<X, X, Z>(d1, params[0]); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_pow<X, Y, Z>(d1, d2); } op_def static Z op(X d1) { return d1; } }; template <typename X, typename Y, typename Z> class PowDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return params[0] * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(params[0]) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1, Y d2, Z *params) { return static_cast<Z>(d2) * nd4j::math::nd4j_pow<X, Z, Z>(d1, static_cast<Z>(d2) - static_cast<Z>(1.f)); } op_def static Z op(X d1) { return d1; } }; template <typename X> class Round { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_round<X,X>(d1); } }; template <typename X, typename Z> class IsNan { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<X>(1) : static_cast<X>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class Expm1 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(1); } }; template <typename X, typename Z> class IsPositive { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return d1 > (X)0.f; } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInf { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isinf<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsInfOrNan{ public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(0) : static_cast<Z>(1); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class IsFinite { public: no_op_exec_special_bool no_op_exec_special_bool_cuda no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static Z op(X d1, X *params) { return nd4j::math::nd4j_isfin<X>(d1) ? static_cast<Z>(1) : static_cast<Z>(0); } op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ClipByValue { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { if (d1 > params[1]) return params[1]; if (d1 < params[0]) return params[0]; return d1; } }; template <typename X, typename Y, typename Z> class LstmClip { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { X _v = (X) d2; if (d1 > _v) return _v; else if (d1 < _v) return _v; else return d1; } }; template <typename X> class Swish { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * nd4j::math::nd4j_sigmoid<X,X>(d1); } }; template <typename X> class SwishDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(static_cast<X>(M_E), d1); return (ex * (d1 + ex + static_cast<X>(1.f))) / nd4j::math::nd4j_pow<X, X, X>((ex + static_cast<X>(1.f)) , static_cast<X>(2.f)); } }; template <typename X> class LogSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_log<X, X>(nd4j::math::nd4j_sigmoid<X, X>(d1)); } }; template <typename X> class LogSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X ex = nd4j::math::nd4j_pow<X, X, X>(M_E, d1); return static_cast<X>(1.f) / (ex + static_cast<X>(1.f)); } }; template <typename X> class Sigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoid<X, X>(d1); } }; template <typename X> class SigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sigmoidderivative<X, X>(d1); } }; template <typename X> class HardSigmoid { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_min<X>(static_cast<X>(1), nd4j::math::nd4j_max<X>(static_cast<X>(0), (static_cast<X>(0.2f)) * d1 + static_cast<X>(0.5f))); } }; template <typename X> class HardSigmoidDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 < static_cast<X>(-2.5f) || d1 > static_cast<X>(2.5f) ? static_cast<X>(0.f) : static_cast<X>(0.2f); } }; /** * Scale to be between a min and max */ template <typename X> class SetRange { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto min = params[0]; auto max = params[1]; if (static_cast<X>(d1) >= min && static_cast<X>(d1) <= max) return d1; if (min == static_cast<X>(0) && max == static_cast<X>(1)) { auto val = static_cast<X>(1) / (static_cast<X>(1) + nd4j::math::nd4j_exp<X, X>(-d1)); return (nd4j::math::nd4j_floor<X,X>(val * (max - min)) + min); } return (nd4j::math::nd4j_floor<X,X>(d1 * (max - min)) + min); } }; template <typename X> class Sin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sin<X,X>(d1); } }; template <typename X> class Square { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1; } }; template <typename X, typename Z> class Sqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X, typename Z> class RSqrt { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Z *params) { return static_cast<Z>(1) / nd4j::math::nd4j_sqrt<X, Z>(d1); } }; template <typename X> class Rint { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_rint<X,X>(d1); } }; template <typename X> class SoftPlus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::softplus<X, X>(d1); } }; template <typename X> class Sign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return (d1 > static_cast<X>(0)) - (d1 < static_cast<X>(0)); } }; template <typename X> class TimesOneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * (static_cast<X>(1) - d1); } }; template <typename X> class RationalTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { // keep 2/3 as runtime variable, to match precision auto dis = (static_cast<X>(2) / static_cast<X>(3)) * d1; auto tanh = nd4j::math::nd4j_sgn<X,X>(dis) * (static_cast<X>(1) - (static_cast<X>(1) / (static_cast<X>(1) + static_cast<X>(nd4j::math::nd4j_abs<X>(dis)) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)) ))); return static_cast<X>(1.7159f) * tanh; } }; template <typename X> class RationalTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { auto dis = (static_cast<X>(2.f) / static_cast<X>(3.f)) * d1; auto a = static_cast<X>(1.f) + nd4j::math::nd4j_abs<X>(dis) + nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(2.f)) + static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(4)); auto tDeriv = (static_cast<X>(1.f) + nd4j::math::nd4j_sign<X,X>(dis) * (static_cast<X>(2.f) * dis + static_cast<X>(4.f) * static_cast<X>(1.41645f) * nd4j::math::nd4j_pow<X, X, X>(dis, static_cast<X>(3)))) / (a * a); return static_cast<X>(1.7159f) * (static_cast<X>(2.f) / static_cast<X>(3.f)) * tDeriv; } }; template <typename X> class Tanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanh<X, X>(d1); } }; template <typename X> class RectifiedTanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_max<X>(static_cast<X>(0), nd4j::math::nd4j_tanh<X,X>(d1)); } }; template <typename X> class RectifiedTanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? nd4j::math::nd4j_tanhderivative<X,X>(d1) : static_cast<X>(0.f); } }; template <typename X> class ATanh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atanh<X,X>(d1); } }; template <typename X> class TanhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tanhderivative<X,X>(d1); } }; template <typename X> class Cube { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 * d1 * d1; } }; template <typename X> class CubeDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(3) * d1 * d1; } }; template <typename X> class ACos { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acos<X, X>(d1); } }; template <typename X> class ASinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asinh<X, X>(d1); } }; template <typename X> class ASinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(nd4j::math::nd4j_pow<X, X, X>(d1, static_cast<X>(2.f)) + static_cast<X>(1.f))); } }; template <typename X> class ACosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_acosh<X, X>(d1); } }; template <typename X> class ACoshDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / (nd4j::math::nd4j_sqrt<X, X>(d1 - static_cast<X>(1.f)) * nd4j::math::nd4j_sqrt<X, X>(d1 + static_cast<X>(1.f))); } }; template <typename X> class Ones { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.0f); } }; template <typename X> class SoftSign { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsign<X, X>(d1); } }; template <typename X> class SoftSignDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_softsignderivative<X,X>(d1); } }; template <typename X, typename Z> class MatchConditionBool { public: no_op_exec_special_bool no_op_exec_special_bool_cuda // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //nd4j_printf("value: %f; comp: %f; eps: %f; mode: %i;\n", d1, compare, eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? true : false; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? true : false; case 2: // less_than return d1 < compare ? true : false; case 3: // greater_than return d1 > compare ? true : false; case 4: // less_or_equals_than return d1 <= compare ? true : false; case 5: // greater_or_equals_than return d1 >= compare ? true : false; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? true : false; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? true : false; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? true : false; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? true : false; case 10: return (d1 == compare) ? true : false; case 11: return (d1 != compare) ? true : false; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? true : false; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? true : false; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)); case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1); default: printf("Undefined match condition: [%i]\n", mode); } return d1; } }; template <typename X, typename Z> class MatchCondition { public: no_op_exec_special no_op_exec_special_cuda no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return old + opOutput; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return old + opOutput; } // this op return 1.0 if condition met, 0.0 otherwise op_def static Z op(X d1, X *extraParams) { X compare = extraParams[0]; X eps = extraParams[1]; auto mode = static_cast<int>(extraParams[2]); //printf("value: %f; comp: %f; eps: %f; mode: %i;\n", (float) d1, (float) compare, (float) eps, mode); switch (mode) { case 0: // equals return nd4j::math::nd4j_abs<X>(d1 - compare) <= eps ? 1 : 0; case 1: // not equals return nd4j::math::nd4j_abs<X>(d1 - compare) > eps ? 1 : 0; case 2: // less_than return d1 < compare ? 1 : 0; case 3: // greater_than return d1 > compare ? 1 : 0; case 4: // less_or_equals_than return d1 <= compare ? 1 : 0; case 5: // greater_or_equals_than return d1 >= compare ? 1 : 0; case 6: // abs_less_than return nd4j::math::nd4j_abs<X>(d1) < compare ? 1 : 0; case 7: // abs_greater_than return nd4j::math::nd4j_abs<X>(d1) > compare ? 1 : 0; case 8: // is inf return nd4j::math::nd4j_isinf(d1) ? 1 : 0; case 9: // is nan return nd4j::math::nd4j_isnan(d1) ? 1 : 0; case 10: return (d1 == compare) ? 1 : 0; case 11: return (d1 != compare) ? 1 : 0; case 12: // abs_greater_or_equals_than return nd4j::math::nd4j_abs<X>(d1) >= compare ? 1 : 0; case 13: // abs_less_or_equals_than return nd4j::math::nd4j_abs<X>(d1) <= compare ? 1 : 0; case 14: // isFinite return !(nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1)) ? 1 : 0; case 15: // isInfinite return nd4j::math::nd4j_isinf(d1) || nd4j::math::nd4j_isnan(d1) ? 1 : 0; default: printf("Undefined match condition: [%i]\n", mode); } return d1; } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X> class ELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_elu<X,X>(d1); } }; template <typename X> class ELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_eluderivative<X,X>(d1); } }; template <typename X, typename Y, typename Z> class RELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto xt = static_cast<Z>(d1); auto xf = static_cast<Z>(d2); return xt < xf ? xf : xt; } }; template <typename X, typename Y, typename Z> class SXELogitsSmoother { public: op_def static Z op(X d1, Y d2, Z *params) { return d1 * ((X)1.f - (X) d2) + (X)(0.5f) * (X) d2; } }; template <typename X, typename Y, typename Z> class RELU6 { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { auto relu = simdOps::RELU<X,Y,Z>::op(d1, d2, params); return relu < static_cast<Z>(6) ? relu : static_cast<Z>(6); } }; template <typename X, typename Y, typename Z> class LeakyRELU { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_leakyrelu<X,Z>(d1, d2); } }; template <typename X> class SELU { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.0f) ? static_cast<X>(SELU_LAMBDA) * static_cast<X>(d1) : static_cast<X>(SELU_LAMBDA) * (static_cast<X>(SELU_ALPHA) * nd4j::math::nd4j_exp<X, X>(d1) - static_cast<X>(SELU_ALPHA)); } }; template <typename X> class SELUDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1 > static_cast<X>(0.f) ? static_cast<X>(SELU_LAMBDA) : static_cast<X>(SELU_ALPHA) * static_cast<X>(SELU_LAMBDA) * nd4j::math::nd4j_exp<X, X>(d1); } }; template <typename X, typename Y, typename Z> class LeakyRELUDerivative { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { if (d1 >= static_cast<X>(0)) return static_cast<Z>(1); else return static_cast<Z>(d2); } }; template <typename X> class ASin { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_asin<X,X>(d1); } }; template <typename X> class Sinh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_sinh<X,X>(d1); } }; template <typename X> class SinhDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X, X>(d1); } }; template <typename X> class Cosh { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_cosh<X,X>(d1); } }; template <typename X> class Tan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_tan<X,X>(d1); } }; template <typename X> class TanDerivative { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1.f) / nd4j::math::nd4j_pow<X, X, X>(nd4j::math::nd4j_cos<X, X>(d1), static_cast<X>(2.0f)); } }; template <typename X> class ATan { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return nd4j::math::nd4j_atan<X, X>(d1); } }; template <typename X, typename Y, typename Z> class Atan2 { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_atan2<X, Z>(d2, d1); } op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } // op for MetaOps op_def static Z op(X d1, Y *params) { return op(d1, params[0]); } }; template <typename X> class Identity { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return d1; } }; template <typename X> class Stabilize { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { X k = params[0]; if (d1 * k > static_cast<X>(- MIN_CUTFOFF)) return static_cast<X>(- MIN_CUTFOFF) / k; else if (d1 * k < static_cast<X>(MIN_CUTFOFF)) return static_cast<X>(MIN_CUTFOFF) / k; return d1; } }; template <typename X, typename Y, typename Z> class Step { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static Z op(X d1, Y d2, Z *params) { return (d1 > static_cast<X>(d2) ? static_cast<Z>(1) : static_cast<Z>(0)); } }; template <typename X> class OneMinus { public: no_op_exec_special_same no_op_exec_special_same_cuda op_def static X op(X d1, X *params) { return static_cast<X>(1) - d1; } }; template <typename X> class Sum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class ShannonEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2)) * nd4j::math::nd4j_log<X, Z>(nd4j::math::nd4j_pow<X, X, Z>(d1, static_cast<X>(2.0f))); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return -reduction; } }; template <typename X, typename Z> class LogEntropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { //entropy is -sum(p(x) * log(p(x))); log entropy is log of this return nd4j::math::nd4j_log<X, Z>(-reduction); } }; template <typename X, typename Z> class Entropy { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1) * nd4j::math::nd4j_log<X, Z>(d1); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(-reduction); //entropy is -sum(p(x) * log(p(x))) } }; template <typename X> class ASum { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X, typename Z> class CountNonZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0.0f) ? static_cast<Z>(0.0f) : static_cast<Z>(1.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class CountZero { public: no_op_exec_special_accumulation_long no_op_exec_special_accumulation_cuda op_def static Z startingValue(const X *input) { return static_cast<Z>(0.0f); } op_def static Z merge(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(Z old, Z opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1 == static_cast<X>(0) ? static_cast<X>(1) : static_cast<X>(0); } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return static_cast<Z>(reduction); } }; template <typename X> class Prod { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static X merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Any { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput + old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0) ; } }; template <typename X, typename Z> class All { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(1); } op_def static Z merge(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z update(X old, X opOutput, X *extraParams) { return opOutput * old; } op_def static Z op(X d1, X *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction > static_cast<X>(0) ? static_cast<Z>(1) : static_cast<Z>(0); } }; template <typename X, typename Z> class Mean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return (Z) reduction / (Z) n; } }; template <typename X, typename Z> class AMean { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static X update(X old, X opOutput, Z *extraParams) { return nd4j::math::nd4j_abs<X>(opOutput) + nd4j::math::nd4j_abs<X>(old); } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_abs<X>(reduction) / static_cast<X>(n); } }; template <typename X> class Max { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Y, typename Z> class AMaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) > nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class AMinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return op(d1, d2); } op_def static Z op(X d1, Y d2) { auto z1 = static_cast<Z>(d1); auto z2 = static_cast<Z>(d2); if (nd4j::math::nd4j_abs<Z>(z1) < nd4j::math::nd4j_abs<Z>(z2)) return z1; else return z2; } }; template <typename X, typename Y, typename Z> class MaxPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_max<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X, typename Y, typename Z> class MinPairwise { public: op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } op_def static Z op(X d1, Y d2) { return nd4j::math::nd4j_min<Z>(static_cast<Z>(d1), static_cast<Z>(d2)); } }; template <typename X> class AMax { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_abs<X>(d1) > nd4j::math::nd4j_abs<X>(d2) ? d1 : d2; } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class AMin { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(opOutput), nd4j::math::nd4j_abs<X>(old)); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(nd4j::math::nd4j_abs<X>(d1), nd4j::math::nd4j_abs<X>(d2)); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return nd4j::math::nd4j_abs<X>(d1); } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return nd4j::math::nd4j_abs<X>(reduction); } }; template <typename X> class Min { public: no_op_exec_special_accumulation_same no_op_exec_special_accumulation_same_cuda op_def static X startingValue(const X *input) { return input[0]; } op_def static X merge(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(old, opOutput); } op_def static X update(X old, X opOutput, X *extraParams) { return nd4j::math::nd4j_min<X>(opOutput, old); } op_def static X op(X d1, X d2, X *params) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static X op(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } // FIXME: this signature overlaps with MetaOp op_def static X op(X d1, X *extraParams) { return d1; } op_def static X postProcess(X reduction, Nd4jLong n, X *extraParams) { return reduction; } }; template <typename X, typename Z> class Norm1 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(nd4j::math::nd4j_abs<X>(d1)); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(reduction); } }; template <typename X, typename Z> class Norm2 { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<X, Z>(reduction); } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } }; template <typename X, typename Z> class SquaredNorm { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return static_cast<Z>(d1 * d1); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(reduction); } }; template <typename X, typename Z> class NormFrobenius { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { X v = nd4j::math::nd4j_abs<X>(d1); return static_cast<Z>(v * v); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_sqrt<X, Z>(reduction); } }; template <typename X, typename Z> class NormP { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z op(X d1, Z *extraParams) { return nd4j::math::nd4j_pow<X, Z, Z>(nd4j::math::nd4j_abs<X>(d1), extraParams[0]); } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return nd4j::math::nd4j_pow<X, Z, Z>(reduction, static_cast<Z>(1.0f) / extraParams[0]); } }; template <typename X, typename Z> class NormMax { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return opOutput + old; } op_def static Z update(X old, X opOutput, Z *extraParams) { return nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(old), nd4j::math::nd4j_abs<X>(opOutput)); } op_def static Z op(X d1, Z *extraParams) { return d1; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { return static_cast<Z>(nd4j::math::nd4j_max<X>(nd4j::math::nd4j_abs<X>(reduction), nd4j::math::nd4j_abs<X>(reduction))); } }; template <typename X, typename Z> class Variance { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static X op(X d1, Z *extraParams) { X mean = static_cast<X>(extraParams[0]); X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { // T bias = extraParams[1]; // return (reduction - (nd4j::math::nd4j_pow<T>(bias, static_cast<T>(2.0f)) / static_cast<T>(n))) / (n - 1) return static_cast<Z>(reduction) / static_cast<Z>(n - 1); } }; /** * Standard deviation of a buffer */ template <typename X, typename Z> class StandardDeviation { public: no_op_exec_special_accumulation no_op_exec_special_accumulation_cuda op_def static X startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Z merge(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z update(X old, X opOutput, Z *extraParams) { return old + opOutput; } op_def static Z op(X d1, Z *extraParams) { X mean = extraParams[0]; X ret = d1 - mean; return ret * ret; } op_def static Z postProcess(X reduction, Nd4jLong n, Z *extraParams) { Z ret = Variance<X,Z>::postProcess(reduction, n, extraParams); Z sqrtRet = nd4j::math::nd4j_sqrt<X, Z>(ret); return sqrtRet; } }; template <typename X, typename Y> class CosineSimilarity { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1])); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(d1 * d1); extraParams[1] += static_cast<Y>(d2 * d2); return static_cast<Y>(d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],static_cast<Y>(d1 * d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1],static_cast<Y>(d2 * d2)); return static_cast<Y>(d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class JaccardDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(const X *input) { return static_cast<X>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { // num / denom return (static_cast<Y>(1.0f)) - (extraParams[0] / extraParams[1]); } op_def static Y num(X d1, X d2) { return nd4j::math::nd4j_min<X>(d1, d2); } op_def static Y denom(X d1, X d2) { return nd4j::math::nd4j_max<X>(d1, d2); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(num(d1, d2)); extraParams[1] += static_cast<Y>(denom(d1, d2)); return static_cast<Y>(0.0f); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0],num(d1, d2)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], denom(d1, d2)); return static_cast<Y>(0.0f); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class SimpleHammingDistance { public: static const int extraParamsLen = 0; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return static_cast<Y>(reduction / n); } op_def static Y op(X d1, X d2, Y *extraParams) { return (d1 == d2) ? static_cast<Y>(0.0f) : static_cast<Y>(1.0f); } op_def static void aggregateExtraParams(X *extraParamsTotal, X *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParams) { return op(d1, d2, extraParams); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; template <typename X, typename Y> class CosineDistance { public: static const int extraParamsLen = 2; op_def static X *generateExtraParams() { //T *extraParams = new T[2]; return nullptr; } op_def static void finalizeExtraParams(X *extraParams) { //delete[] extraParams; } op_def static Y startingValue(X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParams) { return (static_cast<Y>(1.0f)) - (reduction / (nd4j::math::nd4j_sqrt<Y, Y>(extraParams[0]) * nd4j::math::nd4j_sqrt<Y, Y>(extraParams[1]))); } op_def static Y op(X d1, X d2, Y *extraParams) { extraParams[0] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d1) * nd4j::math::nd4j_abs<X>(d1)); extraParams[1] += static_cast<Y>(nd4j::math::nd4j_abs<X>(d2) * nd4j::math::nd4j_abs<X>(d2)); return (d1 * d2); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { extraParamsTotal[0] += extraParamsLocal[0]; extraParamsTotal[1] += extraParamsLocal[1]; } #ifdef __CUDACC__ static _CUDA_D inline Y opAtomic(X d1, X d2, Y *extraParams) { nd4j::math::atomics::nd4j_atomicAdd(&extraParams[0], nd4j::math::nd4j_abs<Y>(d1) * nd4j::math::nd4j_abs<Y>(d1)); nd4j::math::atomics::nd4j_atomicAdd(&extraParams[1], nd4j::math::nd4j_abs<Y>(d2) * nd4j::math::nd4j_abs<Y>(d2)); return (d1 * d2); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParams) { return old + opOutput; } op_def static Y merge(Y old, Y opOutput, Y *extraParams) { return update(old, opOutput, extraParams); } }; /** * Dot product between 2 arrays */ template <typename X, typename Y> class Dot { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op //delete[] * extraParamsRef; } op_def static Y startingValue(X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return static_cast<Y>(d1 * d2); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; /** * Op to check equality within arrays */ template <typename X, typename Z> class EqualsWithEps { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Z startingValue(X *input) { return static_cast<Z>(0.0f); } op_def static Z postProcess(Z reduction, Nd4jLong n, Z *extraParamsRef) { return reduction; } op_def static Z op(X d1, X d2, Z *extraParamsRef) { Z eps = nd4j::math::nd4j_abs<Z>(extraParamsRef[2]); Z diff = static_cast<Z>(nd4j::math::nd4j_abs<X>(d1 - d2)); // works well except in the range of very large numbers if (diff <= eps) return static_cast<Z>(0.f); // Knuth approach // works well except in the range of very small numbers if (diff <= nd4j::math::nd4j_max<Z>(nd4j::math::nd4j_abs<Z>(static_cast<Z>(d1)), nd4j::math::nd4j_abs<Z>(static_cast<Z>(d2))) * eps) return static_cast<Z>(0.f); return static_cast<Z>(1.f); } #ifdef __CUDACC__ __device__ static inline Z opAtomic(X d1, X d2, Z *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Z update(Z old, Z opOutput, Z *extraParamsRef) { return opOutput + old; } op_def static Z merge(X old, Z opOutput, Z *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Z *extraParamsTotal, Z *extraParamsLocal) {} }; template <typename X, typename Y> class EuclideanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return nd4j::math::nd4j_sqrt<Y, Y>(reduction); } op_def static Y op(X d1, X d2, Y *extraParamsRef) { X ret = d1 - d2; return static_cast<Y>(ret * ret); } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return opOutput + old; } op_def static Y merge(Y old, Y opOutput, Y *extraParamsRef) { return update(old, opOutput, extraParamsRef); } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) {} }; template <typename X, typename Y> class ManhattanDistance { public: static const int extraParamsLen = 0; op_def static X * generateExtraParams() { return nullptr; } op_def static void finalizeExtraParams(X *extraParamsRef) { //no-op } op_def static Y startingValue(X *input) { return static_cast<Y>(0.0f); } op_def static Y postProcess(Y reduction, Nd4jLong n, Y *extraParamsRef) { return reduction; } op_def static Y op(X d1, X d2, Y *extraParamsRef) { return nd4j::math::nd4j_abs<X>(d1 - d2); } op_def static Y update(Y old, Y opOutput, Y *extraParamsRef) { return old + opOutput; } op_def static void aggregateExtraParams(Y *extraParamsTotal, Y *extraParamsLocal) { } #ifdef __CUDACC__ __device__ static inline Y opAtomic(X d1, X d2, Y *extraParamsRef) { return op(d1, d2, extraParamsRef); } #endif #ifndef __clang__ #pragma omp declare simd uniform(extraParamsRef) #endif op_def static Y merge(X old, X opOutput, X *extraParamsRef) { return update(old, opOutput, extraParamsRef); } }; template <typename X> class IndexAbsoluteMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return nd4j::math::nd4j_abs<X>(val); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value > old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) > nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(X *input) { return 0; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class FirstIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); //printf("res: %f; oldIdx: %i; newIdx: %i\n", res, old.index, opOutput.index); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index > opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index > f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X> class LastIndex { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { #ifdef __CUDACC__ if (opOutput.index < 0) return old; #endif auto res = simdOps::MatchCondition<X,X>::op(opOutput.value, extraParams); if (res == static_cast<X>(0)) return old; if (old.index < 0) return opOutput; if (old.index < opOutput.index) return opOutput; return old; } static _CUDA_HD inline X startingValue(X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = -1; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.index < f2.index) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } }; template <typename X> class IndexMax { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value > old.value) { return opOutput; } #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value > f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline X startingValue(X *input) { return -nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class IndexAbsoluteMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(X *input) { return nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { opOutput.value = nd4j::math::nd4j_abs<X>(opOutput.value); old.value = nd4j::math::nd4j_abs<X>(old.value); if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (nd4j::math::nd4j_abs<X>(f1.value) < nd4j::math::nd4j_abs<X>(f2.value)) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X> class IndexMin { public: static _CUDA_HD inline functions::indexreduce::IndexValue<X> op( functions::indexreduce::IndexValue<X> val, X *extraParams) { return val; } static _CUDA_HD inline X startingValue(X *input) { return nd4j::DataTypeUtils::max<X>(); } static _CUDA_HD inline functions::indexreduce::IndexValue<X> startingIndexValue(X *input) { functions::indexreduce::IndexValue<X> local; local.value = startingValue(input); local.index = 0; return local; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> update(functions::indexreduce::IndexValue<X> &old, functions::indexreduce::IndexValue<X> &opOutput, X *extraParams) { if (opOutput.value < old.value) return opOutput; #ifdef __CUDACC__ // workaround for cuda race condition at merge phase else if (opOutput.value == old.value && opOutput.index < old.index) return opOutput; #elif defined(__GNUC__) #endif return old; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> merge( functions::indexreduce::IndexValue<X> f1, functions::indexreduce::IndexValue<X> f2, X *extraParams) { if (f1.value < f2.value) return f2; return f1; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> postProcess( functions::indexreduce::IndexValue<X> reduction, int n, int xOffset, X *dx, int incx, X *extraParams, X *result) { return reduction; } static _CUDA_HD inline functions::indexreduce::IndexValue<X> op(functions::indexreduce::IndexValue<X> d1, functions::indexreduce::IndexValue<X> d2, X *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsVariance { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { Z ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return static_cast<Z>(val.variance()); return ret; } return static_cast<Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X, typename Z> class SummaryStatsStandardDeviation { public: static _CUDA_HD inline Z getValue(const bool biasCorrected, functions::summarystats::SummaryStatsData<X> val) { if (biasCorrected) { auto ret = static_cast<Z>(val.varianceBiasCorrected()); if (ret < static_cast<Z>(0.0f)) return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); else return nd4j::math::nd4j_sqrt<double, Z>(ret); } return nd4j::math::nd4j_sqrt<double, Z>(val.variance()); } static _CUDA_HD inline functions::summarystats::SummaryStatsData<X> op(functions::summarystats::SummaryStatsData<X> d1, Z *extraParams) { return d1; } }; template <typename X> class DropOut { public: no_op_exec_special_same no_op_exec_special_same_cuda inline _CUDA_D static X op(X d1, X *params) { X prob = params[0]; #ifdef __CUDACC__ X length = params[1]; X tid = gridDim.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= prob ? static_cast<X>(0.0f) : d1; } }; template <typename X, typename Y, typename Z> class DropOutInverted { public: no_op_exec_special no_op_exec_special_cuda #ifdef __CUDACC__ __device__ #endif inline static Z op(X d1, Y d2, Z *params) { Y prob = d2; #ifdef __CUDACC__ X length = params[1]; X tid = gridDim.x * blockDim.x + threadIdx.x; X rnd = nd4j::math::nd4j_abs<X>(nd4j::math::nd4j_cos<X>(static_cast<X>(clock64()) * static_cast<X>(tid) + static_cast<X>(length) * static_cast<X>(tid))); #else X rnd = static_cast<X>(rand() / RAND_MAX); #endif return rnd >= static_cast<X>(prob) ? static_cast<Z>(0.0f) : reinterpret_cast<Z>(d1 / static_cast<X>(prob)); } }; template <typename X, typename Y, typename Z> class ReplaceNans { public: no_op_exec_special no_op_exec_special_cuda op_def static Z op(X d1, Y d2, Z *params) { return nd4j::math::nd4j_isnan(d1) ? static_cast<Z>(d2) : static_cast<Z>(d1) ; } }; // this op is used for conditional pairwise transforms only template <typename X, typename Y, typename Z> class CompareAndReplace{ public: // op definition for PairWise Transform op_def static Z op(X d1, Y d2, Z *params) { auto zd1 = static_cast<Z>(d1); auto zd2 = static_cast<Z>(d2); auto compare = params[0]; auto eps = params[2]; int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(zd1 - compare) <= eps) return zd2; else return zd1; else if (mode == 1) // not equals eps if (nd4j::math::nd4j_abs<Z>(zd1 - compare) > eps) return zd2; else return zd1; else if (mode == 2) // less_than eps if (zd1 < compare) return zd2; else return zd1; else if (mode ==3) // greater_than if (zd1 > compare) return zd2; else return zd1; else if (mode == 4) // less_or_equals_than if (zd1 <= compare) return zd2; else return zd1; else if (mode == 5) // greater_or_equals_than if (zd1 >= compare) return zd2; else return zd1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(zd1) < compare) return zd2; else return zd1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(zd1) > compare) return zd2; else return zd1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(zd1)) return zd2; else return zd1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(zd1)) return zd2; else return zd1; else if (mode == 10) if (zd1 == compare) return zd2; else return zd1; else if (mode == 11) if (zd1 != compare) return zd2; else return zd1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) >= compare) return zd2; else return zd1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(zd1) <= compare) return zd2; else return zd1; else printf("Undefined boolean operation: [%i]\n", mode); return zd1; } }; template <typename X, typename Y, typename Z> class CompareAndSet { public: // op definition for PairWise Transform op_def static Z op(X dX, Y dY, Z *params) { auto d1 = static_cast<Z>(dX); auto d2 = static_cast<Z>(dY); auto compare = params[0]; auto eps = params[2]; auto mode = static_cast<int>(params[3]); if (mode == 0) // equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) <= eps) return d2; else return d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<Z>(d2 - compare) > eps) return d2; else return d1; else if (mode == 2) // less_than if (d2 < compare) return d2; else return d1; else if (mode ==3) // greater_than if (d2 > compare) return d2; else return d1; else if (mode == 4) // less_or_equals_than if (d2 <= compare) return d2; else return d1; else if (mode == 5) // greater_or_equals_than if (d2 >= compare) return d2; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<Z>(d2) < compare) return d2; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<Z>(d2) > compare) return d2; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d2)) return d2; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d2)) return d2; else return d1; else if (mode == 10) if (d2 == compare) return d2; else return d1; else if (mode == 11) if (d2 != compare) return d2; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) >= compare) return d2; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<Z>(d1) <= compare) return d2; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; template <typename X> class CompareAndSetTransform { public: no_op_exec_special_same no_op_exec_special_same_cuda // op definition for Transform op_def static X op(X d1, X *params) { auto compare = params[0]; auto set = params[1]; auto eps = params[2]; // with mode == 0 we do set if d1 equals to compare, and with mode == 1 - we go otherwise int mode = (int) params[3]; if (mode == 0) // equals if (nd4j::math::nd4j_abs<X>(d1 - compare) <= eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) <= eps ? set : d1; else if (mode == 1) // not equals if (nd4j::math::nd4j_abs<X>(d1 - compare) > eps) return set; else return d1; //return nd4j::math::nd4j_abs<T>(d1 - compare) > eps ? set : d1; else if (mode == 2) // less_than if (d1 < compare) return set; else return d1; else if (mode ==3) // greater_than if (d1 > compare) return set; else return d1; else if (mode == 4) // less_or_equals_than if (d1 <= compare) return set; else return d1; else if (mode == 5) // greater_or_equals_than if (d1 >= compare) return set; else return d1; else if (mode == 6) // abs_less_than if (nd4j::math::nd4j_abs<X>(d1) < compare) return set; else return d1; else if (mode == 7) // abs_greater_than if (nd4j::math::nd4j_abs<X>(d1) > compare) return set; else return d1; else if (mode == 8) // is inf if (nd4j::math::nd4j_isinf(d1)) return set; else return d1; else if (mode == 9) // is nan if (nd4j::math::nd4j_isnan(d1)) return set; else return d1; else if (mode == 10) if (d1 == compare) return set; else return d1; else if (mode == 11) if (d1 != compare) return set; else return d1; else if (mode == 12) // abs_greater_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) >= compare) return set; else return d1; else if (mode == 13) // abs_less_or_equals_than if (nd4j::math::nd4j_abs<X>(d1) <= compare) return set; else return d1; else printf("Undefined boolean operation: [%i]\n", mode); return d1; } }; } #endif
mixed_tentusscher_myo_epi_2004_S2_20.c
// Scenario 2 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S2_20.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5626314873864,0.00129162059588251,0.779565841868151,0.779314339768234,0.000174937390688145,0.485031353960147,0.00294149195344193,0.999998346418836,1.93534486766886e-08,1.89248872699741e-05,0.999775353607234,1.00753388054703,0.999999038303684,3.47610047822055e-05,1.00562825829621,9.46957015137721,139.869479747257}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.9266422007604,0.000306211763267299,0.000130134845221041,0.000571745609978391,0.247335217693447,0.185194358577401,0.103790172036162,3.70853519439188,0.0133585353452839,2.20377995116952,1098.12344962390,0.000446735827598516,0.252881711351026,0.0117635663866967,0.00515418083406778,9.05330255534724e-06}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
oskar_auto_correlate_scalar_omp.c
/* * Copyright (c) 2015, The University of Oxford * 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 University of Oxford nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <math.h> #include "correlate/private_correlate_functions_inline.h" #include "correlate/oskar_auto_correlate_scalar_omp.h" #include "math/oskar_add_inline.h" #ifdef __cplusplus extern "C" { #endif /* Single precision. */ void oskar_auto_correlate_scalar_omp_f(const int num_sources, const int num_stations, const float2* jones, const float* source_I, float2* vis) { int s; /* Loop over stations. */ #pragma omp parallel for private(s) for (s = 0; s < num_stations; ++s) { int i; const float2 *station; float2 sum, guard; sum.x = 0.0f; sum.y = 0.0f; guard.x = 0.0f; guard.y = 0.0f; /* Pointer to source vector for station. */ station = &jones[s * num_sources]; /* Accumulate visibility response for source. */ for (i = 0; i < num_sources; ++i) oskar_accumulate_station_visibility_for_source_scalar_inline_f( &sum, i, source_I, station, &guard); /* Add result to the station visibility. We only need the real part. */ vis[s].x += sum.x; } } /* Double precision. */ void oskar_auto_correlate_scalar_omp_d(const int num_sources, const int num_stations, const double2* jones, const double* source_I, double2* vis) { int s; /* Loop over stations. */ #pragma omp parallel for private(s) for (s = 0; s < num_stations; ++s) { int i; const double2 *station; double2 sum; sum.x = 0.0; sum.y = 0.0; /* Pointer to source vector for station. */ station = &jones[s * num_sources]; /* Accumulate visibility response for source. */ for (i = 0; i < num_sources; ++i) oskar_accumulate_station_visibility_for_source_scalar_inline_d( &sum, i, source_I, station); /* Add result to the station visibility. We only need the real part. */ vis[s].x += sum.x; } } #ifdef __cplusplus } #endif
DRB111-linearmissing-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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 "omprace.h" #include <omp.h> #include <stdio.h> /* * loop missing the linear clause * Data race pair: j@67:7 vs. j@68:5 */ int main() { omprace_init(); int len=100; double a[len], b[len], c[len]; int i,j=0; for (i=0;i<len;i++) { a[i]=((double)i)/2.0; b[i]=((double)i)/3.0; c[i]=((double)i)/7.0; } #pragma omp parallel for for (i=0;i<len;i++) { c[j]+=a[i]*b[i]; j++; } printf ("c[50]=%f\n",c[50]); omprace_fini(); return 0; }
par_coarsen.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * *****************************************************************************/ /* following should be in a header file */ #include "_hypre_parcsr_ls.h" /*==========================================================================*/ /*==========================================================================*/ /** Selects a coarse "grid" based on the graph of a matrix. Notes: \begin{itemize} \item The underlying matrix storage scheme is a hypre_ParCSR matrix. \item The routine returns the following: \begin{itemize} \item S - a ParCSR matrix representing the "strength matrix". This is used in the "build interpolation" routine. \item CF\_marker - an array indicating both C-pts (value = 1) and F-pts (value = -1) \end{itemize} \item We define the following temporary storage: \begin{itemize} \item measure\_array - an array containing the "measures" for each of the fine-grid points \item graph\_array - an array containing the list of points in the "current subgraph" being considered in the coarsening process. \end{itemize} \item The graph of the "strength matrix" for A is a subgraph of the graph of A, but requires nonsymmetric storage even if A is symmetric. This is because of the directional nature of the "strengh of dependence" notion (see below). Since we are using nonsymmetric storage for A right now, this is not a problem. If we ever add the ability to store A symmetrically, then we could store the strength graph as floats instead of doubles to save space. \item This routine currently "compresses" the strength matrix. We should consider the possibility of defining this matrix to have the same "nonzero structure" as A. To do this, we could use the same A\_i and A\_j arrays, and would need only define the S\_data array. There are several pros and cons to discuss. \end{itemize} Terminology: \begin{itemize} \item Ruge's terminology: A point is "strongly connected to" $j$, or "strongly depends on" $j$, if $-a_ij >= \theta max_{l != j} \{-a_il\}$. \item Here, we retain some of this terminology, but with a more generalized notion of "strength". We also retain the "natural" graph notation for representing the directed graph of a matrix. That is, the nonzero entry $a_ij$ is represented as: i --> j. In the strength matrix, S, the entry $s_ij$ is also graphically denoted as above, and means both of the following: \begin{itemize} \item $i$ "depends on" $j$ with "strength" $s_ij$ \item $j$ "influences" $i$ with "strength" $s_ij$ \end{itemize} \end{itemize} {\bf Input files:} _hypre_parcsr_ls.h @return Error code. @param A [IN] coefficient matrix @param strength_threshold [IN] threshold parameter used to define strength @param S_ptr [OUT] strength matrix @param CF_marker_ptr [OUT] array indicating C/F points @see */ /*--------------------------------------------------------------------------*/ #define C_PT 1 #define F_PT -1 #define SF_PT -3 #define COMMON_C_PT 2 #define Z_PT -2 HYPRE_Int hypre_BoomerAMGCoarsen( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int CF_init, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = NULL; HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(S); HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstColDiag(S); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)hypre_CSRMatrixNumCols(S_diag); HYPRE_Int num_cols_offd = 0; hypre_CSRMatrix *S_ext; HYPRE_Int *S_ext_i = NULL; HYPRE_BigInt *S_ext_j = NULL; HYPRE_Int num_sends = 0; HYPRE_Int *int_buf_data; HYPRE_Real *buf_data; HYPRE_Int *CF_marker; HYPRE_Int *CF_marker_offd; HYPRE_Real *measure_array; HYPRE_Int *graph_array; HYPRE_Int *graph_array_offd; HYPRE_Int graph_size; HYPRE_BigInt big_graph_size; HYPRE_Int graph_offd_size; HYPRE_BigInt global_graph_size; HYPRE_Int i, j, k, kc, jS, kS, ig, elmt; HYPRE_Int index, start, my_id, num_procs, jrow, cnt; HYPRE_Int use_commpkg_A = 0; HYPRE_Int break_var = 1; HYPRE_Real wall_time; HYPRE_Int iter = 0; HYPRE_BigInt big_k; #if 0 /* debugging */ char filename[256]; FILE *fp; HYPRE_Int iter = 0; #endif /*-------------------------------------------------------------- * Compute a ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ S_ext = NULL; if (debug_flag == 3) wall_time = time_getWallclockSeconds(); hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (!comm_pkg) { use_commpkg_A = 1; comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); num_cols_offd = hypre_CSRMatrixNumCols(S_offd); S_diag_j = hypre_CSRMatrixJ(S_diag); if (num_cols_offd) { S_offd_j = hypre_CSRMatrixJ(S_offd); } /*---------------------------------------------------------- * Compute the measures * * The measures are currently given by the column sums of S. * Hence, measure_array[i] is the number of influences * of variable i. * * The measures are augmented by a random number * between 0 and 1. *----------------------------------------------------------*/ measure_array = hypre_CTAlloc(HYPRE_Real, num_variables+num_cols_offd, HYPRE_MEMORY_HOST); for (i=0; i < S_offd_i[num_variables]; i++) { measure_array[num_variables + S_offd_j[i]] += 1.0; } if (num_procs > 1) comm_handle = hypre_ParCSRCommHandleCreate(2, comm_pkg, &measure_array[num_variables], buf_data); for (i=0; i < S_diag_i[num_variables]; i++) { measure_array[S_diag_j[i]] += 1.0; } if (num_procs > 1) hypre_ParCSRCommHandleDestroy(comm_handle); index = 0; for (i=0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) measure_array[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] += buf_data[index++]; } for (i=num_variables; i < num_variables+num_cols_offd; i++) { measure_array[i] = 0; } /* this augments the measures */ if (CF_init == 2) hypre_BoomerAMGIndepSetInit(S, measure_array, 1); else hypre_BoomerAMGIndepSetInit(S, measure_array, 0); /*--------------------------------------------------- * Initialize the graph array * graph_array contains interior points in elements 0 ... num_variables-1 * followed by boundary values *---------------------------------------------------*/ graph_array = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); if (num_cols_offd) graph_array_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); else graph_array_offd = NULL; /* initialize measure array and graph array */ for (ig = 0; ig < num_cols_offd; ig++) graph_array_offd[ig] = ig; /*--------------------------------------------------- * Initialize the C/F marker array * C/F marker array contains interior points in elements 0 ... * num_variables-1 followed by boundary values *---------------------------------------------------*/ graph_offd_size = num_cols_offd; if (CF_init==1) { CF_marker = *CF_marker_ptr; cnt = 0; for (i=0; i < num_variables; i++) { if ( (S_offd_i[i+1]-S_offd_i[i]) > 0 || CF_marker[i] == -1) { CF_marker[i] = 0; } if ( CF_marker[i] == Z_PT) { if (measure_array[i] >= 1.0 || (S_diag_i[i+1]-S_diag_i[i]) > 0) { CF_marker[i] = 0; graph_array[cnt++] = i; } else { CF_marker[i] = F_PT; } } else if (CF_marker[i] == SF_PT) measure_array[i] = 0; else graph_array[cnt++] = i; } } else { CF_marker = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); cnt = 0; for (i=0; i < num_variables; i++) { CF_marker[i] = 0; if ( (S_diag_i[i+1]-S_diag_i[i]) == 0 && (S_offd_i[i+1]-S_offd_i[i]) == 0) { CF_marker[i] = SF_PT; measure_array[i] = 0; } else graph_array[cnt++] = i; } } graph_size = cnt; if (num_cols_offd) CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); else CF_marker_offd = NULL; for (i=0; i < num_cols_offd; i++) CF_marker_offd[i] = 0; /*--------------------------------------------------- * Loop until all points are either fine or coarse. *---------------------------------------------------*/ if (num_procs > 1) { if (use_commpkg_A) S_ext = hypre_ParCSRMatrixExtractBExt(S,A,0); else S_ext = hypre_ParCSRMatrixExtractBExt(S,S,0); S_ext_i = hypre_CSRMatrixI(S_ext); S_ext_j = hypre_CSRMatrixBigJ(S_ext); } /* compress S_ext and convert column numbers*/ index = 0; for (i=0; i < num_cols_offd; i++) { for (j=S_ext_i[i]; j < S_ext_i[i+1]; j++) { big_k = S_ext_j[j]; if (big_k >= col_1 && big_k < col_n) { S_ext_j[index++] = big_k - col_1; } else { kc = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (kc > -1) S_ext_j[index++] = (HYPRE_BigInt)(-kc-1); } } S_ext_i[i] = index; } for (i = num_cols_offd; i > 0; i--) S_ext_i[i] = S_ext_i[i-1]; if (num_procs > 1) S_ext_i[0] = 0; if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Initialize CLJP phase = %f\n", my_id, wall_time); } while (1) { /*------------------------------------------------ * Exchange boundary data, i.i. get measures and S_ext_data *------------------------------------------------*/ if (num_procs > 1) comm_handle = hypre_ParCSRCommHandleCreate(2, comm_pkg, &measure_array[num_variables], buf_data); if (num_procs > 1) hypre_ParCSRCommHandleDestroy(comm_handle); index = 0; for (i=0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) measure_array[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] += buf_data[index++]; } /*------------------------------------------------ * Set F-pts and update subgraph *------------------------------------------------*/ if (iter || (CF_init != 1)) { for (ig = 0; ig < graph_size; ig++) { i = graph_array[ig]; if ( (CF_marker[i] != C_PT) && (measure_array[i] < 1) ) { /* set to be an F-pt */ CF_marker[i] = F_PT; /* make sure all dependencies have been accounted for */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { if (S_diag_j[jS] > -1) { CF_marker[i] = 0; } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { if (S_offd_j[jS] > -1) { CF_marker[i] = 0; } } } if (CF_marker[i]) { measure_array[i] = 0; /* take point out of the subgraph */ graph_size--; graph_array[ig] = graph_array[graph_size]; graph_array[graph_size] = i; ig--; } } } /*------------------------------------------------ * Exchange boundary data, i.i. get measures *------------------------------------------------*/ if (debug_flag == 3) wall_time = time_getWallclockSeconds(); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { jrow = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); buf_data[index++] = measure_array[jrow]; } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, buf_data, &measure_array[num_variables]); hypre_ParCSRCommHandleDestroy(comm_handle); } /*------------------------------------------------ * Debugging: * * Uncomment the sections of code labeled * "debugging" to generate several files that * can be visualized using the `coarsen.m' * matlab routine. *------------------------------------------------*/ #if 0 /* debugging */ /* print out measures */ hypre_sprintf(filename, "coarsen.out.measures.%04d", iter); fp = fopen(filename, "w"); for (i = 0; i < num_variables; i++) { hypre_fprintf(fp, "%f\n", measure_array[i]); } fclose(fp); /* print out strength matrix */ hypre_sprintf(filename, "coarsen.out.strength.%04d", iter); hypre_CSRMatrixPrint(S, filename); /* print out C/F marker */ hypre_sprintf(filename, "coarsen.out.CF.%04d", iter); fp = fopen(filename, "w"); for (i = 0; i < num_variables; i++) { hypre_fprintf(fp, "%d\n", CF_marker[i]); } fclose(fp); iter++; #endif /*------------------------------------------------ * Test for convergence *------------------------------------------------*/ big_graph_size = (HYPRE_BigInt) graph_size; hypre_MPI_Allreduce(&big_graph_size,&global_graph_size,1,HYPRE_MPI_BIG_INT,hypre_MPI_SUM,comm); if (global_graph_size == 0) break; /*------------------------------------------------ * Pick an independent set of points with * maximal measure. *------------------------------------------------*/ if (iter || (CF_init != 1)) { hypre_BoomerAMGIndepSet(S, measure_array, graph_array, graph_size, graph_array_offd, graph_offd_size, CF_marker, CF_marker_offd); if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, CF_marker_offd, int_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j=start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1);j++) { elmt = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); if (!int_buf_data[index++] && CF_marker[elmt] > 0) { CF_marker[elmt] = 0; } } } } iter++; /*------------------------------------------------ * Exchange boundary data for CF_marker *------------------------------------------------*/ index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { elmt = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); int_buf_data[index++] = CF_marker[elmt]; } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } for (ig = 0; ig < graph_offd_size; ig++) { i = graph_array_offd[ig]; if (CF_marker_offd[i] < 0) { /* take point out of the subgraph */ graph_offd_size--; graph_array_offd[ig] = graph_array_offd[graph_offd_size]; graph_array_offd[graph_offd_size] = i; ig--; } } if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d iter %d comm. and subgraph update = %f\n", my_id, iter, wall_time); } /*------------------------------------------------ * Set C_pts and apply heuristics. *------------------------------------------------*/ for (i=num_variables; i < num_variables+num_cols_offd; i++) { measure_array[i] = 0; } if (debug_flag == 3) wall_time = time_getWallclockSeconds(); for (ig = 0; ig < graph_size; ig++) { i = graph_array[ig]; /*--------------------------------------------- * Heuristic: C-pts don't interpolate from * neighbors that influence them. *---------------------------------------------*/ if (CF_marker[i] > 0) { /* set to be a C-pt */ CF_marker[i] = C_PT; for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { j = S_diag_j[jS]; if (j > -1) { /* "remove" edge from S */ S_diag_j[jS] = -S_diag_j[jS]-1; /* decrement measures of unmarked neighbors */ if (!CF_marker[j]) { measure_array[j]--; } } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { j = S_offd_j[jS]; if (j > -1) { /* "remove" edge from S */ S_offd_j[jS] = -S_offd_j[jS]-1; /* decrement measures of unmarked neighbors */ if (!CF_marker_offd[j]) { measure_array[j+num_variables]--; } } } } else { /* marked dependencies */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { j = S_diag_j[jS]; if (j < 0) j = -j-1; if (CF_marker[j] > 0) { if (S_diag_j[jS] > -1) { /* "remove" edge from S */ S_diag_j[jS] = -S_diag_j[jS]-1; } /* IMPORTANT: consider all dependencies */ /* temporarily modify CF_marker */ CF_marker[j] = COMMON_C_PT; } else if (CF_marker[j] == SF_PT) { if (S_diag_j[jS] > -1) { /* "remove" edge from S */ S_diag_j[jS] = -S_diag_j[jS]-1; } } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { j = S_offd_j[jS]; if (j < 0) j = -j-1; if (CF_marker_offd[j] > 0) { if (S_offd_j[jS] > -1) { /* "remove" edge from S */ S_offd_j[jS] = -S_offd_j[jS]-1; } /* IMPORTANT: consider all dependencies */ /* temporarily modify CF_marker */ CF_marker_offd[j] = COMMON_C_PT; } else if (CF_marker_offd[j] == SF_PT) { if (S_offd_j[jS] > -1) { /* "remove" edge from S */ S_offd_j[jS] = -S_offd_j[jS]-1; } } } /* unmarked dependencies */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { if (S_diag_j[jS] > -1) { j = S_diag_j[jS]; break_var = 1; /* check for common C-pt */ for (kS = S_diag_i[j]; kS < S_diag_i[j+1]; kS++) { k = S_diag_j[kS]; if (k < 0) k = -k-1; /* IMPORTANT: consider all dependencies */ if (CF_marker[k] == COMMON_C_PT) { /* "remove" edge from S and update measure*/ S_diag_j[jS] = -S_diag_j[jS]-1; measure_array[j]--; break_var = 0; break; } } if (break_var) { for (kS = S_offd_i[j]; kS < S_offd_i[j+1]; kS++) { k = S_offd_j[kS]; if (k < 0) k = -k-1; /* IMPORTANT: consider all dependencies */ if ( CF_marker_offd[k] == COMMON_C_PT) { /* "remove" edge from S and update measure*/ S_diag_j[jS] = -S_diag_j[jS]-1; measure_array[j]--; break; } } } } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { if (S_offd_j[jS] > -1) { j = S_offd_j[jS]; /* check for common C-pt */ for (kS = S_ext_i[j]; kS < S_ext_i[j+1]; kS++) { k = (HYPRE_Int)S_ext_j[kS]; if (k >= 0) { /* IMPORTANT: consider all dependencies */ if (CF_marker[k] == COMMON_C_PT) { /* "remove" edge from S and update measure*/ S_offd_j[jS] = -S_offd_j[jS]-1; measure_array[j+num_variables]--; break; } } else { kc = -k-1; if (kc > -1 && CF_marker_offd[kc] == COMMON_C_PT) { /* "remove" edge from S and update measure*/ S_offd_j[jS] = -S_offd_j[jS]-1; measure_array[j+num_variables]--; break; } } } } } } /* reset CF_marker */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { j = S_diag_j[jS]; if (j < 0) j = -j-1; if (CF_marker[j] == COMMON_C_PT) { CF_marker[j] = C_PT; } } for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { j = S_offd_j[jS]; if (j < 0) j = -j-1; if (CF_marker_offd[j] == COMMON_C_PT) { CF_marker_offd[j] = C_PT; } } } if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d CLJP phase = %f graph_size = %d nc_offd = %d\n", my_id, wall_time, graph_size, num_cols_offd); } } /*--------------------------------------------------- * Clean up and return *---------------------------------------------------*/ /* Reset S_matrix */ for (i=0; i < S_diag_i[num_variables]; i++) { if (S_diag_j[i] < 0) S_diag_j[i] = -S_diag_j[i]-1; } for (i=0; i < S_offd_i[num_variables]; i++) { if (S_offd_j[i] < 0) S_offd_j[i] = -S_offd_j[i]-1; } /*for (i=0; i < num_variables; i++) if (CF_marker[i] == SF_PT) CF_marker[i] = F_PT;*/ hypre_TFree(measure_array, HYPRE_MEMORY_HOST); hypre_TFree(graph_array, HYPRE_MEMORY_HOST); if (num_cols_offd) hypre_TFree(graph_array_offd, HYPRE_MEMORY_HOST); hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); if (num_procs > 1) hypre_CSRMatrixDestroy(S_ext); *CF_marker_ptr = CF_marker; return hypre_error_flag; } /*========================================================================== * Ruge's coarsening algorithm *==========================================================================*/ #define C_PT 1 #define F_PT -1 #define Z_PT -2 #define SF_PT -3 /* special fine points */ #define SC_PT 3 /* special coarse points */ #define UNDECIDED 0 /************************************************************** * * Ruge Coarsening routine * **************************************************************/ HYPRE_Int hypre_BoomerAMGCoarsenRuge( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int measure_type, HYPRE_Int coarsen_type, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_j = hypre_CSRMatrixJ(S_diag); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = NULL; HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(S_offd); HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(S); hypre_CSRMatrix *S_ext = NULL; HYPRE_Int *S_ext_i = NULL; HYPRE_BigInt *S_ext_j = NULL; hypre_CSRMatrix *ST; HYPRE_Int *ST_i; HYPRE_Int *ST_j; HYPRE_Int *CF_marker; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int ci_tilde = -1; HYPRE_Int ci_tilde_mark = -1; HYPRE_Int ci_tilde_offd = -1; HYPRE_Int ci_tilde_offd_mark = -1; HYPRE_Int *measure_array; HYPRE_Int *graph_array; HYPRE_Int *int_buf_data = NULL; HYPRE_Int *ci_array = NULL; HYPRE_BigInt big_k; HYPRE_Int i, j, k, jS; HYPRE_Int ji, jj, jk, jm, index; HYPRE_Int set_empty = 1; HYPRE_Int C_i_nonempty = 0; //HYPRE_Int num_nonzeros; HYPRE_Int num_procs, my_id; HYPRE_Int num_sends = 0; HYPRE_BigInt first_col; HYPRE_Int start; HYPRE_BigInt col_0, col_n; hypre_LinkList LoL_head; hypre_LinkList LoL_tail; HYPRE_Int *lists, *where; HYPRE_Int measure, new_meas; HYPRE_Int meas_type = 0; HYPRE_Int agg_2 = 0; HYPRE_Int num_left, elmt; HYPRE_Int nabor, nabor_two; HYPRE_Int use_commpkg_A = 0; HYPRE_Int break_var = 0; HYPRE_Int f_pnt = F_PT; HYPRE_Real wall_time; if (coarsen_type < 0) { coarsen_type = -coarsen_type; } if (measure_type == 1 || measure_type == 4) { meas_type = 1; } if (measure_type == 4 || measure_type == 3) { agg_2 = 1; } /*------------------------------------------------------- * Initialize the C/F marker, LoL_head, LoL_tail arrays *-------------------------------------------------------*/ LoL_head = NULL; LoL_tail = NULL; lists = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); where = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); #if 0 /* debugging */ char filename[256]; FILE *fp; HYPRE_Int iter = 0; #endif /*-------------------------------------------------------------- * Compute a CSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: the entries are negative initially, corresponding * to "unaccounted-for" dependence. *----------------------------------------------------------------*/ if (debug_flag == 3) wall_time = time_getWallclockSeconds(); first_col = hypre_ParCSRMatrixFirstColDiag(S); col_0 = first_col-1; col_n = col_0+(HYPRE_BigInt)num_variables; hypre_MPI_Comm_size(comm,&num_procs); hypre_MPI_Comm_rank(comm,&my_id); if (!comm_pkg) { use_commpkg_A = 1; comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); if (num_cols_offd) { S_offd_j = hypre_CSRMatrixJ(S_offd); } jS = S_i[num_variables]; ST = hypre_CSRMatrixCreate(num_variables, num_variables, jS); hypre_CSRMatrixMemoryLocation(ST) = HYPRE_MEMORY_HOST; ST_i = hypre_CTAlloc(HYPRE_Int, num_variables+1, HYPRE_MEMORY_HOST); ST_j = hypre_CTAlloc(HYPRE_Int, jS, HYPRE_MEMORY_HOST); hypre_CSRMatrixI(ST) = ST_i; hypre_CSRMatrixJ(ST) = ST_j; /*---------------------------------------------------------- * generate transpose of S, ST *----------------------------------------------------------*/ for (i=0; i <= num_variables; i++) { ST_i[i] = 0; } for (i=0; i < jS; i++) { ST_i[S_j[i]+1]++; } for (i=0; i < num_variables; i++) { ST_i[i+1] += ST_i[i]; } for (i=0; i < num_variables; i++) { for (j=S_i[i]; j < S_i[i+1]; j++) { index = S_j[j]; ST_j[ST_i[index]] = i; ST_i[index]++; } } for (i = num_variables; i > 0; i--) { ST_i[i] = ST_i[i-1]; } ST_i[0] = 0; /*---------------------------------------------------------- * Compute the measures * * The measures are given by the row sums of ST. * Hence, measure_array[i] is the number of influences * of variable i. * correct actual measures through adding influences from * neighbor processors *----------------------------------------------------------*/ measure_array = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); for (i = 0; i < num_variables; i++) { measure_array[i] = ST_i[i+1]-ST_i[i]; } /* special case for Falgout coarsening */ if (coarsen_type == 6) { f_pnt = Z_PT; coarsen_type = 1; } if (coarsen_type == 10) { f_pnt = Z_PT; coarsen_type = 11; } if ((meas_type || (coarsen_type != 1 && coarsen_type != 11)) && num_procs > 1) { if (use_commpkg_A) S_ext = hypre_ParCSRMatrixExtractBExt(S,A,0); else S_ext = hypre_ParCSRMatrixExtractBExt(S,S,0); S_ext_i = hypre_CSRMatrixI(S_ext); S_ext_j = hypre_CSRMatrixBigJ(S_ext); HYPRE_Int num_nonzeros = S_ext_i[num_cols_offd]; /*first_col = hypre_ParCSRMatrixFirstColDiag(S); col_0 = first_col-1; col_n = col_0+num_variables; */ if (meas_type) { for (i=0; i < num_nonzeros; i++) { index = (HYPRE_Int)(S_ext_j[i] - first_col); if (index > -1 && index < num_variables) measure_array[index]++; } } } /*--------------------------------------------------- * Loop until all points are either fine or coarse. *---------------------------------------------------*/ if (debug_flag == 3) wall_time = time_getWallclockSeconds(); /* first coarsening phase */ /************************************************************* * * Initialize the lists * *************************************************************/ CF_marker = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); num_left = 0; for (j = 0; j < num_variables; j++) { if (S_i[j+1]-S_i[j] == 0 && S_offd_i[j+1]-S_offd_i[j] == 0) { CF_marker[j] = SF_PT; if (agg_2) { CF_marker[j] = SC_PT; } measure_array[j] = 0; } else { CF_marker[j] = UNDECIDED; num_left++; } } for (j = 0; j < num_variables; j++) { measure = measure_array[j]; if (CF_marker[j] != SF_PT && CF_marker[j] != SC_PT) { if (measure > 0) { hypre_enter_on_lists(&LoL_head, &LoL_tail, measure, j, lists, where); } else { if (measure < 0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"negative measure!\n"); } /*if (measure < 0) hypre_printf("negative measure!\n");*/ CF_marker[j] = f_pnt; for (k = S_i[j]; k < S_i[j+1]; k++) { nabor = S_j[k]; if (CF_marker[nabor] != SF_PT && CF_marker[nabor] != SC_PT) { if (nabor < j) { new_meas = measure_array[nabor]; if (new_meas > 0) { hypre_remove_point(&LoL_head, &LoL_tail, new_meas, nabor, lists, where); } new_meas = ++(measure_array[nabor]); hypre_enter_on_lists(&LoL_head, &LoL_tail, new_meas, nabor, lists, where); } else { new_meas = ++(measure_array[nabor]); } } } --num_left; } } } /**************************************************************** * * Main loop of Ruge-Stueben first coloring pass. * * WHILE there are still points to classify DO: * 1) find first point, i, on list with max_measure * make i a C-point, remove it from the lists * 2) For each point, j, in S_i^T, * a) Set j to be an F-point * b) For each point, k, in S_j * move k to the list in LoL with measure one * greater than it occupies (creating new LoL * entry if necessary) * 3) For each point, j, in S_i, * move j to the list in LoL with measure one * smaller than it occupies (creating new LoL * entry if necessary) * ****************************************************************/ while (num_left > 0) { index = LoL_head -> head; CF_marker[index] = C_PT; measure = measure_array[index]; measure_array[index] = 0; --num_left; hypre_remove_point(&LoL_head, &LoL_tail, measure, index, lists, where); for (j = ST_i[index]; j < ST_i[index+1]; j++) { nabor = ST_j[j]; if (CF_marker[nabor] == UNDECIDED) { CF_marker[nabor] = F_PT; measure = measure_array[nabor]; hypre_remove_point(&LoL_head, &LoL_tail, measure, nabor, lists, where); --num_left; for (k = S_i[nabor]; k < S_i[nabor+1]; k++) { nabor_two = S_j[k]; if (CF_marker[nabor_two] == UNDECIDED) { measure = measure_array[nabor_two]; hypre_remove_point(&LoL_head, &LoL_tail, measure, nabor_two, lists, where); new_meas = ++(measure_array[nabor_two]); hypre_enter_on_lists(&LoL_head, &LoL_tail, new_meas, nabor_two, lists, where); } } } } for (j = S_i[index]; j < S_i[index+1]; j++) { nabor = S_j[j]; if (CF_marker[nabor] == UNDECIDED) { measure = measure_array[nabor]; hypre_remove_point(&LoL_head, &LoL_tail, measure, nabor, lists, where); measure_array[nabor] = --measure; if (measure > 0) { hypre_enter_on_lists(&LoL_head, &LoL_tail, measure, nabor, lists, where); } else { CF_marker[nabor] = F_PT; --num_left; for (k = S_i[nabor]; k < S_i[nabor+1]; k++) { nabor_two = S_j[k]; if (CF_marker[nabor_two] == UNDECIDED) { new_meas = measure_array[nabor_two]; hypre_remove_point(&LoL_head, &LoL_tail, new_meas, nabor_two, lists, where); new_meas = ++(measure_array[nabor_two]); hypre_enter_on_lists(&LoL_head, &LoL_tail, new_meas, nabor_two, lists, where); } } } } } } hypre_TFree(measure_array, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(ST); if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Coarsen 1st pass = %f\n", my_id, wall_time); } hypre_TFree(lists, HYPRE_MEMORY_HOST); hypre_TFree(where, HYPRE_MEMORY_HOST); hypre_TFree(LoL_head, HYPRE_MEMORY_HOST); hypre_TFree(LoL_tail, HYPRE_MEMORY_HOST); for (i=0; i < num_variables; i++) { if (CF_marker[i] == SC_PT) { CF_marker[i] = C_PT; } } if (coarsen_type == 11) { *CF_marker_ptr = CF_marker; if (meas_type && num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); } return 0; } /* second pass, check fine points for coarse neighbors for coarsen_type = 2, the second pass includes off-processore boundary points */ /*--------------------------------------------------- * Initialize the graph array *---------------------------------------------------*/ graph_array = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); for (i = 0; i < num_variables; i++) { graph_array[i] = -1; } if (debug_flag == 3) wall_time = time_getWallclockSeconds(); if (coarsen_type == 2) { /*------------------------------------------------ * Exchange boundary data for CF_marker *------------------------------------------------*/ CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } ci_array = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd; i++) ci_array[i] = -1; for (i=0; i < num_variables; i++) { if (ci_tilde_mark != i) ci_tilde = -1; if (ci_tilde_offd_mark != i) ci_tilde_offd = -1; if (CF_marker[i] == -1) { break_var = 1; for (ji = S_i[i]; ji < S_i[i+1]; ji++) { j = S_j[ji]; if (CF_marker[j] > 0) graph_array[j] = i; } for (ji = S_offd_i[i]; ji < S_offd_i[i+1]; ji++) { j = S_offd_j[ji]; if (CF_marker_offd[j] > 0) ci_array[j] = i; } for (ji = S_i[i]; ji < S_i[i+1]; ji++) { j = S_j[ji]; if (CF_marker[j] == -1) { set_empty = 1; for (jj = S_i[j]; jj < S_i[j+1]; jj++) { index = S_j[jj]; if (graph_array[index] == i) { set_empty = 0; break; } } if (set_empty) { for (jj = S_offd_i[j]; jj < S_offd_i[j+1]; jj++) { index = S_offd_j[jj]; if (ci_array[index] == i) { set_empty = 0; break; } } } if (set_empty) { if (C_i_nonempty) { CF_marker[i] = 1; if (ci_tilde > -1) { CF_marker[ci_tilde] = -1; ci_tilde = -1; } if (ci_tilde_offd > -1) { CF_marker_offd[ci_tilde_offd] = -1; ci_tilde_offd = -1; } C_i_nonempty = 0; break_var = 0; break; } else { ci_tilde = j; ci_tilde_mark = i; CF_marker[j] = 1; C_i_nonempty = 1; i--; break_var = 0; break; } } } } if (break_var) { for (ji = S_offd_i[i]; ji < S_offd_i[i+1]; ji++) { j = S_offd_j[ji]; if (CF_marker_offd[j] == -1) { set_empty = 1; for (jj = S_ext_i[j]; jj < S_ext_i[j+1]; jj++) { big_k = S_ext_j[jj]; if (big_k > col_0 && big_k < col_n) /* index interior */ { if (graph_array[(HYPRE_Int)(big_k-first_col)] == i) { set_empty = 0; break; } } else { jk = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (jk != -1) { if (ci_array[jk] == i) { set_empty = 0; break; } } } } if (set_empty) { if (C_i_nonempty) { CF_marker[i] = 1; if (ci_tilde > -1) { CF_marker[ci_tilde] = -1; ci_tilde = -1; } if (ci_tilde_offd > -1) { CF_marker_offd[ci_tilde_offd] = -1; ci_tilde_offd = -1; } C_i_nonempty = 0; break; } else { ci_tilde_offd = j; ci_tilde_offd_mark = i; CF_marker_offd[j] = 1; C_i_nonempty = 1; i--; break; } } } } } } } } else { for (i=0; i < num_variables; i++) { if (ci_tilde_mark != i) ci_tilde = -1; if (CF_marker[i] == -1) { for (ji = S_i[i]; ji < S_i[i+1]; ji++) { j = S_j[ji]; if (CF_marker[j] > 0) graph_array[j] = i; } for (ji = S_i[i]; ji < S_i[i+1]; ji++) { j = S_j[ji]; if (CF_marker[j] == -1) { set_empty = 1; for (jj = S_i[j]; jj < S_i[j+1]; jj++) { index = S_j[jj]; if (graph_array[index] == i) { set_empty = 0; break; } } if (set_empty) { if (C_i_nonempty) { CF_marker[i] = 1; if (ci_tilde > -1) { CF_marker[ci_tilde] = -1; ci_tilde = -1; } C_i_nonempty = 0; break; } else { ci_tilde = j; ci_tilde_mark = i; CF_marker[j] = 1; C_i_nonempty = 1; i--; break; } } } } } } } if (debug_flag == 3 && coarsen_type != 2) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Coarsen 2nd pass = %f\n", my_id, wall_time); } /* third pass, check boundary fine points for coarse neighbors */ if (coarsen_type == 3 || coarsen_type == 4) { if (debug_flag == 3) wall_time = time_getWallclockSeconds(); CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); /*------------------------------------------------ * Exchange boundary data for CF_marker *------------------------------------------------*/ index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } ci_array = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd; i++) ci_array[i] = -1; } if (coarsen_type > 1 && coarsen_type < 5) { for (i=0; i < num_variables; i++) graph_array[i] = -1; for (i=0; i < num_cols_offd; i++) { if (ci_tilde_mark != i) ci_tilde = -1; if (ci_tilde_offd_mark != i) ci_tilde_offd = -1; if (CF_marker_offd[i] == -1) { for (ji = S_ext_i[i]; ji < S_ext_i[i+1]; ji++) { big_k = S_ext_j[ji]; if (big_k > col_0 && big_k < col_n) { j = (HYPRE_Int)(big_k - first_col); if (CF_marker[j] > 0) graph_array[j] = i; } else { jj = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (jj != -1 && CF_marker_offd[jj] > 0) ci_array[jj] = i; } } for (ji = S_ext_i[i]; ji < S_ext_i[i+1]; ji++) { big_k = S_ext_j[ji]; if (big_k > col_0 && big_k < col_n) { j = (HYPRE_Int)(big_k - first_col); if ( CF_marker[j] == -1) { set_empty = 1; for (jj = S_i[j]; jj < S_i[j+1]; jj++) { index = S_j[jj]; if (graph_array[index] == i) { set_empty = 0; break; } } for (jj = S_offd_i[j]; jj < S_offd_i[j+1]; jj++) { index = S_offd_j[jj]; if (ci_array[index] == i) { set_empty = 0; break; } } if (set_empty) { if (C_i_nonempty) { CF_marker_offd[i] = 1; if (ci_tilde > -1) { CF_marker[ci_tilde] = -1; ci_tilde = -1; } if (ci_tilde_offd > -1) { CF_marker_offd[ci_tilde_offd] = -1; ci_tilde_offd = -1; } C_i_nonempty = 0; break; } else { ci_tilde = j; ci_tilde_mark = i; CF_marker[j] = 1; C_i_nonempty = 1; i--; break; } } } } else { jm = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (jm != -1 && CF_marker_offd[jm] == -1) { set_empty = 1; for (jj = S_ext_i[jm]; jj < S_ext_i[jm+1]; jj++) { big_k = S_ext_j[jj]; if (big_k > col_0 && big_k < col_n) { if (graph_array[(HYPRE_Int)(big_k-first_col)] == i) { set_empty = 0; break; } } else { jk = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (jk != -1) { if (ci_array[jk] == i) { set_empty = 0; break; } } } } if (set_empty) { if (C_i_nonempty) { CF_marker_offd[i] = 1; if (ci_tilde > -1) { CF_marker[ci_tilde] = -1; ci_tilde = -1; } if (ci_tilde_offd > -1) { CF_marker_offd[ci_tilde_offd] = -1; ci_tilde_offd = -1; } C_i_nonempty = 0; break; } else { ci_tilde_offd = jm; ci_tilde_offd_mark = i; CF_marker_offd[jm] = 1; C_i_nonempty = 1; i--; break; } } } } } } } /*------------------------------------------------ * Send boundary data for CF_marker back *------------------------------------------------*/ if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, CF_marker_offd, int_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); } /* only CF_marker entries from larger procs are accepted if coarsen_type = 4 coarse points are not overwritten */ index = 0; if (coarsen_type != 4) { for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); if (hypre_ParCSRCommPkgSendProc(comm_pkg,i) > my_id) { for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] = int_buf_data[index++]; } else { index += hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - start; } } } else { for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); if (hypre_ParCSRCommPkgSendProc(comm_pkg,i) > my_id) { for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { elmt = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); if (CF_marker[elmt] != 1) CF_marker[elmt] = int_buf_data[index]; index++; } } else { index += hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - start; } } } if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; if (coarsen_type == 4) hypre_printf("Proc = %d Coarsen 3rd pass = %f\n", my_id, wall_time); if (coarsen_type == 3) hypre_printf("Proc = %d Coarsen 3rd pass = %f\n", my_id, wall_time); if (coarsen_type == 2) hypre_printf("Proc = %d Coarsen 2nd pass = %f\n", my_id, wall_time); } } if (coarsen_type == 5) { /*------------------------------------------------ * Exchange boundary data for CF_marker *------------------------------------------------*/ if (debug_flag == 3) wall_time = time_getWallclockSeconds(); CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } ci_array = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); for (i=0; i < num_cols_offd; i++) ci_array[i] = -1; for (i=0; i < num_variables; i++) graph_array[i] = -1; for (i=0; i < num_variables; i++) { if (CF_marker[i] == -1 && (S_offd_i[i+1]-S_offd_i[i]) > 0) { break_var = 1; for (ji = S_i[i]; ji < S_i[i+1]; ji++) { j = S_j[ji]; if (CF_marker[j] > 0) graph_array[j] = i; } for (ji = S_offd_i[i]; ji < S_offd_i[i+1]; ji++) { j = S_offd_j[ji]; if (CF_marker_offd[j] > 0) ci_array[j] = i; } for (ji = S_offd_i[i]; ji < S_offd_i[i+1]; ji++) { j = S_offd_j[ji]; if (CF_marker_offd[j] == -1) { set_empty = 1; for (jj = S_ext_i[j]; jj < S_ext_i[j+1]; jj++) { big_k = S_ext_j[jj]; if (big_k > col_0 && big_k < col_n) /* index interior */ { if (graph_array[(HYPRE_Int)(big_k-first_col)] == i) { set_empty = 0; break; } } else { jk = hypre_BigBinarySearch(col_map_offd,big_k,num_cols_offd); if (jk != -1) { if (ci_array[jk] == i) { set_empty = 0; break; } } } } if (set_empty) { if (C_i_nonempty) { CF_marker[i] = -2; C_i_nonempty = 0; break; } else { C_i_nonempty = 1; i--; break; } } } } } } if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Coarsen special points = %f\n", my_id, wall_time); } } /*--------------------------------------------------- * Clean up and return *---------------------------------------------------*/ /*if (coarsen_type != 1) { */ hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(ci_array, HYPRE_MEMORY_HOST); /*} */ hypre_TFree(graph_array, HYPRE_MEMORY_HOST); if ((meas_type || (coarsen_type != 1 && coarsen_type != 11)) && num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); } *CF_marker_ptr = CF_marker; return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGCoarsenFalgout( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int measure_type, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { HYPRE_Int ierr = 0; /*------------------------------------------------------- * Perform Ruge coarsening followed by CLJP coarsening *-------------------------------------------------------*/ ierr += hypre_BoomerAMGCoarsenRuge (S, A, measure_type, 6, debug_flag, CF_marker_ptr); ierr += hypre_BoomerAMGCoarsen (S, A, 1, debug_flag, CF_marker_ptr); return (ierr); } /*--------------------------------------------------------------------------*/ #define C_PT 1 #define F_PT -1 #define SF_PT -3 #define COMMON_C_PT 2 #define Z_PT -2 /* begin HANS added */ /************************************************************** * * Modified Independent Set Coarsening routine * (don't worry about strong F-F connections * without a common C point) * **************************************************************/ HYPRE_Int hypre_BoomerAMGCoarsenPMISHost( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int CF_init, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PMIS] -= hypre_MPI_Wtime(); #endif MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j; HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int num_cols_offd = 0; /* hypre_CSRMatrix *S_ext; HYPRE_Int *S_ext_i; HYPRE_Int *S_ext_j; */ HYPRE_Int num_sends = 0; HYPRE_Int *int_buf_data; HYPRE_Real *buf_data; HYPRE_Int *CF_marker; HYPRE_Int *CF_marker_offd; HYPRE_Real *measure_array; HYPRE_Int *graph_array; HYPRE_Int *graph_array_offd; HYPRE_Int graph_size; HYPRE_BigInt big_graph_size; HYPRE_Int graph_offd_size; HYPRE_BigInt global_graph_size; HYPRE_Int i, j, jj, jS, ig; HYPRE_Int index, start, my_id, num_procs, jrow, cnt, elmt; HYPRE_Int ierr = 0; HYPRE_Real wall_time; HYPRE_Int iter = 0; HYPRE_Int *prefix_sum_workspace; #if 0 /* debugging */ char filename[256]; FILE *fp; HYPRE_Int iter = 0; #endif /******************************************************************************* BEFORE THE INDEPENDENT SET COARSENING LOOP: measure_array: calculate the measures, and communicate them (this array contains measures for both local and external nodes) CF_marker, CF_marker_offd: initialize CF_marker (separate arrays for local and external; 0=unassigned, negative=F point, positive=C point) ******************************************************************************/ /*-------------------------------------------------------------- * Use the ParCSR strength matrix, S. * * For now, the "strength" of dependence/influence is defined in * the following way: i depends on j if * aij > hypre_max (k != i) aik, aii < 0 * or * aij < hypre_min (k != i) aik, aii >= 0 * Then S_ij = 1, else S_ij = 0. * * NOTE: S_data is not used; in stead, only strong columns are retained * in S_j, which can then be used like S_data *----------------------------------------------------------------*/ /*S_ext = NULL; */ if (debug_flag == 3) { wall_time = time_getWallclockSeconds(); } hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (!comm_pkg) { comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); num_cols_offd = hypre_CSRMatrixNumCols(S_offd); S_diag_j = hypre_CSRMatrixJ(S_diag); if (num_cols_offd) { S_offd_j = hypre_CSRMatrixJ(S_offd); } /*---------------------------------------------------------- * Compute the measures * * The measures are currently given by the column sums of S. * Hence, measure_array[i] is the number of influences * of variable i. * * The measures are augmented by a random number * between 0 and 1. *----------------------------------------------------------*/ measure_array = hypre_CTAlloc(HYPRE_Real, num_variables + num_cols_offd, HYPRE_MEMORY_HOST); /* first calculate the local part of the sums for the external nodes */ #ifdef HYPRE_USING_OPENMP HYPRE_Int *measure_array_temp = hypre_CTAlloc(HYPRE_Int, num_variables + num_cols_offd, HYPRE_MEMORY_HOST); #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE for (i = 0; i < S_offd_i[num_variables]; i++) { #pragma omp atomic measure_array_temp[num_variables + S_offd_j[i]]++; } #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE for (i = 0; i < num_cols_offd; i++) { measure_array[i + num_variables] = measure_array_temp[i + num_variables]; } #else for (i = 0; i < S_offd_i[num_variables]; i++) { measure_array[num_variables + S_offd_j[i]] += 1.0; } #endif // HYPRE_USING_OPENMP /* now send those locally calculated values for the external nodes to the neighboring processors */ if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(2, comm_pkg, &measure_array[num_variables], buf_data); } /* calculate the local part for the local nodes */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE for (i = 0; i < S_diag_i[num_variables]; i++) { #pragma omp atomic measure_array_temp[S_diag_j[i]]++; } #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE for (i = 0; i < num_variables; i++) { measure_array[i] = measure_array_temp[i]; } hypre_TFree(measure_array_temp, HYPRE_MEMORY_HOST); #else for (i = 0; i < S_diag_i[num_variables]; i++) { measure_array[S_diag_j[i]] += 1.0; } #endif // HYPRE_USING_OPENMP /* finish the communication */ if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); } /* now add the externally calculated part of the local nodes to the local nodes */ index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { measure_array[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)] += buf_data[index++]; } } /* set the measures of the external nodes to zero */ for (i = num_variables; i < num_variables + num_cols_offd; i++) { measure_array[i] = 0; } /* this augments the measures with a random number between 0 and 1 */ /* (only for the local part) */ /* this augments the measures */ if (CF_init == 2 || CF_init == 4) { hypre_BoomerAMGIndepSetInit(S, measure_array, 1); } else { hypre_BoomerAMGIndepSetInit(S, measure_array, 0); } /*--------------------------------------------------- * Initialize the graph arrays, and CF_marker arrays *---------------------------------------------------*/ /* first the off-diagonal part of the graph array */ if (num_cols_offd) { graph_array_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); } else { graph_array_offd = NULL; } for (ig = 0; ig < num_cols_offd; ig++) { graph_array_offd[ig] = ig; } graph_offd_size = num_cols_offd; /* now the local part of the graph array, and the local CF_marker array */ graph_array = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); if (CF_init == 1) { CF_marker = *CF_marker_ptr; cnt = 0; for (i = 0; i < num_variables; i++) { if ( S_offd_i[i+1] - S_offd_i[i] > 0 || CF_marker[i] == -1 ) { CF_marker[i] = 0; } if ( CF_marker[i] == Z_PT) { if ( measure_array[i] >= 1.0 || S_diag_i[i+1] - S_diag_i[i] > 0 ) { CF_marker[i] = 0; graph_array[cnt++] = i; } else { CF_marker[i] = F_PT; } } else if (CF_marker[i] == SF_PT) { measure_array[i] = 0; } else { graph_array[cnt++] = i; } } } else { CF_marker = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); cnt = 0; for (i = 0; i < num_variables; i++) { CF_marker[i] = 0; if ( S_diag_i[i+1] - S_diag_i[i] == 0 && S_offd_i[i+1] - S_offd_i[i] == 0) { CF_marker[i] = SF_PT; /* an isolated fine grid */ if (CF_init == 3 || CF_init == 4) { CF_marker[i] = C_PT; } measure_array[i] = 0; } else { graph_array[cnt++] = i; } } } graph_size = cnt; /* now the off-diagonal part of CF_marker */ if (num_cols_offd) { CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); } else { CF_marker_offd = NULL; } for (i = 0; i < num_cols_offd; i++) { CF_marker_offd[i] = 0; } /*------------------------------------------------ * Communicate the local measures, which are complete, to the external nodes *------------------------------------------------*/ index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { jrow = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); buf_data[index++] = measure_array[jrow]; } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, buf_data, &measure_array[num_variables]); hypre_ParCSRCommHandleDestroy(comm_handle); } if (debug_flag == 3) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Initialize CLJP phase = %f\n", my_id, wall_time); } /* graph_array2 */ HYPRE_Int *graph_array2 = hypre_CTAlloc(HYPRE_Int, num_variables, HYPRE_MEMORY_HOST); HYPRE_Int *graph_array_offd2 = NULL; if (num_cols_offd) { graph_array_offd2 = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); } /******************************************************************************* THE INDEPENDENT SET COARSENING LOOP: ******************************************************************************/ /*--------------------------------------------------- * Loop until all points are either fine or coarse. *---------------------------------------------------*/ while (1) { big_graph_size = (HYPRE_BigInt) graph_size; /* stop the coarsening if nothing left to be coarsened */ hypre_MPI_Allreduce(&big_graph_size, &global_graph_size, 1, HYPRE_MPI_BIG_INT, hypre_MPI_SUM,comm); /* if (my_id == 0) { hypre_printf("graph size %b\n", global_graph_size); } */ if (global_graph_size == 0) { break; } /* hypre_printf("\n"); hypre_printf("*** MIS iteration %d\n",iter); hypre_printf("graph_size remaining %d\n",graph_size); */ /*----------------------------------------------------------------------------------------- * Pick an independent set of points with maximal measure * At the end, CF_marker is complete, but still needs to be communicated to CF_marker_offd * for CF_init == 1, as in HMIS, the first IS was fed from prior R-S coarsening *----------------------------------------------------------------------------------------*/ if (!CF_init || iter) { /* hypre_BoomerAMGIndepSet(S, measure_array, graph_array, graph_size, graph_array_offd, graph_offd_size, CF_marker, CF_marker_offd); */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ig, i) HYPRE_SMP_SCHEDULE #endif for (ig = 0; ig < graph_size; ig++) { i = graph_array[ig]; if (measure_array[i] > 1) { CF_marker[i] = 1; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ig, i) HYPRE_SMP_SCHEDULE #endif for (ig = 0; ig < graph_offd_size; ig++) { i = graph_array_offd[ig]; if (measure_array[i+num_variables] > 1) { CF_marker_offd[i] = 1; } } /*------------------------------------------------------- * Remove nodes from the initial independent set *-------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ig, i, jS, j, jj) HYPRE_SMP_SCHEDULE #endif for (ig = 0; ig < graph_size; ig++) { i = graph_array[ig]; if (measure_array[i] > 1) { /* for each local neighbor j of i */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { j = S_diag_j[jS]; if (measure_array[j] > 1) { if (measure_array[i] > measure_array[j]) { CF_marker[j] = 0; } else if (measure_array[j] > measure_array[i]) { CF_marker[i] = 0; } } } /* for each offd neighbor j of i */ for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { jj = S_offd_j[jS]; j = num_variables + jj; if (measure_array[j] > 1) { if (measure_array[i] > measure_array[j]) { CF_marker_offd[jj] = 0; } else if (measure_array[j] > measure_array[i]) { CF_marker[i] = 0; } } } } /* for each node with measure > 1 */ } /* for each node i */ /*------------------------------------------------------------------------------ * Exchange boundary data for CF_marker: send external CF to internal CF *------------------------------------------------------------------------------*/ if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(12, comm_pkg, CF_marker_offd, int_buf_data); hypre_ParCSRCommHandleDestroy(comm_handle); } index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { elmt = hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j); if (!int_buf_data[index] && CF_marker[elmt] > 0) { CF_marker[elmt] = 0; index++; } else { int_buf_data[index++] = CF_marker[elmt]; } } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } } /* if (!CF_init || iter) */ iter++; /*------------------------------------------------ * Set C-pts and F-pts. *------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ig, i, jS, j) HYPRE_SMP_SCHEDULE #endif for (ig = 0; ig < graph_size; ig++) { i = graph_array[ig]; /*--------------------------------------------- * If the measure of i is smaller than 1, then * make i and F point (because it does not influence * any other point) *---------------------------------------------*/ if (measure_array[i] < 1) { CF_marker[i]= F_PT; } /*--------------------------------------------- * First treat the case where point i is in the * independent set: make i a C point, *---------------------------------------------*/ if (CF_marker[i] > 0) { CF_marker[i] = C_PT; } /*--------------------------------------------- * Now treat the case where point i is not in the * independent set: loop over * all the points j that influence equation i; if * j is a C point, then make i an F point. *---------------------------------------------*/ else { /* first the local part */ for (jS = S_diag_i[i]; jS < S_diag_i[i+1]; jS++) { /* j is the column number, or the local number of the point influencing i */ j = S_diag_j[jS]; if (CF_marker[j] > 0) /* j is a C-point */ { CF_marker[i] = F_PT; } } /* now the external part */ for (jS = S_offd_i[i]; jS < S_offd_i[i+1]; jS++) { j = S_offd_j[jS]; if (CF_marker_offd[j] > 0) /* j is a C-point */ { CF_marker[i] = F_PT; } } } /* end else */ } /* end first loop over graph */ /* now communicate CF_marker to CF_marker_offd, to make sure that new external F points are known on this processor */ /*------------------------------------------------------------------------------ * Exchange boundary data for CF_marker: send internal points to external points *------------------------------------------------------------------------------*/ index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } if (num_procs > 1) { comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } /*------------------------------------------------ * Update subgraph *------------------------------------------------*/ /*HYPRE_Int prefix_sum_workspace[2*(hypre_NumThreads() + 1)];*/ prefix_sum_workspace = hypre_TAlloc(HYPRE_Int, 2*(hypre_NumThreads() + 1), HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ig,i) #endif { HYPRE_Int private_graph_size_cnt = 0; HYPRE_Int private_graph_offd_size_cnt = 0; HYPRE_Int ig_begin, ig_end; hypre_GetSimpleThreadPartition(&ig_begin, &ig_end, graph_size); HYPRE_Int ig_offd_begin, ig_offd_end; hypre_GetSimpleThreadPartition(&ig_offd_begin, &ig_offd_end, graph_offd_size); for (ig = ig_begin; ig < ig_end; ig++) { i = graph_array[ig]; if (CF_marker[i] != 0) /* C or F point */ { /* the independent set subroutine needs measure 0 for removed nodes */ measure_array[i] = 0; } else { private_graph_size_cnt++; } } for (ig = ig_offd_begin; ig < ig_offd_end; ig++) { i = graph_array_offd[ig]; if (CF_marker_offd[i] != 0) /* C of F point */ { /* the independent set subroutine needs measure 0 for removed nodes */ measure_array[i + num_variables] = 0; } else { private_graph_offd_size_cnt++; } } hypre_prefix_sum_pair(&private_graph_size_cnt, &graph_size, &private_graph_offd_size_cnt, &graph_offd_size, prefix_sum_workspace); for (ig = ig_begin; ig < ig_end; ig++) { i = graph_array[ig]; if (CF_marker[i] == 0) { graph_array2[private_graph_size_cnt++] = i; } } for (ig = ig_offd_begin; ig < ig_offd_end; ig++) { i = graph_array_offd[ig]; if (CF_marker_offd[i] == 0) { graph_array_offd2[private_graph_offd_size_cnt++] = i; } } } /* omp parallel */ HYPRE_Int *temp = graph_array; graph_array = graph_array2; graph_array2 = temp; temp = graph_array_offd; graph_array_offd = graph_array_offd2; graph_array_offd2 = temp; hypre_TFree(prefix_sum_workspace, HYPRE_MEMORY_HOST); } /* end while */ /* hypre_printf("*** MIS iteration %d\n",iter); hypre_printf("graph_size remaining %d\n",graph_size); hypre_printf("num_cols_offd %d\n",num_cols_offd); for (i=0;i<num_variables;i++) { if(CF_marker[i] == 1) { hypre_printf("node %d CF %d\n",i,CF_marker[i]); } } */ /*--------------------------------------------------- * Clean up and return *---------------------------------------------------*/ hypre_TFree(measure_array, HYPRE_MEMORY_HOST); hypre_TFree(graph_array, HYPRE_MEMORY_HOST); hypre_TFree(graph_array2, HYPRE_MEMORY_HOST); hypre_TFree(graph_array_offd2, HYPRE_MEMORY_HOST); if (num_cols_offd) { hypre_TFree(graph_array_offd, HYPRE_MEMORY_HOST); } hypre_TFree(buf_data, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); /*if (num_procs > 1) hypre_CSRMatrixDestroy(S_ext);*/ *CF_marker_ptr = CF_marker; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PMIS] += hypre_MPI_Wtime(); #endif return (ierr); } HYPRE_Int hypre_BoomerAMGCoarsenPMIS( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int CF_init, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { #if defined(HYPRE_USING_CUDA) //hypre_SetExecPolicy(HYPRE_EXEC_DEVICE); #endif HYPRE_Int exec = hypre_GetExecPolicy1( hypre_CSRMatrixMemoryLocation(hypre_ParCSRMatrixDiag(A)) ); hypre_assert(exec != HYPRE_EXEC_UNSET); HYPRE_Int ierr = 0; if (exec == HYPRE_EXEC_HOST) { /* printf(" coarsen PMIS Host \n");*/ ierr = hypre_BoomerAMGCoarsenPMISHost( S, A, CF_init, debug_flag, CF_marker_ptr ); } #if defined(HYPRE_USING_CUDA) else { /* printf(" coarsen PMIS Device \n");*/ ierr = hypre_BoomerAMGCoarsenPMISDevice( S, A, CF_init, debug_flag, CF_marker_ptr ); } #endif #if defined(HYPRE_USING_CUDA) //hypre_SetExecPolicy(HYPRE_EXEC_HOST); #endif return ierr; } HYPRE_Int hypre_BoomerAMGCoarsenHMIS( hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int measure_type, HYPRE_Int debug_flag, HYPRE_Int **CF_marker_ptr) { HYPRE_Int ierr = 0; /*------------------------------------------------------- * Perform Ruge coarsening followed by CLJP coarsening *-------------------------------------------------------*/ ierr += hypre_BoomerAMGCoarsenRuge (S, A, measure_type, 10, debug_flag, CF_marker_ptr); ierr += hypre_BoomerAMGCoarsenPMISHost (S, A, 1, debug_flag, CF_marker_ptr); return (ierr); }
Example_target_data.6.c
/* * @@name: target_data.6c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ #define THRESHOLD 1000000 extern void init(float*, float*, int); extern void init_again(float*, float*, int); extern void output(float*, int); void vec_mult(float *p, float *v1, float *v2, int N) { int i; init(v1, v2, N); #pragma omp target data if(N>THRESHOLD) map(from: p[0:N]) { #pragma omp target if (N>THRESHOLD) map(to: v1[:N], v2[:N]) #pragma omp parallel for for (i=0; i<N; i++) p[i] = v1[i] * v2[i]; init_again(v1, v2, N); #pragma omp target if (N>THRESHOLD) map(to: v1[:N], v2[:N]) #pragma omp parallel for for (i=0; i<N; i++) p[i] = p[i] + (v1[i] * v2[i]); } output(p, N); }
rgb2yuv_sse.c
/** * @file rgb2yuv_sse.c * * RGB2YUV sse */ #include "rgb2yuv.h" #include <xmmintrin.h> #include <emmintrin.h> #include <tmmintrin.h> void rgb2yuv_sse(uint8_t *pixels, int count) { int i; uint8_t *p = pixels; __m128i v_byte1 = _mm_set1_epi32(0x000000ff); __m128i v_byte3 = _mm_set1_epi32(0x00ff0000); __m128i v_mat_00 = _mm_set1_epi16((short int)47); __m128i v_mat_01 = _mm_set1_epi16((short int)157); __m128i v_mat_02 = _mm_set1_epi16((short int)16); __m128i v_mat_03 = _mm_set1_epi16((short int)4096); __m128i v_mat_04 = _mm_set1_epi16((short int)-26); __m128i v_mat_05 = _mm_set1_epi16((short int)-87); __m128i v_mat_06 = _mm_set1_epi16((short int)112); __m128i v_mat_07 = _mm_set1_epi16((short int)32768); __m128i v_mat_08 = _mm_set1_epi16((short int)112); __m128i v_mat_09 = _mm_set1_epi16((short int)-102); __m128i v_mat_10 = _mm_set1_epi16((short int)-10); __m128i v_mat_11 = _mm_set1_epi16((short int)32768); __m128i mask2 = _mm_set1_epi32(0x00ff00ff); __m128i mask_y1 = _mm_set_epi8((char)128, (char)128, 12, (char)128, (char)128, (char)128, 8, (char)128, (char)128, (char)128, 4, (char)128, (char)128, (char)128, 0, (char)128); __m128i mask_y2 = _mm_set_epi8((char)128, (char)128, 14, (char)128, (char)128, (char)128, 10, (char)128, (char)128, (char)128, 6, (char)128, (char)128, (char)128, 2, (char)128); __m128i mask_u1 = _mm_set_epi8((char)128, 12, (char)128, (char)128, (char)128, 8, (char)128, (char)128, (char)128, 4, (char)128, (char)128, (char)128, 0, (char)128, (char)128); __m128i mask_u2 = _mm_set_epi8((char)128, 14, (char)128, (char)128, (char)128, 10, (char)128, (char)128, (char)128, 6, (char)128, (char)128, (char)128, 2, (char)128, (char)128); __m128i mask_v1 = _mm_set_epi8(12, (char)128, (char)128, (char)128, 8, (char)128, (char)128, (char)128, 4, (char)128, (char)128, (char)128, 0, (char)128, (char)128, (char)128); __m128i mask_v2 = _mm_set_epi8(14, (char)128, (char)128, (char)128, 10, (char)128, (char)128, (char)128, 6, (char)128, (char)128, (char)128, 2, (char)128, (char)128, (char)128); // #pragma omp parallel for for (i=0; i<count / 8; i++) { __m128i a1, a2, r, g, b, y, u, v, res; a1 = _mm_loadu_si128((__m128i *)&p[i*32]); a2 = _mm_loadu_si128((__m128i *)&p[i*32 + 16]); r = _mm_or_si128(_mm_and_si128(_mm_srli_si128(a1, 1), v_byte1), _mm_and_si128(_mm_slli_si128(a2, 1), v_byte3)); g = _mm_or_si128(_mm_and_si128(_mm_srli_si128(a1, 2), v_byte1), _mm_and_si128(a2, v_byte3)); b = _mm_or_si128(_mm_and_si128(_mm_srli_si128(a1, 3), v_byte1), _mm_and_si128(_mm_srli_si128(a2, 1), v_byte3)); y = _mm_add_epi16( _mm_add_epi16( _mm_mullo_epi16(r, v_mat_00), _mm_mullo_epi16(g, v_mat_01)), _mm_add_epi16( _mm_mullo_epi16(b, v_mat_02), v_mat_03)); y = _mm_and_si128(_mm_srai_epi16(y, 8), mask2); u = _mm_add_epi16( _mm_add_epi16( _mm_mullo_epi16(r, v_mat_04), _mm_mullo_epi16(g, v_mat_05)), _mm_add_epi16( _mm_mullo_epi16(b, v_mat_06), v_mat_07)); u = _mm_and_si128(_mm_srai_epi16(u, 8), mask2); v = _mm_add_epi16( _mm_add_epi16( _mm_mullo_epi16(r, v_mat_08), _mm_mullo_epi16(g, v_mat_09)), _mm_add_epi16( _mm_mullo_epi16(b, v_mat_10), v_mat_11)); v = _mm_and_si128(_mm_srai_epi16(v, 8), mask2); res = _mm_or_si128(_mm_shuffle_epi8(y, mask_y1), _mm_shuffle_epi8(u, mask_u1)); res = _mm_or_si128(res, _mm_shuffle_epi8(v, mask_v1)); _mm_storeu_si128((__m128i *)&p[i*32], res); res = _mm_or_si128(_mm_shuffle_epi8(y, mask_y2), _mm_shuffle_epi8(u, mask_u2)); res = _mm_or_si128(res, _mm_shuffle_epi8(v, mask_v2)); _mm_storeu_si128((__m128i *)&p[i*32 + 16], res); } }
example_matrix_vector_multiplication_mpi_openmp.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <mpi.h> int main (int argc, char *argv[]){ double *matrix, *vector_in, *vector_out, out; long dim_mn, iterations, i, j, iteration; struct timeval start, stop, tdiff; int mpi_size, mpi_rank; double exec_time; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &mpi_size); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank); if (argc!=3){ if (mpi_rank==0){ fprintf(stderr, "%s matrixdimension numberofiterations\n", argv[0]); } exit(1); } dim_mn = atoi(argv[1]); iterations = atoi(argv[2]); if ((dim_mn<1)||(iterations<1)){ if (mpi_rank==0){ fprintf(stderr, "matrixdimension and numberofiterations must be " "positive integers\n"); } exit(2); } if (dim_mn%mpi_size!=0){ if (mpi_rank==0){ fprintf(stderr, "matrixdimension must be a multiple of number of " "MPI ranks\n"); } exit(3); } matrix = (double*) malloc(dim_mn/mpi_size*dim_mn*sizeof(double)); vector_in = (double*) malloc(dim_mn*sizeof(double)); vector_out = (double*) malloc(dim_mn/mpi_size*sizeof(double)); for (i=0; i<dim_mn/mpi_size; i++){ for (j=0; j<dim_mn; j++){ matrix[i*dim_mn+j] = 0.; } } for (i=0; i<dim_mn; i++){ vector_in[i] = 1.; } for (i=0; i<dim_mn/mpi_size; i++){ matrix[i*dim_mn+i+mpi_rank*dim_mn/mpi_size] = 1.; } gettimeofday(&start, NULL); for (iteration=0; iteration<iterations; iteration++){ #pragma omp parallel private(i, j, out) { #pragma omp for for (i=0; i<dim_mn/mpi_size; i++){ out = 0.; for (j=0; j<dim_mn; j++){ out += matrix[i*dim_mn+j]*vector_in[j]; } vector_out[i] = out; } } MPI_Allgather(vector_out, dim_mn/mpi_size, MPI_LONG, vector_in, dim_mn/mpi_size, MPI_LONG, MPI_COMM_WORLD); } gettimeofday(&stop, NULL); timersub(&stop, &start, &tdiff); exec_time = ((double)tdiff.tv_sec+((double)tdiff.tv_usec)/1000000.) /iterations; if (mpi_rank==0){ MPI_Reduce(MPI_IN_PLACE, &exec_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); printf("time for single matrix vector multiplication %E s\n", exec_time); }else{ MPI_Reduce(&exec_time, &exec_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); } double l2_norm = 0.0; for (i=0; i < dim_mn/mpi_size; i++){ l2_norm += vector_out[i] * vector_out[i]; } if (mpi_rank==0){ MPI_Reduce(MPI_IN_PLACE, &l2_norm, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); printf("The L2 norm of the resulting vector is: %E\n", l2_norm); }else{ MPI_Reduce(&l2_norm, &l2_norm, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); } free(vector_out); free(vector_in); free(matrix); MPI_Finalize(); return(0); }
matdiv.c
#include "matrix.h" /** \brief Computes element-wise matrix inverse * * \param[in] A Input matrix * \param[in] result Matrix to store the result * \return \f$ \mathbf{11}^T./\mathbf{A} \f$ * */ MATRIX mat_inv_dot(MATRIX A, MATRIX result) { int i, j, m, n; m = MatCol(A); n = MatRow(A); if(result==NULL) if((result = mat_creat(n, m, UNDEFINED))==NULL) return mat_error(MAT_MALLOC); #pragma omp parallel for private(j) for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { result[i][j] = 1.0/A[i][j]; } } return (result); } /** \brief Computes element-wise matrix division * * \param[in] A First input matrix * \param[in] B Second input matrix * \param[in] result Matrix to store the result * \return \f$ \mathbf{A}./\mathbf{B} \f$ * */ MATRIX mat_div_dot(MATRIX A, MATRIX B, MATRIX result) { int i, j, m, n, o, p; m = MatCol(A); n = MatRow(A); o = MatCol(B); p = MatRow(B); if(result==NULL) if((result = mat_creat(MatRow(A), MatCol(A), UNDEFINED))==NULL) return mat_error(MAT_MALLOC); if(o==m &&p==n) { #pragma omp parallel for private(j) for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { result[i][j] = A[i][j]/B[i][j]; } } } else if(o==1 && p!=1) { #pragma omp parallel for private(j) for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { result[i][j] = A[i][j]/B[i][0]; } } } else if(p==1 && o!=1) { #pragma omp parallel for private(j) for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { result[i][j] = A[i][j]/B[0][j]; } } } else gen_error(GEN_SIZEMISMATCH); return result; } /** \brief Divides a matrix by a scalar * * \param[in] A Input matrix * \param[in] s Scalar * \param[in] result Matrix to store the result * \return \f$ \dfrac{\mathbf{A}}{s} \f$ * */ MATRIX mat_divs(MATRIX A, mtype s, MATRIX result) { return mat_muls(A, (1.0f/s), result); } /** \brief Divides a scalar by a matrix * * \param[in] A Input matrix * \param[in] s Scalar * \param[in] result Matrix to store the result * \return \f$ s\mathbf{11}^T./\mathbf{A} \f$ * */ MATRIX mat_divs_inv(MATRIX A, mtype s, MATRIX result) { int i, j, m, n; m = MatCol(A); n = MatRow(A); if(result==NULL) if((result = mat_creat(n, m, UNDEFINED))==NULL) return mat_error(MAT_MALLOC); #pragma omp parallel for private(j) for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { result[i][j] = s/A[i][j]; } } return (result); } /** \brief Computes element-wise integer vector division * * \param[in] A First input vector * \param[in] B Second input vector * \param[in] result Vector to store the result * \return \f$ A./B \f$ * */ INT_VECTOR int_vec_div(INT_VECTOR A, INT_VECTOR B, INT_VECTOR result) { int i, m; m = Int_VecLen(A); if(result==NULL) if((result = int_vec_creat(m, UNDEFINED))==NULL) int_vec_error(INT_VEC_MALLOC); if(m!=Int_VecLen(B)) gen_error(GEN_SIZEMISMATCH); #pragma omp parallel for for(i=0; i<m; ++i) result[i] = A[i]/B[i]; return result; } /** \brief Divides an integer vector by a scalar * * \param[in] A Input vector * \param[in] s Scalar * \param[in] result Vector to store the result * \return \f$ \dfrac{A}{s} \f$ * */ INT_VECTOR int_vec_divs(INT_VECTOR A, int s, INT_VECTOR result) { int i, m; m = Int_VecLen(A); if(result==NULL) if((result = int_vec_creat(m, UNDEFINED))==NULL) int_vec_error(INT_VEC_MALLOC); #pragma omp parallel for for(i=0; i<m; ++i) result[i] = A[i]/s; return result; } /** \brief Computes element-wise integer vector inverse * * \param[in] A Input vector * \param[in] result Vector to store the result * \return \f$ 1./A \f$ * */ INT_VECTOR int_vec_inv(INT_VECTOR A, INT_VECTOR result) { int i, m; m = Int_VecLen(A); if(result==NULL) if((result = int_vec_creat(m, UNDEFINED))==NULL) int_vec_error(INT_VEC_MALLOC); #pragma omp parallel for for(i=0; i<m; ++i) result[i] = 1.0/A[i]; return result; } /** \brief Divides a scalar by an integer vector * * \param[in] A Input vector * \param[in] s Scalar * \param[in] result Vector to store the result * \return \f$ s1./A \f$ * */ INT_VECTOR int_vec_divs_inv(INT_VECTOR A, int s, INT_VECTOR result) { int i, m; m = Int_VecLen(A); if(result==NULL) if((result = int_vec_creat(m, UNDEFINED))==NULL) int_vec_error(INT_VEC_MALLOC); #pragma omp parallel for for(i=0; i<m; ++i) result[i] = s/A[i]; return result; }
omp_nested.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include "omp_testsuite.h" /* * Test if the compiler supports nested parallelism * By Chunhua Liao, University of Houston * Oct. 2005 */ int test_omp_nested() { #ifdef _OPENMP if (omp_get_max_threads() > 4) omp_set_num_threads(4); if (omp_get_max_threads() < 2) omp_set_num_threads(2); #endif int counter = 0; #ifdef _OPENMP omp_set_nested(1); #endif #pragma omp parallel shared(counter) { #pragma omp critical counter++; #pragma omp parallel { #pragma omp critical counter--; } } return (counter != 0); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_nested()) { num_failed++; } } return num_failed; }
core_dsyssq.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zsyssq.c, normal z -> d, Fri Sep 28 17:38:23 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" #include <math.h> /******************************************************************************/ __attribute__((weak)) void plasma_core_dsyssq(plasma_enum_t uplo, int n, const double *A, int lda, double *scale, double *sumsq) { int ione = 1; if (uplo == PlasmaUpper) { for (int j = 1; j < n; j++) // TODO: Inline this operation. LAPACK_dlassq(&j, &A[lda*j], &ione, scale, sumsq); } else { // PlasmaLower for (int j = 0; j < n-1; j++) { int len = n-j-1; // TODO: Inline this operation. LAPACK_dlassq(&len, &A[lda*j+j+1], &ione, scale, sumsq); } } *sumsq *= 2.0; for (int i = 0; i < n; i++) { // diagonal is complex, don't ignore complex part double absa = fabs(A[lda*i+i]); if (absa != 0.0) { // != propagates nan if (*scale < absa) { *sumsq = 1.0 + *sumsq*((*scale/absa)*(*scale/absa)); *scale = absa; } else { *sumsq = *sumsq + ((absa/(*scale))*(absa/(*scale))); } } } } /******************************************************************************/ void plasma_core_omp_dsyssq(plasma_enum_t uplo, int n, const double *A, int lda, double *scale, double *sumsq, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:A[0:lda*n]) \ depend(out:scale[0:n]) \ depend(out:sumsq[0:n]) { if (sequence->status == PlasmaSuccess) { *scale = 0.0; *sumsq = 1.0; plasma_core_dsyssq(uplo, n, A, lda, scale, sumsq); } } } /******************************************************************************/ void plasma_core_omp_dsyssq_aux(int m, int n, const double *scale, const double *sumsq, double *value, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:scale[0:n]) \ depend(in:sumsq[0:n]) \ depend(out:value[0:1]) { if (sequence->status == PlasmaSuccess) { double scl = 0.0; double sum = 1.0; for (int j = 0; j < n; j++) { for (int i = j+1; i < n; i++) { int idx = m*j+i; if (scl < scale[idx]) { sum = sumsq[idx] + sum*((scl/scale[idx])*(scl/scale[idx])); scl = scale[idx]; } else { sum = sum + sumsq[idx]*((scale[idx]/scl)*(scale[idx]/scl)); } } } sum = 2.0*sum; for (int j = 0; j < n; j++) { int idx = m*j+j; if (scl < scale[idx]) { sum = sumsq[idx] + sum*((scl/scale[idx])*(scl/scale[idx])); scl = scale[idx]; } else { sum = sum + sumsq[idx]*((scale[idx]/scl)*(scale[idx]/scl)); } } *value = scl*sqrt(sum); } } }
GB_binop__ne_fc32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__ne_fc32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__ne_fc32) // A.*B function (eWiseMult): GB (_AemultB_03__ne_fc32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_fc32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__ne_fc32) // C+=b function (dense accum): GB (_Cdense_accumb__ne_fc32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_fc32) // C=scalar+B GB (_bind1st__ne_fc32) // C=scalar+B' GB (_bind1st_tran__ne_fc32) // C=A+scalar GB (_bind2nd__ne_fc32) // C=A'+scalar GB (_bind2nd_tran__ne_fc32) // C type: bool // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_ne (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = (crealf (Ax [pA]) != 0) || (cimagf (Ax [pA]) != 0) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = (crealf (Bx [pB]) != 0) || (cimagf (Bx [pB]) != 0) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_FC32_ne (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_NE || GxB_NO_FC32 || GxB_NO_NE_FC32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__ne_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__ne_fc32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ne_fc32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((node)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ne_fc32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__ne_fc32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__ne_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__ne_fc32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__ne_fc32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__ne_fc32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_ne (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ne_fc32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_ne (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_ne (x, aij) ; \ } GrB_Info GB (_bind1st_tran__ne_fc32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_ne (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__ne_fc32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
CMT2TT.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <float.h> #define COMPEARTH_PRIVATE_CROSS3 1 #define COMPEARTH_PRIVATE_NORM3 1 #define COMPEARTH_PRIVATE_DOT3 1 #define COMPEARTH_PRIVATE_WRAP360 1 #include "compearth.h" #ifdef COMPEARTH_USE_MKL #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wreserved-id-macro" #pragma clang diagnostic ignored "-Wstrict-prototypes" #endif #include <mkl_cblas.h> #ifdef __clang__ #pragma clang diagnostic pop #endif #else #include <cblas.h> #endif //#define MAXMT 64 static void setZero(const int nmt, const double tol, double *__restrict__ X); static void faultVec2Ang(const double *__restrict__ S, const double *__restrict__ N, double *theta, double *sigma, double *kappa, double *__restrict__ K, int *ierr); static int pickP1(const double thetaA, const double sigmaA, const double kappaA, const double thetaB, const double sigmaB, const double kappaB, const double tol, const int p1, const int p2); /*! * @brief Converts a moment tensor to six parameters of Tape and Tape 2012. * The reverse program is TT2CMT.c * * @param[in] nmt Number of moment tensors. * @param[in] Min [6 x nmt] array of moment tensors in CMT * convention (i.e. UP-SOUTH-EAST). M is packed: * \f$ * M = \{ M_{rr}, M_{\theta \theta}, M_{\phi \phi} * M_{r \theta}, M_{r \phi}, M_{\theta \phi} \} * \f$. * The leading dimension is 6. * @param[in] ldisplay If true then display the results. \n * Otherwise, this routine will be quiet unless * an error is encountered. * * @param[out] gamma Angle from DC meridian to MT point. * Note that \f$ \gamma \in [-30, 30] \f$. * This is an array of dimension [nmt]. * @param[out] delta Angle from deviatoric plane to MT point. * Note that \f$ \delta \in [-90, 90] \f$. * This is an array of dimension [nmt]. * @param[out] M0 Seismic moment in N-m. This is an array of * dimension [nmt]. * @param[out] kappa Strike angle \f$ \kappa \in [0,360] \f$. * This is an array of dimension [nmt]. * @param[out] theta Dip angle \f$ \theta \in [0,90] \f$. * This is an array of dimension [nmt]. * @param[out] sigma Slip (or rake) angle \f$ \sigma \in [-90,90] \f$. * This is an array of dimension [nmt]. * @param[out] K If K is not NULL then it is the strike vector * (SOUTH-EAST-UP). In this case K is an array * of dimension [3 x nmt] with leading dimension 3. * @param[out] N If N is not NULL then it is the normal vector * (SOUTH-EAST-UP). In this case N is an array * of dimension [3 x nmt] with leading dimension 3. * @param[out] S If S Is not NULL then it is the slip vector * (SOUTH-EAST-UP). In this case S is an array * of dimension [3 x nmt] with leading dimension 3. * @param[out] thetadc If thetadc is not NULL then it is angle between * the moment tensor and the double couple where * \f$ \theta_{DC} \in [0,90] \f$. * In this case thetadc is an array of dimension [nmt]. * @param[out] lam If lam is not NULL then these are the eigenvalues * corresponding to the moment tensor. In this * case lam is an array of dimension [3 x nmt] * with leading dimension 3. * @param[out] U If U is not NULL then this is the basis in * SOUTH-EAST-UP for the moment tensor. In this * case U an array of dimension [3 x 3 x nmt] with * leading dimension 9 and the understanding that * each 3 x 3 matrix is in column major format. * * @result 0 indicates success. * * @author Carl Tape and translated to C by Ben Baker * * @date July 2017 * * @copyright MIT * */ int compearth_CMT2TT(const int nmt, const double *__restrict__ Min, const bool ldisplay, double *__restrict__ gamma, double *__restrict__ delta, double *__restrict__ M0, double *__restrict__ kappa, double *__restrict__ theta, double *__restrict__ sigma, double *__restrict__ K, double *__restrict__ N, double *__restrict__ S, double *__restrict__ thetadc, double *__restrict__ lam, double *__restrict__ U) { double *lamdev, *lamiso, Vwork[9], Yrot[9], M[6], Sloc[12], Kloc[12], Nloc[12], kappaL[4], sigmaL[4], thetaL[4]; double *thetadcWork; double Uwork[9*CE_CHUNKSIZE] __attribute__((aligned(64))); double lamWork[3*CE_CHUNKSIZE] __attribute__((aligned(64))); double Nwork[3*CE_CHUNKSIZE] __attribute__((aligned(64))); double Swork[3*CE_CHUNKSIZE] __attribute__((aligned(64))); //double lamSpace[3*MAXMT]; //double uSpace[9*MAXMT]; bool lwantLam, lwantK, lwantN, lwantS, lwantU; int itemp[4], ierr, ierrAll, match, imt, j, jmt, nmtLoc, nMatch; const int isort = 1; const double rotAngle = 45.0; const double tol = 1.e-6; ierr = 0; if (nmt < 1 || Min == NULL || gamma == NULL || delta == NULL || M0 == NULL || kappa == NULL || theta == NULL || sigma == NULL) { if (nmt < 1){fprintf(stderr, "%s: No moment tensors\n", __func__);} if (Min == NULL){fprintf(stderr, "%s: Min is NULL\n", __func__);} if (gamma == NULL){fprintf(stderr, "%s: gamma is NULL\n", __func__);} if (delta == NULL){fprintf(stderr, "%s: delta is NULL\n", __func__);} if (M0 == NULL){fprintf(stderr, "%s: M0 is NULL\n", __func__);} if (kappa == NULL){fprintf(stderr, "%s: kappa is NULL\n", __func__);} if (theta == NULL){fprintf(stderr, "%s: theta is NULL\n", __func__);} if (sigma == NULL){fprintf(stderr, "%s: sigma is NULL\n", __func__);} return -1; } // Determine if eigenvalue/eigenvector decomposition is requested lwantLam = false; if (lam != NULL){lwantLam = true;} lwantU = false; if (U != NULL){lwantU = true;} // Determine the desired fault vectors lwantK = false; lwantN = false; lwantS = false; if (K != NULL){lwantK = true;} if (N != NULL){lwantN = true;} if (S != NULL){lwantS = true;} // Loop on moment tensor chunks for (jmt=0; jmt<nmt; jmt=jmt+CE_CHUNKSIZE) { nmtLoc = MIN(CE_CHUNKSIZE, nmt - jmt); // This is the numerically expensive part b/c of eigendecomposition ierrAll = 0; for (imt=0; imt<nmtLoc; imt++) { // KEY: Convert M into another basis. // YOU MUST ALSO CHANGE north AND zenith IN fault2vecang BELOW // --> U will be with respect to this basis (from CMTdecom.m) // ierr = compearth_convertMT(1, CE_USE, CE_NWU, &Min[6*imt], M); ierr = compearth_convertMT(1, CE_USE, CE_SEU, &Min[6*(jmt+imt)], M); if (ierr != 0) { fprintf(stderr, "%s: Error switching basis\n", __func__); ierrAll = ierrAll + 1; //break; } // PART 1: moment tensor source type (or pattern) // Decompose moment tensor into eigenvalues + basis (M = U*lam*U') // NOTE: ordering of eigenvalues is important. ierr = compearth_CMTdecom(1, M, isort, &lamWork[3*imt], &Uwork[9*imt]); if (ierr != 0) { fprintf(stderr, "%s: Error decomposing CMT\n", __func__); ierrAll = ierrAll + 1; //break; } } if (ierrAll != 0) { fprintf(stderr, "%s: Error during eigendecomposition\n", __func__); ierr = 1; goto ERROR; } // Compute the lune coordinates and magnitude from eigenvalues lamdev = NULL; lamiso = NULL; thetadcWork = NULL; if (thetadc != NULL){thetadcWork = &thetadc[jmt];} ierr = compearth_lam2lune(nmtLoc, lamWork, &gamma[jmt], &delta[jmt], &M0[jmt], thetadcWork, lamdev, lamiso); // Part 2: moment tensor orientation; TT2012, Section 6.3 ierr = compearth_eulerUtil_rotmat(1, &rotAngle, 2, Yrot); if (ierr != 0) { fprintf(stderr, "%s: Error computing rotation matrix\n", __func__); return -1; } // Compute candidate fault vectors for (imt=0; imt<nmtLoc; imt++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, 3, 3, 3, 1.0, &Uwork[9*imt], 3, Yrot, 3, 0.0, Vwork, 3); // V = U*Yrot (TT2012, p. 487) Swork[3*imt+0] = Vwork[0]; Swork[3*imt+1] = Vwork[1]; Swork[3*imt+2] = Vwork[2]; Nwork[3*imt+0] = Vwork[6]; Nwork[3*imt+1] = Vwork[7]; Nwork[3*imt+2] = Vwork[8]; } // Save lambda and U if (lwantLam){cblas_dcopy(3*nmtLoc, lamWork, 1, &lam[3*jmt], 1);} if (lwantU){cblas_dcopy(9*nmtLoc, Uwork, 1, &U[9*jmt], 1);} // Reassign ~0 elements to 0; ~1 elements to 1, and ~-1 elements to -1. setZero(nmtLoc, tol, Swork); setZero(nmtLoc, tol, Nwork); // Compute fault angles for four possible combinations (TT2012 Fig 15) for (imt=0; imt<nmtLoc; imt++) { for (j=0; j<3; j++) { Sloc[3*0+j] = Swork[3*imt+j]; Nloc[3*0+j] = Nwork[3*imt+j]; Sloc[3*1+j] =-Swork[3*imt+j]; Nloc[3*1+j] =-Nwork[3*imt+j]; Sloc[3*2+j] = Nwork[3*imt+j]; Nloc[3*2+j] = Swork[3*imt+j]; Sloc[3*3+j] =-Nwork[3*imt+j]; Nloc[3*3+j] =-Swork[3*imt+j]; } faultVec2Ang(&Sloc[0], &Nloc[0], &thetaL[0], &sigmaL[0], &kappaL[0], &Kloc[0], &ierr); faultVec2Ang(&Sloc[3], &Nloc[3], &thetaL[1], &sigmaL[1], &kappaL[1], &Kloc[3], &ierr); faultVec2Ang(&Sloc[6], &Nloc[6], &thetaL[2], &sigmaL[2], &kappaL[2], &Kloc[6], &ierr); faultVec2Ang(&Sloc[9], &Nloc[9], &thetaL[3], &sigmaL[3], &kappaL[3], &Kloc[9], &ierr); // There are four combinations of N and S that represent a double // copule moment tensor, as shown in Figure 15 of TT2012. // From these four combinations, there are two possible fault // planes. We want to isoate the combination that is within the // boundingregion shown in Figures 16 and B1. memset(itemp, 0, 4*sizeof(int)); nMatch = 0; for (j=0; j<4; j++) { if (thetaL[j] <= 90.0 + tol && fabs(sigmaL[j]) <= 90.0 + tol) { itemp[nMatch] = j; //bmatch[j] = true; nMatch = nMatch + 1; } } if (nMatch == 1) { match = itemp[0]; } else if (nMatch == 2) { match = pickP1(thetaL[itemp[0]], sigmaL[itemp[0]], kappaL[itemp[0]], thetaL[itemp[1]], sigmaL[itemp[1]], kappaL[itemp[1]], tol, itemp[0], itemp[1]); if (match < 0) { fprintf(stderr, "%s: Failed to pick a fault plane\n", __func__); ierr = 1; goto ERROR; } } else if (nMatch == 3) { fprintf(stdout, "%s: Warning mt on bdry of orientation domain 3 candidates\n", __func__); fprintf(stdout, "%s: thetas: %e %e %e\n", __func__, thetaL[0], thetaL[1], thetaL[2]); fprintf(stdout, "%s: sigmas: %e %e %e\n", __func__, sigmaL[0], sigmaL[1], sigmaL[2]); fprintf(stdout, "%s: kappas: %e %e %e\n", __func__, kappaL[0], kappaL[1], kappaL[2]); // Just take the first one match = itemp[0]; } else if (nMatch == 4) { fprintf(stderr, "%s: Error not yet programmed\n", __func__); ierr = 1; goto ERROR; } else { fprintf(stderr, "%s: Error no match\n", __func__); ierr = 1; goto ERROR; } // Select the angle kappa[jmt+imt] = kappaL[match]; sigma[jmt+imt] = sigmaL[match]; theta[jmt+imt] = thetaL[match]; // Fault vectors if (lwantK) { for (j=0; j<3; j++){K[3*(jmt+imt)+j] = Kloc[3*match+j];} } if (lwantN) { for (j=0; j<3; j++){N[3*(jmt+imt)+j] = Nloc[3*match+j];} } if (lwantS) { for (j=0; j<3; j++){S[3*(jmt+imt)+j] = Sloc[3*match+j];} } } } // Loop on moment tensor chunks if (ldisplay) { fprintf(stderr, "%s: ldisply not yet supported\n", __func__); } ERROR:; /* Uwork = NULL; lamWork = NULL; */ return ierr; } /*! * @brief Returns fault angles in degrees. Assumes input vectors are in * the South-East-Up basis. * * @author Carl Tape and converted to C by Ben Baker * * @copyright MIT * */ static void faultVec2Ang(const double *__restrict__ S, const double *__restrict__ N, double *theta, double *sigma, double *kappa, double *__restrict__ K, int *ierr) { double v[3], costh, vnorm; int ierr1; const double deg = 180.0/M_PI; // South-East-Up (as In TT2012) const double zenith[3] = {0, 0, 1}; const double negZenith[3] = {0, 0, -1}; const double north[3] = {-1, 0, 0}; *ierr = 0; *kappa = (double) NAN; *theta = (double) NAN; *sigma = (double) NAN; // Strike vector from TT2012, Eqn 29 cross3(zenith, N, v); vnorm = norm3(v); if (vnorm < DBL_EPSILON) //== 0.0) { fprintf(stderr, "%s: Horizontal fault -- strike vector is same as slip vector\n", __func__); K[0] = S[0]; K[1] = S[1]; K[2] = S[2]; } else { K[0] = v[0]/vnorm; K[1] = v[1]/vnorm; K[2] = v[2]/vnorm; } // Figure 14 *kappa = compearth_eulerUtil_fangleSigned(3, north, K, negZenith, &ierr1); if (ierr1 != 0){*ierr = *ierr + 1;} *kappa = wrap360(*kappa); // Figure 14 costh = dot3(N, zenith); *theta = acos(costh)*deg; // Figure 14 *sigma = compearth_eulerUtil_fangleSigned(3, K, S, N, &ierr1); if (ierr1 != 0){*ierr = *ierr + 1;} return; } static void setZero(const int nmt, const double tol, double *__restrict__ X) { double dmax; int i, idmax; // Compute the largest element of abs(X) idmax = (int) cblas_idamax(3*nmt, X, 1); dmax = X[idmax]; // Elements near zero whilst trying to eliminate round-off errors #pragma omp simd for (i=0; i<3*nmt; i++) { if (fabs(X[i]/dmax) < tol){X[i] = 0.0;} } #pragma omp simd for (i=0; i<3*nmt; i++) { if (fabs(X[i] - 1.0) < tol){X[i] =-1.0;} } #pragma omp simd for (i=0; i<3*nmt; i++) { if (fabs(X[i] + 1.0) < tol){X[i] = 1.0;} } return; } static int pickP1(const double thetaA, const double sigmaA, const double kappaA, const double thetaB, const double sigmaB, const double kappaB, const double tol, const int p1, const int p2) { int ipick; ipick =-1; if (fabs(thetaA - 90.0) < tol) { if (kappaA < 180.0){ipick = p1;} if (kappaB < 180.0){ipick = p2;} return ipick; } if (fabs(sigmaA - 90.0) < tol) { if (kappaA < 180.0){ipick = p1;} if (kappaB < 180.0){ipick = p2;} return ipick; } if (fabs(sigmaA + 90.0) < tol) { if (kappaA < 180.0){ipick = p1;} if (kappaB < 180.0){ipick = p2;} return ipick; } fprintf(stderr, "%s: Error no selection criterion was met\n", __func__); fprintf(stderr, "thetaA,sigmaA,kappaA=%f,%f,%f\n", thetaA, sigmaA, kappaA); fprintf(stderr, "thetaB,sigmaB,kappaB=%f,%f,%f\n", thetaB, sigmaB, kappaB); return ipick; }
GB_binop__rdiv_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__rdiv_fp32 // A.*B function (eWiseMult): GB_AemultB__rdiv_fp32 // A*D function (colscale): GB_AxD__rdiv_fp32 // D*A function (rowscale): GB_DxB__rdiv_fp32 // C+=B function (dense accum): GB_Cdense_accumB__rdiv_fp32 // C+=b function (dense accum): GB_Cdense_accumb__rdiv_fp32 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_fp32 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_fp32 // C=scalar+B GB_bind1st__rdiv_fp32 // C=scalar+B' GB_bind1st_tran__rdiv_fp32 // C=A+scalar GB_bind2nd__rdiv_fp32 // C=A'+scalar GB_bind2nd_tran__rdiv_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = (bij / aij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (y / x) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_FP32 || GxB_NO_RDIV_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__rdiv_fp32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *GB_RESTRICT Cx = (float *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__rdiv_fp32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float bij = Bx [p] ; Cx [p] = (bij / x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rdiv_fp32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; Cx [p] = (y / aij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (aij / x) ; \ } GrB_Info GB_bind1st_tran__rdiv_fp32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = (y / aij) ; \ } GrB_Info GB_bind2nd_tran__rdiv_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
parallel_linearSys_pipeline.c
#include <stdio.h> #include <omp.h> #include <stdlib.h> #include <string.h> #include <time.h> void printMatrix(double** matrix, int n, FILE *fp) { if (fp != NULL) { for (int i = 0; i < n; i++) { for (int j = 0; j < n+1; j++) { fprintf(fp, "%f, ",matrix[i][j]); } fprintf(fp, "\n"); } fprintf(fp, "\n"); } else { for (int i = 0; i < n; i++) { for (int j = 0; j < n+1; j++) { printf("%f, ",matrix[i][j]); } printf("\n"); } printf("\n"); } } void printSolutions(double** matrix, int n, FILE *fp) { if (fp != NULL) { for (int i = 0; i < n; i++) { fprintf(fp, "%f, ",matrix[i][n]); fprintf(fp, "\n"); } fprintf(fp, "\n"); } else { for (int i = 0; i < n; i++) { printf("%f, ",matrix[i][n]); printf("\n"); } printf("\n"); } } struct record_s { double val; long prod; struct record_s* next; }; struct buf_list { struct record_s* head_p; struct record_s* tail_p; }; struct buf_list *buff; int *producers_done; struct record_s* Dequeue(long thread) { struct record_s* rec_p;// = malloc(sizeof(*rec_p)); if (buff[thread].head_p == NULL) { return NULL; } else if (buff[thread].head_p == buff[thread].tail_p) { rec_p = buff[thread].head_p; buff[thread].head_p = buff[thread].tail_p = NULL; } else { rec_p = buff[thread].head_p; buff[thread].head_p = buff[thread].head_p->next; } return rec_p; } double Get(long thread) { struct record_s* rec_p;// = malloc(sizeof(*rec_p)); double data; while (producers_done[thread] < 1 || buff[thread].head_p != NULL) { #pragma omp critical (queue) { rec_p = Dequeue(thread); } if (rec_p != NULL) { #pragma omp critical(done) { producers_done[thread] -= 1; } data = rec_p -> val; free(rec_p); return data; } } } struct record_s* Create_record(long thread, double data) { struct record_s* rec_p = malloc(sizeof(*rec_p)); rec_p->next=NULL; rec_p->prod=thread; rec_p->val=data; return rec_p; } void Enqueue(long thread, struct record_s* rec_p) { if (buff[thread].tail_p == NULL) { buff[thread].head_p = rec_p; } else { buff[thread].tail_p->next = rec_p; } buff[thread].tail_p = rec_p; } void Put(long thread, double data) { struct record_s *rec_p = malloc(sizeof(*rec_p)); rec_p->next=NULL; rec_p->prod=thread; rec_p->val=data; #pragma omp critical(queue) { Enqueue(thread, rec_p); } #pragma omp critical(done) { producers_done[thread]++; } } void paralle_gaussian_elimination(double **matrix, int n, int p) { int blockSize = n/p; for (int offset = 0; offset <= n - blockSize; offset+=blockSize) { int i,j,k,row,count; omp_set_num_threads(p); #pragma omp parallel private(i,j,k,row,count) shared(matrix) { long threadID = omp_get_thread_num(); if (threadID != 0) { for (count = 0; count < blockSize; count++) { row = Get(threadID); Put(threadID+1, row); for (i = threadID * blockSize; i < threadID * blockSize + blockSize; i++) { if (row < i) { matrix[i][row] = matrix[i][row]/matrix[row][row]; for (j = row+1; j < n+1; j++) { matrix[i][j] = matrix[i][j] - matrix[i][row]*matrix[row][j]; } } } } // thread 0 } else { for (count = 0; count < blockSize; count++) { long k = count + offset; Put(threadID+1,k); for (i = k+1; i < blockSize; i++) { for (int j = k+1; j < n+1; j++) { matrix[i][j] -= (matrix[i][k] / matrix[k][k]) * matrix[k][j]; } } } } } } } void parallel_backward_substitution(double **matrix, int n) { for (int i = n - 1; i >= 0; i--) { #pragma omp for schedule(static) for (int j = n - 1; j > i; j--) { matrix[i][n] -= matrix[i][j] * matrix[j][n]; } #pragma omp single matrix[i][n] = matrix[i][n] / matrix[i][i]; } } void main(int argc, char *argv[]) { int i, j, n, threads; char *input_file, *output_file; FILE *fp; clock_t start, end; input_file = argv[1]; output_file = argv[2]; int p = atoi(argv[3]); if (input_file == NULL) fprintf( stderr, "Please enter input file" ); if (output_file == NULL) fprintf( stderr, "Please enter output file" ); fp = fopen(input_file, "r"); fscanf(fp, "%i", &(n)); printf("n is %i \n", n); double** matrix = (double**)malloc(n*sizeof(double*)); for (i = 0; i<n; i++){ matrix[i] = (double*)malloc((n+1)*sizeof(double)); } for (i = 0; i < n; ++i) { for (j = 0;j < n+1; ++j) { fscanf(fp, "%lf", &matrix[i][j]); } } fclose(fp); buff = (struct buf_list*) malloc((n+1)*sizeof(struct buf_list)); producers_done = malloc((n+1)*sizeof(int)); for (int i = 0; i < n + 1; i++) { buff[i].head_p = NULL; buff[i].tail_p = NULL; producers_done[i] = 0; } start = clock(); paralle_gaussian_elimination(matrix,n,p); parallel_backward_substitution(matrix,n); end = clock(); double runtime = (double) (end - start) / CLOCKS_PER_SEC; printf("parallel linear time (pipeline) is %lf: \r\n", runtime); fp = fopen(output_file, "w"); printSolutions(matrix,n,fp); fclose(fp); free(matrix); free(buff); free(producers_done); }
if-3.c
/* { dg-do compile } */ /* { dg-additional-options "-O2" } */ #define N 1024 void foo (int *x, int *y, int *z, int a) { int i; #pragma omp simd if (simd: a > 2) aligned (x, y, z : 16) for (i = 0; i < N; i++) x[i] = y[i] + z[i]; }
core_math.h
/* * Copyright (c) 2020 Georgios Damaskinos * All rights reserved. * @author Georgios Damaskinos <georgios.damaskinos@gmail.com> * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // == mojo ==================================================================== // // Copyright (c) gnawice@gnawice.com. All rights reserved. // See LICENSE in root folder // // 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. // // ============================================================================ // core_math.h: defines matrix class and math functions // ==================================================================== mojo == #pragma once #include <math.h> #include <string.h> #include <string> #include <map> #include <cstdlib> #include <random> #include <algorithm> #ifdef MOJO_ENABLE_NEON #include <arm_neon.h> #endif namespace mojo { enum pad_type { zero = 0, edge = 1, median_edge = 2 }; inline float dot(const float *x1, const float *x2, const int size) { switch (size) { case 1: return x1[0] * x2[0]; case 2: return x1[0] * x2[0] + x1[1] * x2[1]; case 3: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2]; case 4: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3]; case 5: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3] + x1[4] * x2[4]; default: float v = 0; for (int i = 0; i<size; i++) v += x1[i] * x2[i]; return v; }; } inline float unwrap_2d_dot(const float *x1, const float *x2, const int size, int stride1, int stride2) { float v=0; for(int j=0; j<size; j++) v+= dot(&x1[stride1*j],&x2[stride2*j],size); return v; } // second item is rotated 180 (this is a convolution) inline float dot_rot180(const float *x1, const float *x2, const int size) { switch(size) { case 1: return x1[0]*x2[0]; case 2: return x1[0]*x2[1]+x1[1]*x2[0]; case 3: return x1[0]*x2[2]+x1[1]*x2[1]+x1[2]*x2[0]; case 4: return x1[0]*x2[3]+x1[1]*x2[2]+x1[2]*x2[1]+x1[3]*x2[0]; case 5: return x1[0]*x2[4]+x1[1]*x2[3]+x1[2]*x2[2]+x1[3]*x2[1]+x1[4]*x2[0]; default: float v=0; for(int i=0; i<size; i++) v+=x1[i]*x2[size-i-1]; return v; }; } inline float unwrap_2d_dot_rot180(const float *x1, const float *x2, const int size, int stride1, int stride2) { float v=0; for(int j=0; j<size; j++) { v+= dot_rot180(&x1[stride1*j],&x2[stride2*(size-j-1)],size); } return v; } inline void unwrap_aligned_NxN(const int N, float *aligned_out, const float *in, const int in_size, const int stride = 1) { const int node_size = (in_size - N) + 1; int c1 = 0; int off = 0; const int inc_off = N*N*8; for (int j = 0; j < node_size; j += 1) // intput h { for (int i = 0; i < node_size; i += 1) // intput w { const float *tn = in + j*in_size + i; if(N==5) { for (int k = 0; k < 5; k++) { aligned_out[c1 + 0 + k * 40 + off] = tn[0 + 0 + in_size*k]; aligned_out[c1 + 8 + k * 40 + off] = tn[0 + 1 + in_size*k]; aligned_out[c1 + 16 + k * 40 + off] = tn[0 + 2 + in_size*k]; aligned_out[c1 + 24 + k * 40 + off] = tn[0 + 3 + in_size*k]; aligned_out[c1 + 32 + k * 40 + off] = tn[0 + 4 + in_size*k]; } } else if(N==3) { aligned_out[c1 + off] = tn[0]; aligned_out[c1 + 8 + off] = tn[0 + 1]; aligned_out[c1 + 16 + off] = tn[0 + 2]; aligned_out[c1 + 24 + off] = tn[0 + in_size]; aligned_out[c1 + 32 + off] = tn[0 + 1 + in_size]; aligned_out[c1 + 40 + off] = tn[0 + 2 + in_size]; aligned_out[c1 + 48 + off] = tn[0 + 2 * in_size]; aligned_out[c1 + 56 + off] = tn[0 + 1 + 2 * in_size]; aligned_out[c1 + 64 + off] = tn[0 + 2 + 2 * in_size]; } else { int cnt=0; for (int k = 0; k < N; k++) { for (int m = 0; m < N; m++) { aligned_out[c1 + cnt*8 + off] = tn[0 + m + in_size*k]; cnt++; } } } off++; if (off > 7) { off = 0; c1 += inc_off; } } } } inline void dotsum_unwrapped_NxN(const int N, const float *im, const float *filter_ptr, float *out, const int outsize) { const int NN=N*N; for (int j = 0; j < outsize; j += 8) { float *c = out+j; for(int i=0; i<NN; i++) { const float f = filter_ptr[i]; c[0]+=im[0]*f; c[1]+=im[1]*f; c[2]+=im[2]*f; c[3]+=im[3]*f; c[4]+=im[4]*f; c[5]+=im[5]*f; c[6]+=im[6]*f; c[7]+=im[7]*f; im+=8; } } } #ifdef MOJO_AVX inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 32; } _mm256_zeroupper(); } inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); for (int j = 0; j < outsize; j += 8)//stride) // intput w { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 72; } _mm256_zeroupper(); } inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]); const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]); const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]); const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]); for (int j = 0; j < outsize; j += 8)//stride) // intput w { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 128; } _mm256_zeroupper(); } inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]); const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]); const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]); const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]); const __m256 f16 = _mm256_broadcast_ss(&filter_ptr[16]); const __m256 f17 = _mm256_broadcast_ss(&filter_ptr[17]); const __m256 f18 = _mm256_broadcast_ss(&filter_ptr[18]); const __m256 f19 = _mm256_broadcast_ss(&filter_ptr[19]); const __m256 f20 = _mm256_broadcast_ss(&filter_ptr[20]); const __m256 f21 = _mm256_broadcast_ss(&filter_ptr[21]); const __m256 f22 = _mm256_broadcast_ss(&filter_ptr[22]); const __m256 f23 = _mm256_broadcast_ss(&filter_ptr[23]); const __m256 f24 = _mm256_broadcast_ss(&filter_ptr[24]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 128); c1 = _mm256_mul_ps(a, f16); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 136); c1 = _mm256_mul_ps(a, f17); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 144); c1 = _mm256_mul_ps(a, f18); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 152); c1 = _mm256_mul_ps(a, f19); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 160); c1 = _mm256_mul_ps(a, f20); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 168); c1 = _mm256_mul_ps(a, f21); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 176); c1 = _mm256_mul_ps(a, f22); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 184); c1 = _mm256_mul_ps(a, f23); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 192); c1 = _mm256_mul_ps(a, f24); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 200; } _mm256_zeroupper(); } inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); __m256 f[49];//=new __m256(s); for(int i=0; i<49; i++) f[i]= _mm256_broadcast_ss(&filter_ptr[i]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f[0]); for(int i=1; i<49;i++) { a = _mm256_load_ps(_img + 8*i); c1 = _mm256_mul_ps(a, f[i]); c0 = _mm256_add_ps(c0, c1); } a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 49*8; } _mm256_zeroupper(); //delete [] f; } #else // no AVX inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(2, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(3, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(4, _img, filter_ptr, out, outsize); } inline int64_t get_cycles() { uint32_t pmccntr; uint32_t pmuseren; uint32_t pmcntenset; // Read the user mode perf monitor counter access permissions. asm volatile("mrc p15, 0, %0, c9, c14, 0" : "=r"(pmuseren)); if (pmuseren & 1) { // Allows reading perfmon counters for user mode code. asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r"(pmcntenset)); if (pmcntenset & 0x80000000ul) { // Is it counting? asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r"(pmccntr)); // The counter is set up to count every 64th cycle //__android_log_print(ANDROID_LOG_DEBUG, "INFO", "cycles %d", pmccntr); return (int64_t) pmccntr; // Should optimize to << 6 } return -1; } return -2; } #ifdef MOJO_ENABLE_NEON #define MOJO_Conv2dNeonK5x5SnLoadCalc4 \ /* load filter (4 outch x 1 height x 4 width) */ \ float32x4_t vf00, vf10, vf20, vf30; \ float32x2_t vf01, vf11, vf21, vf31; \ vf00 = vld1q_f32(filter_ptr0); \ vf01 = vld1_f32(filter_ptr0 + 3); \ vf10 = vld1q_f32(filter_ptr1); \ vf11 = vld1_f32(filter_ptr1 + 3); \ vf20 = vld1q_f32(filter_ptr2); \ vf21 = vld1_f32(filter_ptr2 + 3); \ vf30 = vld1q_f32(filter_ptr3); \ vf31 = vld1_f32(filter_ptr3 + 3); \ \ /* outch 0 */ \ vo0 = vmlaq_lane_f32(vo0, vi0, vget_low_f32(vf00), 0); \ vo0 = vmlaq_lane_f32(vo0, vi1, vget_low_f32(vf00), 1); \ vo0 = vmlaq_lane_f32(vo0, vi2, vget_high_f32(vf00), 0); \ vo0 = vmlaq_lane_f32(vo0, vi3, vget_high_f32(vf00), 1); \ vo0 = vmlaq_lane_f32(vo0, vi4, vf01, 1); \ \ /* outch 1 */ \ vo1 = vmlaq_lane_f32(vo1, vi0, vget_low_f32(vf10), 0); \ vo1 = vmlaq_lane_f32(vo1, vi1, vget_low_f32(vf10), 1); \ vo1 = vmlaq_lane_f32(vo1, vi2, vget_high_f32(vf10), 0); \ vo1 = vmlaq_lane_f32(vo1, vi3, vget_high_f32(vf10), 1); \ vo1 = vmlaq_lane_f32(vo1, vi4, vf11, 1); \ \ /* outch 2 */ \ vo2 = vmlaq_lane_f32(vo2, vi0, vget_low_f32(vf20), 0); \ vo2 = vmlaq_lane_f32(vo2, vi1, vget_low_f32(vf20), 1); \ vo2 = vmlaq_lane_f32(vo2, vi2, vget_high_f32(vf20), 0); \ vo2 = vmlaq_lane_f32(vo2, vi3, vget_high_f32(vf20), 1); \ vo2 = vmlaq_lane_f32(vo2, vi4, vf21, 1); \ \ /* outch 3 */ \ vo3 = vmlaq_lane_f32(vo3, vi0, vget_low_f32(vf30), 0); \ vo3 = vmlaq_lane_f32(vo3, vi1, vget_low_f32(vf30), 1); \ vo3 = vmlaq_lane_f32(vo3, vi2, vget_high_f32(vf30), 0); \ vo3 = vmlaq_lane_f32(vo3, vi3, vget_high_f32(vf30), 1); \ vo3 = vmlaq_lane_f32(vo3, vi4, vf31, 1); inline void dotsum_neon_5x5_4maps(const float *_img, const float *filter_ptr, float *out, const int map_stride, const int in_size, const int out_size) { float *out_ptr0_base = out; float *out_ptr1_base = out + map_stride; float *out_ptr2_base = out + 2 * map_stride; float *out_ptr3_base = out + 3 * map_stride; const float *filter_ptr0 = filter_ptr; const float *filter_ptr1 = filter_ptr + 25; // kernel_size = 25 const float *filter_ptr2 = filter_ptr + 2 * 25; const float *filter_ptr3 = filter_ptr + 3 * 25; for (int h = 0; h < out_size; ++h) { for (int w = 0; w + 3 < out_size; w += 4) { // input offset int in_offset = h * in_size + w; // output (4 outch x 1 height x 4 width): vo_outch_height float32x4_t vo0, vo1, vo2, vo3; // load output int out_offset = h * out_size + w; vo0 = vld1q_f32(out_ptr0_base + out_offset); vo1 = vld1q_f32(out_ptr1_base + out_offset); vo2 = vld1q_f32(out_ptr2_base + out_offset); vo3 = vld1q_f32(out_ptr3_base + out_offset); for (int r = 0; r < 5; ++r) { // input (3 slide) float32x4_t vi0, vi1, vi2, vi3, vi4; // load input vi0 = vld1q_f32(_img + in_offset); vi4 = vld1q_f32(_img + in_offset + 4); vi1 = vextq_f32(vi0, vi4, 1); vi2 = vextq_f32(vi0, vi4, 2); vi3 = vextq_f32(vi0, vi4, 3); MOJO_Conv2dNeonK5x5SnLoadCalc4; in_offset += in_size; filter_ptr0 += 5; filter_ptr1 += 5; filter_ptr2 += 5; filter_ptr3 += 5; } // r vst1q_f32(out_ptr0_base + out_offset, vo0); vst1q_f32(out_ptr1_base + out_offset, vo1); vst1q_f32(out_ptr2_base + out_offset, vo2); vst1q_f32(out_ptr3_base + out_offset, vo3); filter_ptr0 -= 25; filter_ptr1 -= 25; filter_ptr2 -= 25; filter_ptr3 -= 25; } // w } // h } inline void dotsum_neon_5x5(const float *_img, const float *filter_ptr, float *out, const int in_size, const int out_size) { for (int h = 0; h < out_size; ++h) { for (int w = 0; w + 3 < out_size; w += 4) { // input offset int in_offset = h * in_size + w; // output (1 outch x 1 height x 4 width): vo_outch_height float32x4_t vo0; // load output int out_offset = h * out_size + w; vo0 = vld1q_f32(out + out_offset); for (int r = 0; r < 5; ++r) { // input (3 slide) float32x4_t vi0, vi1, vi2, vi3, vi4; // load input vi0 = vld1q_f32(_img + in_offset); vi4 = vld1q_f32(_img + in_offset + 4); vi1 = vextq_f32(vi0, vi4, 1); vi2 = vextq_f32(vi0, vi4, 2); vi3 = vextq_f32(vi0, vi4, 3); float32x4_t vf00; float32x2_t vf01; vf00 = vld1q_f32(filter_ptr); vf01 = vld1_f32(filter_ptr + 3); /* outch 0 */ vo0 = vmlaq_lane_f32(vo0, vi0, vget_low_f32(vf00), 0); vo0 = vmlaq_lane_f32(vo0, vi1, vget_low_f32(vf00), 1); vo0 = vmlaq_lane_f32(vo0, vi2, vget_high_f32(vf00), 0); vo0 = vmlaq_lane_f32(vo0, vi3, vget_high_f32(vf00), 1); vo0 = vmlaq_lane_f32(vo0, vi4, vf01, 1); in_offset += in_size; filter_ptr += 5; } // r vst1q_f32(out + out_offset, vo0); filter_ptr -= 25; } // w } // h } #endif inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(5, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(7, _img, filter_ptr, out, outsize); } #endif // matrix class --------------------------------------------------- // should use opencv if available // class matrix { int _size; int _capacity; float *_x_mem; void delete_x() { delete[] _x_mem; x = NULL; _x_mem = NULL; } // 4 extra for alignment and 4 for 3 padding for SSE //float *new_x(const int size) { _x_mem = new float[size + 4+3]; x = (float *)(((uintptr_t)_x_mem + 16) & ~(uintptr_t)0x0F); return x; } // avx mem aligment float *new_x(const int size) { _x_mem = new float[size + 8 + 7]; x = (float *)(((uintptr_t)_x_mem + 32) & ~(uintptr_t)0x1F); return x; } public: std::string _name; int cols, rows, chans; int chan_stride; int chan_aligned; float *x; // size must be divisible by 8 for AVX virtual int calc_chan_stride(int w, int h) { if (chan_aligned) { int s = w*h; const int remainder = s % 8; if (remainder > 0) s += 8 - remainder; return s; } else return w*h; } matrix( ): cols(0), rows(0), chans(0), _size(0), _capacity(0), chan_stride(0), x(NULL), chan_aligned(0)/*, empty_chan(NULL)*/{} matrix( int _w, int _h, int _c=1, const float *data=NULL, int align_chan=0): cols(_w), rows(_h), chans(_c) { chan_aligned = align_chan; chan_stride = calc_chan_stride(cols, rows); _size= chan_stride*chans; _capacity=_size; x = new_x(_size); if(data!=NULL) memcpy(x,data,_size*sizeof(float)); } // copy constructor - deep copy matrix( const matrix &m) : cols(m.cols), rows(m.rows), chan_aligned(m.chan_aligned), chans(m.chans), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size) {x = new_x(_size); memcpy(x,m.x,sizeof(float)*_size); /*empty_chan = new unsigned char[chans]; memcpy(empty_chan, m.empty_chan, chans);*/} // { v=m.v; x=(float*)v.data();} // copy and pad constructor matrix( const matrix &m, int pad_cols, int pad_rows, mojo::pad_type padding= mojo::zero, int threads=1) : cols(m.cols), rows(m.rows), chans(m.chans), chan_aligned(m.chan_aligned), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size) { x = new_x(_size); memcpy(x, m.x, sizeof(float)*_size); *this = pad(pad_cols, pad_rows, padding, threads); } ~matrix() { if (x) delete_x(); } matrix get_chans(int start_channel, int num_chans=1) const { return matrix(cols,rows,num_chans,&x[start_channel*chan_stride]); } // if edge_pad==0, then the padded area is just 0. // if edge_pad==1 it fills with edge pixel colors // if edge_pad==2 it fills with median edge pixel color matrix pad(int dx, int dy, mojo::pad_type edge_pad = mojo::zero, int threads=1) const { return pad(dx, dy, dx, dy, edge_pad, threads); } matrix pad(int dx, int dy, int dx_right, int dy_bottom, mojo::pad_type edge_pad = mojo::zero, int threads=1) const { matrix v(cols+dx+dx_right,rows+dy+dy_bottom,chans);//,NULL,this->chan_aligned); v.fill(0); //float *new_x = new float[chans*w*h]; #pragma omp parallel for num_threads(threads) for(int k=0; k<chans; k++) { const int v_chan_offset=k*v.chan_stride; const int chan_offset=k*chan_stride; // find median color of perimeter float median = 0.f; if (edge_pad == mojo::median_edge) { int perimeter = 2 * (cols + rows - 2); std::vector<float> d(perimeter); for (int i = 0; i < cols; i++) { d[i] = x[i+ chan_offset]; d[i + cols] = x[i + cols*(rows - 1)+ chan_offset]; } for (int i = 1; i < (rows - 1); i++) { d[i + cols * 2] = x[cols*i+ chan_offset]; // file from back so i dont need to cal index d[perimeter - i] = x[cols - 1 + cols*i+ chan_offset]; } std::nth_element(d.begin(), d.begin() + perimeter / 2, d.end()); median = d[perimeter / 2]; //for (int i = 0; i < v.rows*v.cols; i++) v.x[v_chan_offset + i] = solid_fill; } for(int j=0; j<rows; j++) { memcpy(&v.x[dx+(j+dy)*v.cols+v_chan_offset], &x[j*cols+chan_offset], sizeof(float)*cols); if(edge_pad== mojo::edge) { // do left/right side for(int i=0; i<dx; i++) v.x[i+(j+dy)*v.cols+v_chan_offset]=x[0+j*cols+chan_offset]; for (int i = 0; i<dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = x[(cols - 1) + j*cols + chan_offset]; } else if (edge_pad == mojo::median_edge) { for (int i = 0; i < dx; i++) v.x[i + (j + dy)*v.cols + v_chan_offset] = median; for (int i = 0; i < dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = median; } } // top bottom pad if(edge_pad== mojo::edge) { for(int j=0; j<dy; j++) memcpy(&v.x[(j)*v.cols+v_chan_offset],&v.x[(dy)*v.cols+v_chan_offset], sizeof(float)*v.cols); for (int j = 0; j<dy_bottom; j++) memcpy(&v.x[(j + dy + rows)*v.cols + v_chan_offset], &v.x[(rows - 1 + dy)*v.cols + v_chan_offset], sizeof(float)*v.cols); } if (edge_pad == mojo::median_edge) { for (int j = 0; j<dy; j++) for (int i = 0; i<v.cols; i++) v.x[i + j*v.cols + v_chan_offset] = median; for (int j = 0; j<dy_bottom; j++) for (int i = 0; i<v.cols; i++) v.x[i + (j + dy + rows)*v.cols + v_chan_offset] = median; } } return v; } matrix crop(int dx, int dy, int w, int h, int threads=1) const { matrix v(w,h,chans); #pragma omp parallel for num_threads(threads) for(int k=0; k<chans; k++) { for(int j=0; j<h; j++) { memcpy(&v.x[j*w+k*v.chan_stride], &x[dx+(j+dy)*cols+k*chan_stride], sizeof(float)*w); } } return v; } mojo::matrix shift(int dx, int dy, mojo::pad_type edge_pad=mojo::zero) { int orig_cols=cols; int orig_rows=rows; int off_x=abs(dx); int off_y=abs(dy); mojo::matrix shifted= pad(off_x, off_y, edge_pad); return shifted.crop(off_x-dx, off_y-dy,orig_cols,orig_rows); } mojo::matrix flip_cols() { mojo::matrix v(cols,rows,chans); for(int k=0; k<chans; k++) for(int j=0; j<rows; j++) for(int i=0; i<cols; i++) v.x[i+j*cols+k*chan_stride]=x[(cols-i-1)+j*cols+k*chan_stride]; return v; } mojo::matrix flip_rows() { mojo::matrix v(cols, rows, chans); for (int k = 0; k<chans; k++) for (int j = 0; j<rows; j++) memcpy(&v.x[(rows-1-j)*cols + k*chan_stride],&x[j*cols + k*chan_stride], cols*sizeof(float)); return v; } void clip(float min, float max) { int s = chan_stride*chans; for (int i = 0; i < s; i++) { if (x[i] < min) x[i] = min; if (x[i] > max) x[i]=max; } } void bucket_scaling(int bucket_size, int s) { int weight_size = _size; //std::cout << " The dimensions of the matrix are: " << rw << " chans: " << chans << std::endl; int num_buckets, start_index, end_index, mini, maxi; float alpha, beta; num_buckets = weight_size / bucket_size; if (num_buckets == 0) { //Take care of the leftover cells of the matrix start_index = 0; //start_index = t + (num_buckets*bucket_size); end_index = weight_size; //Find min max phase mini = start_index; maxi = start_index; for (int j = start_index ; j < end_index; j++) { if (x[j] < x[mini]) mini = j; if (x[j] > x[maxi]) maxi = j; } alpha = x[maxi] - x[mini]; beta = x[mini]; //std::cout<<"MIN: "<<x[mini]<<" MAX: "<<x[maxi]<<" ALPHA: "<<alpha<<" BETA: "<<beta<<std::endl; //Mutation phase for (int j = start_index; j < end_index; j++) { //Scaling x[j] -= beta; //std::cout<<"AFTER THE BETA TRANSFORMATION: "<<x[j]<<std::endl; x[j] /= alpha; //std::cout<<"AFTER THE ALPHA TRANSFORMATION: "<<x[j]<<std::endl; //Bit quantization x[j] *= s; x[j] = round(x[j]); x[j] /= s; //Antiscaling x[j] *= alpha; x[j] += beta; } //std::cout << "\n\nLol:\n~~~~~~~~~~~~~~~~\n\n\n"; } else { //std::cout << " num_buckets: " << num_buckets << std::endl; for (int i = 0 ; i < num_buckets; i++) { //For each bucket //start_index = i * bucket_size; start_index = (i * bucket_size); //end_index = t; end_index = start_index + bucket_size; //Find min max phase mini = start_index; maxi = start_index; for (int j = start_index ; j < end_index; j++) { if (x[j] < x[mini]) mini = j; if (x[j] > x[maxi]) maxi = j; } alpha = x[maxi] - x[mini]; beta = x[mini]; //Mutation phase for (int j = start_index; j < end_index; j++) { //Scaling x[j] -= beta; x[j] /= alpha; //Bit quantization x[j] *= s; x[j] = round(x[j]); x[j] /= s; //Antiscaling x[j] *= alpha; x[j] += beta; } //std::cout << "\n\n\n~~~~~~~~~~~~~~~~\n\n\n"; } if (weight_size % bucket_size != 0) { //Take care of the leftover cells of the matrix start_index = weight_size - weight_size % bucket_size; //start_index = t + (num_buckets*bucket_size); end_index = weight_size; //Find min max phase mini = start_index; maxi = start_index; for (int j = start_index ; j < end_index; j++) { if (x[j] < x[mini]) mini = j; if (x[j] > x[maxi]) maxi = j; } alpha = x[maxi] - x[mini]; beta = x[mini]; //Mutation phase for (int j = start_index; j < end_index; j++) { //Scaling x[j] -= beta; x[j] /= alpha; //Bit quantization x[j] *= s; x[j] = round(x[j]); x[j] /= s; //Antiscaling x[j] *= alpha; x[j] += beta; } //std::cout << "\n\nExtra:\n~~~~~~~~~~~~~~~~\n\n\n"; } } } void min_max(float *min, float *max, int *min_i=NULL, int *max_i=NULL) { int s = rows*cols; int mini = 0; int maxi = 0; for (int c = 0; c < chans; c++) { const int t = chan_stride*c; for (int i = t; i < t+s; i++) { if (x[i] < x[mini]) mini = i; if (x[i] > x[maxi]) maxi = i; } } *min = x[mini]; *max = x[maxi]; if (min_i) *min_i = mini; if (max_i) *max_i = maxi; } void round_matrix(int quantization_s) { int s = rows * cols; for (int c = 0; c < chans; c++) { const int t = chan_stride * c; for (int i = t; i < t + s; i++) { if (x[i] - floor(x[i]) > 0.5) x[i] = floor(x[i]*s)/s + 1/s; else x[i] = floor(x[i]*s)/s; } } } void unmapping(std::map<int,float>& dictionary){ int s = rows * cols; //Iterate through all dict values for (int c = 0; c < chans; c++) { const int t = chan_stride * c; for (int i = t; i < t + s; i++) { //If the value of the matrix is equal to the value of matrix then //assign the index of the dict to the matrix //? Maybe also needs a cast to int x[i] = dictionary[x[i]]; } } } float mean() { const int s = rows*cols; int cnt = 0;// channel*s; float average = 0; for (int c = 0; c < chans; c++) { const int t = chan_stride*c; for (int i = 0; i < s; i++) average += x[i + t]; } average = average / (float)(s*chans); return average; } float remove_mean(int channel) { int s = rows*cols; int offset = channel*chan_stride; float average=0; for(int i=0; i<s; i++) average+=x[i+offset]; average= average/(float)s; for(int i=0; i<s; i++) x[i+offset]-=average; return average; } float remove_mean() { float m=mean(); int s = chan_stride*chans; //int offset = channel*s; for(int i=0; i<s; i++) x[i]-=m; return m; } void fill(float val) { for(int i=0; i<_size; i++) x[i]=val; } void fill_random_uniform(float range) { std::mt19937 gen(0); std::uniform_real_distribution<float> dst(-range, range); for (int i = 0; i<_size; i++) x[i] = dst(gen); } void fill_random_normal(float std) { std::mt19937 gen(0); std::normal_distribution<float> dst(0, std); for (int i = 0; i<_size; i++) x[i] = dst(gen); } // deep copy inline matrix& operator =(const matrix &m) { resize(m.cols, m.rows, m.chans, m.chan_aligned); memcpy(x,m.x,sizeof(float)*_size); // memcpy(empty_chan, m.empty_chan, chans); return *this; } int size() const {return _size;} void resize(int _w, int _h, int _c, int align_chans=0) { chan_aligned = align_chans; int new_stride = calc_chan_stride(_w,_h); int s = new_stride*_c; if(s>_capacity) { if(_capacity>0) delete_x(); _size = s; _capacity=_size; x = new_x(_size); } cols = _w; rows = _h; chans = _c; _size = s; chan_stride = new_stride; } // dot vector to 2d mat inline matrix dot_1dx2d(const matrix &m_2d) const { mojo::matrix v(m_2d.rows, 1, 1); for(int j=0; j<m_2d.rows; j++) v.x[j]=dot(x,&m_2d.x[j*m_2d.cols],_size); return v; } // += inline matrix& operator+=(const matrix &m2){ for(int i = 0; i < _size; i++) x[i] += m2.x[i]; return *this; } // -= inline matrix& operator-=(const matrix &m2) { for (int i = 0; i < _size; i++) x[i] -= m2.x[i]; return *this; } #ifndef MOJO_AVX // *= float inline matrix operator *=(const float v) { for (int i = 0; i < _size; i++) x[i] = x[i] * v; return *this; } #else inline matrix operator *=(const float v) { __m128 b; b = _mm_set_ps(v, v, v, v); for (int j = 0; j < _size; j += 4) _mm_store_ps(x + j, _mm_mul_ps(_mm_load_ps(x + j), b)); return *this; } #endif // *= matrix inline matrix operator *=(const matrix &v) { for (int i = 0; i < _size; i++) x[i] = x[i] * v.x[i]; return *this; } inline matrix operator *(const matrix &v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] * v.x[i]; return T; } // * float inline matrix operator *(const float v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] * v; return T; } // + float inline matrix operator +(const float v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] + v; return T; } // + inline matrix operator +(matrix m2) { matrix T(cols,rows,chans); for(int i = 0; i < _size; i++) T.x[i] = x[i] + m2.x[i]; return T; } }; }// namespace
GB_binop__bget_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_08__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_02__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_04__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_int32) // C+=b function (dense accum): GB (_Cdense_accumb__bget_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int32) // C=scalar+B GB (_bind1st__bget_int32) // C=scalar+B' GB (_bind1st_tran__bget_int32) // C=A+scalar GB (_bind2nd__bget_int32) // C=A'+scalar GB (_bind2nd_tran__bget_int32) // C type: int32_t // A type: int32_t // A pattern? 0 // B type: int32_t // B pattern? 0 // BinaryOp: cij = GB_BITGET (aij, bij, int32_t, 32) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int32_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITGET (x, y, int32_t, 32) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_INT32 || GxB_NO_BGET_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bget_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bget_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int32_t alpha_scalar ; int32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int32_t *) alpha_scalar_in)) ; beta_scalar = (*((int32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bget_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bget_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITGET (x, bij, int32_t, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITGET (aij, y, int32_t, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, int32_t, 32) ; \ } GrB_Info GB (_bind1st_tran__bget_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (aij, y, int32_t, 32) ; \ } GrB_Info GB (_bind2nd_tran__bget_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GxB_deserialize_type_name.c
//------------------------------------------------------------------------------ // GxB_deserialize_type_name: return the name of a type //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB.h" #include "GB_serialize.h" // GxB_deserialize_type_name extracts the type_name of the GrB_Type of the // GrB_Matrix or GrB_Vector held in a serialized blob. On input, type_name // must point to a user-owned char array of size at least GxB_MAX_NAME_LEN (it // must not point into the blob itself). On output, type_name will contain a // null-terminated string with the corresponding C type name. If the blob // holds a matrix of a built-in type, the name is returned as "bool" for // GrB_BOOL, "uint8_t" for GrB_UINT8, "float complex" for GxB_FC32, etc. GrB_Info GxB_deserialize_type_name // return the type name of a blob ( // output: char *type_name, // name of the type (char array of size at least // GxB_MAX_NAME_LEN, owned by the user application). // input, not modified: const void *blob, // the blob GrB_Index blob_size // size of the blob ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_deserialize_type_name (type_name, blob, blob_size)") ; GB_RETURN_IF_NULL (type_name) ; GB_RETURN_IF_NULL (blob) ; if (blob_size < GB_BLOB_HEADER_SIZE) { // blob is invalid return (GrB_INVALID_OBJECT) ; } //-------------------------------------------------------------------------- // get the blob header //-------------------------------------------------------------------------- size_t s = 0 ; GB_BLOB_READ (blob_size2, size_t) ; GB_BLOB_READ (typecode, int32_t) ; if (blob_size2 != (size_t) blob_size) { // blob is invalid return (GrB_INVALID_OBJECT) ; } //-------------------------------------------------------------------------- // get the type_name from the built-in type or the blob //-------------------------------------------------------------------------- if (typecode >= GB_BOOL_code && typecode < GB_UDT_code) { // blob has a built-in type; the name is not in the blob GrB_Type blob_type = GB_code_type ((GB_Type_code) typecode, NULL) ; ASSERT (blob_type != NULL) ; memcpy (type_name, blob_type->name, GxB_MAX_NAME_LEN) ; } else if (typecode == GB_UDT_code) { // blob has a user-defined type if (blob_size < GB_BLOB_HEADER_SIZE + GxB_MAX_NAME_LEN) { // blob is invalid return (GrB_INVALID_OBJECT) ; } // get the name of the user type from the blob memcpy (type_name, ((GB_void *) blob) + GB_BLOB_HEADER_SIZE, GxB_MAX_NAME_LEN) ; } else { // blob is invalid return (GrB_INVALID_OBJECT) ; } // this should already be in the blob, but set it to null just in case type_name [GxB_MAX_NAME_LEN-1] = '\0' ; //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- #pragma omp flush return (GrB_SUCCESS) ; }
fftw.h
#ifndef __FFTW_H__ #define __FFTW_H__ #include <fftw3.h> #include <omp.h> #include <cassert> #include <iostream> #include "types.h" #include "index.h" namespace Impl { struct FFT { int nx1_, nx2_, nb_batches_; int nx1h_, nx2h_; fftw_plan forward_c2c_plan_, forward_r2c_plan_; fftw_plan backward_c2c_plan_, backward_c2r_plan_; // Thread private buffer complex64 *dptr_buffer_c_; complex64 *thread_private_buffers_nx1h_, *thread_private_buffers_nx2_; complex64 *thread_private_buffers_nx2_out_; float64 *thread_private_buffers_nx1_r2c_; float64 *thread_private_buffers_nx1_c2r_; complex_view_3d d_buffer_c_; complex_view_2d d_thread_private_buffers_nx1h_, d_thread_private_buffers_nx2_; complex_view_2d d_thread_private_buffers_nx2_out_; view_2d d_buffers_nx1_r2c_, d_buffers_nx1_c2r_; FFT(int nx1, int nx2) : nx1_(nx1), nx2_(nx2), nb_batches_(1) { init(); } FFT(int nx1, int nx2, int batch) : nx1_(nx1), nx2_(nx2), nb_batches_(batch) { init(); } virtual ~FFT() { fftw_destroy_plan(forward_c2c_plan_); fftw_destroy_plan(backward_c2c_plan_); fftw_destroy_plan(forward_r2c_plan_); fftw_destroy_plan(backward_c2r_plan_); } void fft(complex64 *dptr_in, complex64 *dptr_out) { fftw_complex *in = reinterpret_cast<fftw_complex*>(dptr_in); fftw_complex *out = reinterpret_cast<fftw_complex*>(dptr_out); fftw_execute_dft(forward_c2c_plan_, in, out); } void fftr2c(float64 *dptr_in, complex64 *dptr_out) { fftw_complex *out = reinterpret_cast<fftw_complex*>(dptr_out); fftw_execute_dft_r2c(forward_r2c_plan_, dptr_in, out); } void ifft(complex64 *dptr_in, complex64 *dptr_out) { fftw_complex *in = reinterpret_cast<fftw_complex*>(dptr_in); fftw_complex *out = reinterpret_cast<fftw_complex*>(dptr_out); fftw_execute_dft(backward_c2c_plan_, in, out); } void ifftc2r(complex64 *dptr_in, float64 *dptr_out) { fftw_complex *in = reinterpret_cast<fftw_complex*>(dptr_in); fftw_execute_dft_c2r(backward_c2r_plan_, in, dptr_out); } /* In the host code, we assume LayoutRight (C style) */ void fft2(float64 *dptr_in, complex64 *dptr_out) { if(nb_batches_ == 1) { fft2_serial(dptr_in, dptr_out); } else { fft2_batch(dptr_in, dptr_out); } } /* @brief 2D FFT wrapper for batched case * In the host code, we assume LayoutRight (C style) * @param[in] dptr_in(nx1h,nx2,batch) * @param[out] dptr_out(nx1,nx2,batch) */ void ifft2(complex64 *dptr_in, float64 *dptr_out) { if(nb_batches_ == 1) { ifft2_serial(dptr_in, dptr_out); } else { ifft2_batch(dptr_in, dptr_out); } } private: /* @brief 2D FFT wrapper for batched case * In the host code, we assume LayoutRight (C style) * @param[in] dptr_in(nx1,nx2) * @param[out] dptr_out(nx1h,nx2) */ void fft2_serial(float64 *dptr_in, complex64 *dptr_out) { #pragma omp parallel { int tid = omp_get_thread_num(); float64 *thread_private_buffer_nx1 = &thread_private_buffers_nx1_r2c_[nx1_*tid]; complex64 *thread_private_buffer_nx1h = &thread_private_buffers_nx1h_[nx1h_*tid]; complex64 *thread_private_buffer_nx2 = &thread_private_buffers_nx2_[nx2_*tid]; // Fourier Transform in x direction #pragma omp for schedule(static) for(int ix2=0; ix2 < nx2_; ix2++) { for(int ix1=0; ix1 < nx1_; ix1++) { int idx = Index::coord_2D2int(ix2, ix1, nx2_, nx1_); thread_private_buffer_nx1[ix1] = dptr_in[idx]; } fftr2c(thread_private_buffer_nx1, thread_private_buffer_nx1h); for(int ix1=0; ix1 < nx1h_; ix1++) { int idx = Index::coord_2D2int(ix2, ix1, nx2_, nx1h_); dptr_buffer_c_[idx] = thread_private_buffer_nx1h[ix1]; } } // Fourier Transform in y direction #pragma omp for schedule(static) for(int ix1=0; ix1 < nx1h_; ix1++) { int offset = nx2_ * ix1; fft(&dptr_buffer_c_[offset], thread_private_buffer_nx2); for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_2D2int(ix2, ix1, nx2_, nx1h_); dptr_out[idx] = thread_private_buffer_nx2[ix2]; } } } } /* @brief 2D FFT wrapper for batched case * In the host code, we assume LayoutRight (C style) * @param[in] dptr_in(nx1,nx2,batch) * @param[out] dptr_out(nx1h,nx2,batch) */ void fft2_batch(float64 *dptr_in, complex64 *dptr_out) { #pragma omp parallel { int tid = omp_get_thread_num(); float64 *thread_private_buffer_nx1 = &thread_private_buffers_nx1_r2c_[nx1_*tid]; complex64 *thread_private_buffer_nx1h = &thread_private_buffers_nx1h_[nx1h_*tid]; complex64 *thread_private_buffer_nx2 = &thread_private_buffers_nx2_[nx2_*tid]; // Fourier Transform in x direction #pragma omp for schedule(static), collapse(2) for(int ib=0; ib<nb_batches_; ib++) { for(int ix2=0; ix2 < nx2_; ix2++) { for(int ix1=0; ix1 < nx1_; ix1++) { int idx = Index::coord_3D2int(ib, ix2, ix1, nb_batches_, nx2_, nx1_); thread_private_buffer_nx1[ix1] = dptr_in[idx]; } fftr2c(thread_private_buffer_nx1, thread_private_buffer_nx1h); for(int ix1=0; ix1 < nx1h_; ix1++) { int idx = Index::coord_3D2int(ix2, ix1, ib, nx2_, nx1h_, nb_batches_); dptr_buffer_c_[idx] = thread_private_buffer_nx1h[ix1]; } } } // Fourier Transform in y direction #pragma omp for schedule(static), collapse(2) for(int ib=0; ib<nb_batches_; ib++) { for(int ix1=0; ix1 < nx1h_; ix1++) { int offset = nx2_ * Index::coord_2D2int(ix1, ib, nx1h_, nb_batches_); fft(&dptr_buffer_c_[offset], thread_private_buffer_nx2); for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_3D2int(ib, ix2, ix1, nb_batches_, nx2_, nx1h_); dptr_out[idx] = thread_private_buffer_nx2[ix2]; } } } } } /* @brief 2D FFT wrapper for serial case * In the host code, we assume LayoutRight (C style) * @param[in] dptr_in(nx1h,nx2) * @param[out] dptr_out(nx1,nx2) */ void ifft2_serial(complex64 *dptr_in, float64 *dptr_out) { #pragma omp parallel { int tid = omp_get_thread_num(); float64 *thread_private_buffer_nx1 = &thread_private_buffers_nx1_c2r_[(nx1_+2)*tid]; complex64 *thread_private_buffer_nx2 = &thread_private_buffers_nx2_[nx2_*tid]; complex64 *thread_private_buffer_nx2_out = &thread_private_buffers_nx2_out_[nx2_*tid]; // Inverse Fourier Transform in y direction #pragma omp for schedule(static) for(int ix1=0; ix1 < nx1h_; ix1++) { for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_2D2int(ix2, ix1, nx2_, nx1h_); thread_private_buffer_nx2[ix2] = dptr_in[idx]; } ifft(thread_private_buffer_nx2, thread_private_buffer_nx2_out); for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_2D2int(ix1, ix2, nx1h_, nx2_); dptr_buffer_c_[idx] = thread_private_buffer_nx2_out[ix2]; } } // Inverse Fourier Transform in x direction #pragma omp for schedule(static) for(int ix2=0; ix2 < nx2_; ix2++) { int offset_in = nx1h_ * ix2; ifftc2r(&dptr_buffer_c_[offset_in], thread_private_buffer_nx1); for(int ix1=0; ix1 < nx1_; ix1++) { int idx = Index::coord_2D2int(ix2, ix1, nx2_, nx1_); dptr_out[idx] = thread_private_buffer_nx1[ix1]; } } } } /* @brief 2D FFT wrapper for batched case * In the host code, we assume LayoutRight (C style) * @param[in] dptr_in(nx1h,nx2,batch) * @param[out] dptr_out(nx1,nx2,batch) */ void ifft2_batch(complex64 *dptr_in, float64 *dptr_out) { #pragma omp parallel { int tid = omp_get_thread_num(); float64 *thread_private_buffer_nx1 = &thread_private_buffers_nx1_c2r_[(nx1_+2)*tid]; complex64 *thread_private_buffer_nx2 = &thread_private_buffers_nx2_[nx2_*tid]; complex64 *thread_private_buffer_nx2_out = &thread_private_buffers_nx2_out_[nx2_*tid]; // Inverse Fourier Transform in y direction #pragma omp for schedule(static), collapse(2) for(int ib=0; ib < nb_batches_; ib++) { for(int ix1=0; ix1 < nx1h_; ix1++) { for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_3D2int(ib, ix2, ix1, nb_batches_, nx2_, nx1h_); thread_private_buffer_nx2[ix2] = dptr_in[idx]; } ifft(thread_private_buffer_nx2, thread_private_buffer_nx2_out); for(int ix2=0; ix2 < nx2_; ix2++) { int idx = Index::coord_3D2int(ix1, ix2, ib, nx1h_, nx2_, nb_batches_); dptr_buffer_c_[idx] = thread_private_buffer_nx2_out[ix2]; } } } // Inverse Fourier Transform in x direction #pragma omp for schedule(static), collapse(2) for(int ib=0; ib < nb_batches_; ib++) { for(int ix2=0; ix2 < nx2_; ix2++) { int offset = nx1h_ * Index::coord_2D2int(ix2, ib, nx2_, nb_batches_); ifftc2r(&dptr_buffer_c_[offset], thread_private_buffer_nx1); for(int ix1=0; ix1 < nx1_; ix1++) { int idx = Index::coord_3D2int(ib, ix2, ix1, nb_batches_, nx2_, nx1_); dptr_out[idx] = thread_private_buffer_nx1[ix1]; } } } } } void init() { nx1h_ = nx1_/2 + 1; nx2h_ = nx2_/2 + 1; assert(nb_batches_ >= 1); // Initialize fftw fftw_complex *c_in, *c_out; fftw_complex *c_in_c2r, *c_out_r2c; float64 *in, *out; c_in = fftw_alloc_complex(nx2_); c_out = fftw_alloc_complex(nx2_); in = fftw_alloc_real(nx1_); out = fftw_alloc_real(nx1_+2); c_in_c2r = fftw_alloc_complex(nx1h_); c_out_r2c = fftw_alloc_complex(nx1h_); forward_c2c_plan_ = fftw_plan_dft_1d(nx2_, c_in, c_out, FFTW_FORWARD, FFTW_ESTIMATE); backward_c2c_plan_ = fftw_plan_dft_1d(nx2_, c_out, c_in, FFTW_BACKWARD, FFTW_ESTIMATE); forward_r2c_plan_ = fftw_plan_dft_r2c_1d(nx1_, in, c_out_r2c, FFTW_ESTIMATE); backward_c2r_plan_ = fftw_plan_dft_c2r_1d(nx1_, c_in_c2r, out, FFTW_ESTIMATE); fftw_free(in); fftw_free(out); fftw_free(c_in); fftw_free(c_out); fftw_free(c_in_c2r); fftw_free(c_out_r2c); // Malloc thread private buffers int nb_threads=0; #pragma omp parallel nb_threads = omp_get_num_threads(); std::cout << "nb_threads = " << nb_threads << std::endl; d_buffer_c_ = complex_view_3d("buffer_3d", nb_batches_, nx1h_, nx2_); d_thread_private_buffers_nx1h_ = complex_view_2d("buffer_1d_nx1", nb_threads, nx1h_); d_thread_private_buffers_nx2_ = complex_view_2d("buffer_1d_nx2", nb_threads, nx2_); d_thread_private_buffers_nx2_out_ = complex_view_2d("buffer_1d_nx2", nb_threads, nx2_); d_buffers_nx1_r2c_ = view_2d("buffer_1d_nx1_r2c", nb_threads, nx1_); d_buffers_nx1_c2r_ = view_2d("buffer_1d_nx1_c2r", nb_threads, nx1_+2); dptr_buffer_c_ = d_buffer_c_.data(); thread_private_buffers_nx1h_ = d_thread_private_buffers_nx1h_.data(); thread_private_buffers_nx2_ = d_thread_private_buffers_nx2_.data(); thread_private_buffers_nx2_out_ = d_thread_private_buffers_nx2_out_.data(); thread_private_buffers_nx1_r2c_ = d_buffers_nx1_r2c_.data(); thread_private_buffers_nx1_c2r_ = d_buffers_nx1_c2r_.data(); } }; }; #endif
GB_binop__max_int32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__max_int32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__max_int32) // A.*B function (eWiseMult): GB (_AemultB_03__max_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__max_int32) // A*D function (colscale): GB (_AxD__max_int32) // D*A function (rowscale): GB (_DxB__max_int32) // C+=B function (dense accum): GB (_Cdense_accumB__max_int32) // C+=b function (dense accum): GB (_Cdense_accumb__max_int32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__max_int32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__max_int32) // C=scalar+B GB (_bind1st__max_int32) // C=scalar+B' GB (_bind1st_tran__max_int32) // C=A+scalar GB (_bind2nd__max_int32) // C=A'+scalar GB (_bind2nd_tran__max_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = GB_IMAX (aij, bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IMAX (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MAX || GxB_NO_INT32 || GxB_NO_MAX_INT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__max_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__max_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__max_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__max_int32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int32_t int32_t bwork = (*((int32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__max_int32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__max_int32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__max_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__max_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__max_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__max_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__max_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__max_int32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int32_t bij = Bx [p] ; Cx [p] = GB_IMAX (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__max_int32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = Ax [p] ; Cx [p] = GB_IMAX (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_IMAX (x, aij) ; \ } GrB_Info GB (_bind1st_tran__max_int32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = GB_IMAX (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__max_int32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
trmv_x_dia_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t ONAME_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA* A, const ALPHA_Number* x, const ALPHA_Number beta, ALPHA_Number* y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number** tmp = (ALPHA_Number**)malloc(sizeof(ALPHA_Number*) * thread_num); for(int i = 0; i < thread_num; ++i) { tmp[i] = malloc(sizeof(ALPHA_Number) * m); memset(tmp[i], 0, sizeof(ALPHA_Number) * m); } const ALPHA_INT diags = A->ndiag; #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < diags; ++i) { const ALPHA_INT threadId = alpha_get_thread_id(); const ALPHA_INT dis = A->distance[i]; if(dis > 0) { const ALPHA_INT row_start = 0; const ALPHA_INT col_start = dis; const ALPHA_INT nnz = m - dis; const ALPHA_INT start = i * A->lval; for(ALPHA_INT j = 0; j < nnz; ++j) { ALPHA_Number v; alpha_mul(v, alpha, A->values[start + j]); alpha_madde(tmp[threadId][row_start + j], v, x[col_start + j]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); alpha_madde(y[i], alpha, x[i]); for(ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(y[i], y[i], tmp[j][i]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < thread_num; ++i) { alpha_free(tmp[i]); } alpha_free(tmp); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA* A, const ALPHA_Number* x, const ALPHA_Number beta, ALPHA_Number* y) { return ONAME_omp(alpha, A, x, beta, y); }
GB_unaryop__lnot_bool_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_bool_uint64 // op(A') function: GB_tran__lnot_bool_uint64 // C type: bool // A type: uint64_t // cast: bool cij = (bool) aij // unaryop: cij = !aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !x ; // casting #define GB_CASTING(z, aij) \ bool z = (bool) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_BOOL || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_bool_uint64 ( bool *Cx, // Cx and Ax may be aliased uint64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_bool_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
util.h
#ifndef _C_UTIL_ #define _C_UTIL_ #include <math.h> #include <iostream> //------------------------------------------------------------------- //--initialize array with maximum limit //------------------------------------------------------------------- template<typename datatype> void fill(datatype *A, const int n, const datatype maxi){ for (int j = 0; j < n; j++) { A[j] = ((datatype) maxi * (rand() / (RAND_MAX + 1.0f))); } } //--print matrix template<typename datatype> void print_matrix(datatype *A, int height, int width){ for(int i=0; i<height; i++){ for(int j=0; j<width; j++){ int idx = i*width + j; std::cout<<A[idx]<<" "; } std::cout<<std::endl; } return; } //------------------------------------------------------------------- //--verify results //------------------------------------------------------------------- #define MAX_RELATIVE_ERROR .002 template<typename datatype> void verify_array(const datatype *cpuResults, const datatype *gpuResults, const int size){ char passed = true; #pragma omp parallel for for (int i=0; i<size; i++){ if (fabs(cpuResults[i] - gpuResults[i]) / cpuResults[i] > MAX_RELATIVE_ERROR){ passed = false; } } if (passed){ std::cout << "--cambine:passed:-)" << endl; } else{ std::cout << "--cambine: failed:-(" << endl; } return ; } template<typename datatype> void compare_results(const datatype *cpu_results, const datatype *gpu_results, const int size){ char passed = true; //#pragma omp parallel for for (int i=0; i<size; i++){ if (cpu_results[i]!=gpu_results[i]){ passed = false; } } if (passed){ std::cout << "--cambine: passed: -)" << endl; } else{ std::cout << "--cambine: failed :-(" << endl; } return ; } #endif
pcpaes_ecbencrypt.c
/******************************************************************************* * Copyright 2013-2019 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * You may not use this file except in compliance with the License. You may * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* // // Purpose: // Cryptography Primitive. // AES encryption/decryption (ECB mode) // // Contents: // ippsAESEncryptECB() // */ #include "owndefs.h" #include "owncp.h" #include "pcpaesm.h" #include "pcptool.h" #if defined(_OPENMP) # include "omp.h" #endif #if (_ALG_AES_SAFE_==_ALG_AES_SAFE_COMPOSITE_GF_) #elif (_ALG_AES_SAFE_==_ALG_AES_SAFE_COMPACT_SBOX_) # include "pcprijtables.h" #else #endif /* // AES-ECB ecnryption // // Parameters: // pSrc pointer to the source data buffer // pDst pointer to the target data buffer // nBlocks number of ecnrypted data blocks // pCtx pointer to the AES context */ static void cpEncryptAES_ecb(const Ipp8u* pSrc, Ipp8u* pDst, int nBlocks, const IppsAESSpec* pCtx) { #if (_IPP>=_IPP_P8) || (_IPP32E>=_IPP32E_Y8) /* use pipelined version is possible */ if(AES_NI_ENABLED==RIJ_AESNI(pCtx)) { EncryptECB_RIJ128pipe_AES_NI(pSrc, pDst, RIJ_NR(pCtx), RIJ_EKEYS(pCtx), nBlocks*MBS_RIJ128); } else #endif { /* block-by-block encryption */ RijnCipher encoder = RIJ_ENCODER(pCtx); while(nBlocks) { //encoder((const Ipp32u*)pSrc, (Ipp32u*)pDst, RIJ_NR(pCtx), RIJ_EKEYS(pCtx), (const Ipp32u (*)[256])RIJ_ENC_SBOX(pCtx)); #if (_ALG_AES_SAFE_==_ALG_AES_SAFE_COMPACT_SBOX_) encoder(pSrc, pDst, RIJ_NR(pCtx), RIJ_EKEYS(pCtx), RijEncSbox/*NULL*/); #else encoder(pSrc, pDst, RIJ_NR(pCtx), RIJ_EKEYS(pCtx), NULL); #endif pSrc += MBS_RIJ128; pDst += MBS_RIJ128; nBlocks--; } } } /*F* // Name: ippsAESEncryptECB // // Purpose: AES-ECB encryption. // // Returns: Reason: // ippStsNullPtrErr pCtx == NULL // pSrc == NULL // pDst == NULL // ippStsContextMatchErr !VALID_AES_ID() // ippStsLengthErr dataLen <1 // ippStsUnderRunErr 0!=(dataLen%MBS_RIJ128) // ippStsNoErr no errors // // Parameters: // pSrc pointer to the source data buffer // pDst pointer to the target data buffer // len input/output buffer length (in bytes) // pCtx pointer to the AES context // *F*/ IPPFUN(IppStatus, ippsAESEncryptECB,(const Ipp8u* pSrc, Ipp8u* pDst, int len, const IppsAESSpec* pCtx)) { /* test context */ IPP_BAD_PTR1_RET(pCtx); /* use aligned AES context */ pCtx = (IppsAESSpec*)( IPP_ALIGNED_PTR(pCtx, AES_ALIGNMENT) ); /* test the context ID */ IPP_BADARG_RET(!VALID_AES_ID(pCtx), ippStsContextMatchErr); /* test source and target buffer pointers */ IPP_BAD_PTR2_RET(pSrc, pDst); /* test stream length */ IPP_BADARG_RET((len<1), ippStsLengthErr); /* test stream integrity */ IPP_BADARG_RET((len&(MBS_RIJ128-1)), ippStsUnderRunErr); /* do encryption */ { int nBlocks = len / MBS_RIJ128; #if !defined(_OPENMP) #if(_IPP32E>=_IPP32E_K0) if (IsFeatureEnabled(ippCPUID_AVX512VAES)) EncryptECB_RIJ128pipe_VAES_NI(pSrc, pDst, len, pCtx); else #endif cpEncryptAES_ecb(pSrc, pDst, nBlocks, pCtx); #else int blk_per_thread = AES_NI_ENABLED==RIJ_AESNI(pCtx)? AESNI128_MIN_BLK_PER_THREAD : RIJ128_MIN_BLK_PER_THREAD; int nThreads = IPP_MIN(IPPCP_GET_NUM_THREADS(), IPP_MAX(nBlocks/blk_per_thread, 1)); if(1==nThreads) cpEncryptAES_ecb(pSrc, pDst, nBlocks, pCtx); else { int blksThreadReg; int blksThreadTail; #pragma omp parallel IPPCP_OMP_LIMIT_MAX_NUM_THREADS(nThreads) { #pragma omp master { nThreads = omp_get_num_threads(); blksThreadReg = nBlocks / nThreads; blksThreadTail = blksThreadReg + nBlocks % nThreads; } #pragma omp barrier { int id = omp_get_thread_num(); Ipp8u* pThreadSrc = (Ipp8u*)pSrc + id*blksThreadReg * MBS_RIJ128; Ipp8u* pThreadDst = (Ipp8u*)pDst + id*blksThreadReg * MBS_RIJ128; int blkThread = (id==(nThreads-1))? blksThreadTail : blksThreadReg; cpEncryptAES_ecb(pThreadSrc, pThreadDst, blkThread, pCtx); } } } #endif /* _OPENMP version */ return ippStsNoErr; } }
convolution_pack1to16.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void convolution_pack1to16_avx512(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_packed, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __m512 _sum = _mm512_setzero_ps(); if (bias_data_ptr) { _sum = _mm512_loadu_ps(bias_data_ptr + p * 16); } const float* kptr = weight_data_packed.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const float* sptr = m.row(i * stride_h) + j * stride_w; for (int k = 0; k < maxk; k++) { __m512 _val = _mm512_set1_ps(sptr[space_ofs[k]]); __m512 _w = _mm512_load_ps(kptr); _sum = _mm512_fmadd_ps(_val, _w, _sum); kptr += 16; } } _sum = activation_avx512(_sum, activation_type, activation_params); _mm512_store_ps(outptr, _sum); outptr += 16; } } } }
mkl_util.h
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_UTIL_MKL_UTIL_H_ #define TENSORFLOW_CORE_UTIL_MKL_UTIL_H_ #ifdef INTEL_MKL #include <string> #include <vector> #include <unordered_map> #include <utility> #ifdef INTEL_MKL_ML #include "mkl_dnn.h" #include "mkl_dnn_types.h" #include "mkl_service.h" #include "mkl_trans.h" #endif #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/graph/mkl_graph_util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" #ifndef INTEL_MKL_ML #include "mkldnn.hpp" #include "tensorflow/core/lib/core/stringpiece.h" using mkldnn::engine; using mkldnn::memory; using mkldnn::padding_kind; using mkldnn::primitive; using mkldnn::reorder; #endif #ifdef _WIN32 typedef unsigned int uint; #endif namespace tensorflow { // The file contains a number of utility classes and functions used by MKL // enabled kernels // This class encapsulates all the meta data that is associated with an MKL // tensor. A tensor is an MKL tensor if it was created as the result of an // MKL operation, and did not go through a conversion to a standard // Tensorflow tensor. typedef enum { W = 0, H = 1, C = 2, N = 3 } MklDims; typedef enum { Dim_N = 0, Dim_C = 1, Dim_H = 2, Dim_W = 3, Dim_O = 0, Dim_I = 1 } MklDnnDims; #ifdef INTEL_MKL_ML class MklShape { public: MklShape() {} TF_DISALLOW_COPY_AND_ASSIGN(MklShape); // Cannot copy ~MklShape() { if (sizes_) delete[] sizes_; if (strides_) delete[] strides_; if (mklLayout_) CHECK_EQ(dnnLayoutDelete_F32(mklLayout_), E_SUCCESS); if (tfLayout_) CHECK_EQ(dnnLayoutDelete_F32(tfLayout_), E_SUCCESS); if (tf_to_mkl_dim_map_) delete[] tf_to_mkl_dim_map_; } const bool IsMklTensor() const { return isMklTensor_; } void SetMklTensor(const bool isMklTensor) { isMklTensor_ = isMklTensor; } void SetDimensions(const size_t dimension) { dimension_ = dimension; } void SetMklLayout(dnnLayout_t mklLayout) { mklLayout_ = mklLayout; } void SetMklLayout(const void* primitive, size_t resourceType) { CHECK_EQ( dnnLayoutCreateFromPrimitive_F32(&mklLayout_, (dnnPrimitive_t)primitive, (dnnResourceType_t)resourceType), E_SUCCESS); } void SetTfLayout(const size_t dimension, const size_t* sizes, const size_t* strides) { dimension_ = dimension; if (dimension > 0) { // MKl doesn't support zero dimension tensors sizes_ = new size_t[dimension]; strides_ = new size_t[dimension]; for (int ii = 0; ii < dimension; ii++) { sizes_[ii] = sizes[ii]; strides_[ii] = strides[ii]; } CHECK_EQ(dnnLayoutCreate_F32(&tfLayout_, dimension, sizes, strides), E_SUCCESS); } } // Default case - MKL dim ordering is opposite of TF dim ordering // MKL -> (DIMS-1)...0 where (DIMS-1) is outermost dim and 0 is innermost dim // TF -> 0...(DIMS-1) where 0 is outermost dim and (DIMS-1) is innermost dim // For layers that rely on data_format semantics (conv, pooling etc.) // or operate only on certain dimensions (relu, concat, split etc.), // Mkl APIs might require us to reorder these dimensions. In such cases, // kernels should explicitly set this map void SetTfDimOrder(const size_t dimension) { CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } for (size_t ii = 0; ii < dimension; ii++) { tf_to_mkl_dim_map_[ii] = dimension - (ii + 1); } } void SetTfDimOrder(const size_t dimension, const size_t* tf_to_mkl_dim_map) { CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } for (size_t ii = 0; ii < dimension; ii++) { tf_to_mkl_dim_map_[ii] = tf_to_mkl_dim_map[ii]; } } void SetTfDimOrder(const size_t dimension, TensorFormat data_format) { CHECK_EQ(dimension, 4); CHECK(dimension == dimension_); if (tf_to_mkl_dim_map_ == nullptr) { tf_to_mkl_dim_map_ = new size_t[dimension]; } tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDims::W; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDims::H; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDims::C; tf_to_mkl_dim_map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDims::N; } const dnnLayout_t GetMklLayout() const { return mklLayout_; } const dnnLayout_t GetTfLayout() const { return tfLayout_; } const dnnLayout_t GetCurLayout() const { return isMklTensor_ ? mklLayout_ : tfLayout_; } size_t GetDimension() const { return dimension_; } const size_t* GetSizes() const { return sizes_; } int64 dim_size(int index) const { return sizes_[index]; } int64 tf_dim_size(int index) const { return sizes_[tf_to_mkl_dim_map_[index]]; } const size_t* GetStrides() const { return strides_; } const size_t* GetTfToMklDimMap() const { return tf_to_mkl_dim_map_; } size_t tf_dim_idx(int index) const { return tf_to_mkl_dim_map_[index]; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Channel dimension. bool IsMklChannelDim(int d) const { return tf_dim_idx(d) == MklDims::C; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Batch dimension. bool IsMklBatchDim(int d) const { return tf_dim_idx(d) == MklDims::N; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Width dimension. bool IsMklWidthDim(int d) const { return tf_dim_idx(d) == MklDims::W; } // Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' // corresponds to MKL's Height dimension. bool IsMklHeightDim(int d) const { return tf_dim_idx(d) == MklDims::H; } // Check if the TF-Mkl dimension ordering map specifies if the input // tensor is in NCHW format. bool IsTensorInNCHWFormat() const { TensorFormat data_format = FORMAT_NCHW; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } // Check if the TF-Mkl dimension ordering map specifies if the input // tensor is in NHWC format. bool IsTensorInNHWCFormat() const { TensorFormat data_format = FORMAT_NHWC; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } void GetConvertedFlatData(dnnLayout_t targetLayout, void* input, void* output) const { dnnLayout_t curLayout; if (isMklTensor_) curLayout = mklLayout_; else curLayout = tfLayout_; dnnPrimitive_t convert; CHECK_EQ(dnnConversionCreate_F32(&convert, curLayout, targetLayout), E_SUCCESS); CHECK_EQ(dnnConversionExecute_F32(convert, input, output), E_SUCCESS); CHECK_EQ(dnnDelete_F32(convert), E_SUCCESS); } // The following methods are used for serializing and de-serializing the // contents of the mklshape object. // The data is serialized in this order // isMklTensor_ // dimension_ // sizes_ // strides_ // mklLayout_ // tfLayout_ // tf_to_mkl_dim_map_ #define SIZE_OF_MKL_DNN_BUF \ (dnnLayoutSerializationBufferSize_F32()) // Size of buffer needed to // serialize dnn_layout pointer // Size of buffer to hold the serialized object, the size is computed as // follows sizeof(isMklTensor_) + sizeof(dimension_) + sizeof(sizes_) + // sizeof(strides_) // + sizeof(mklLayout_ buffer) + sizeof(tfLayout_ buffer) // + sizeof(tf_to_mkl_dim_map_) #define SIZE_OF_MKL_SERIAL_DATA(dims) \ (2 * sizeof(size_t) + 3 * dims * sizeof(size_t) + 2 * SIZE_OF_MKL_DNN_BUF) // First we need to define some macro for offsets into the serial buffer where // different elements of Mklshape is written/read from #define IS_MKL_TENSOR_OFFSET 0 // Location from start of buffer where isMklTensor_ is serialized #define DIMS_OFFSET \ (IS_MKL_TENSOR_OFFSET + sizeof(size_t)) // Location of dimension_ // Location of sizes. Note dim is not used here, left here // to make macros consistent. #define SIZES_OFFSET(dims) (DIMS_OFFSET + sizeof(size_t)) #define STRIDES_OFFSET(dims) \ (SIZES_OFFSET(dims) + dims * sizeof(size_t)) // Location of strides #define MKL_LAYOUT_OFFSET(dims) \ (STRIDES_OFFSET(dims) + dims * sizeof(size_t)) // Location of mklLayout_ #define TF_LAYOUT_OFFSET(dims) \ (MKL_LAYOUT_OFFSET(dims) + SIZE_OF_MKL_DNN_BUF) // Location of tfLayout_ // Location of tf_to_mkl_dim_map_ #define TF_TO_MKL_DIM_MAP_OFFSET(dims) \ (TF_LAYOUT_OFFSET(dims) + SIZE_OF_MKL_DNN_BUF) // TODO(agramesh1) make sure to create a const to share with rewrite pass // for min size of MKL metadata tensor. void DeSerializeMklShape(const unsigned char* buf, size_t buf_size) { CHECK(buf_size >= sizeof(size_t)) << "Bufsize too small in DeSerialize"; // Make sure buffer holds at least isMklTensor_ isMklTensor_ = *reinterpret_cast<const size_t*>(buf + IS_MKL_TENSOR_OFFSET) != 0; if (isMklTensor_) { // If it is an MKL Tensor then read the rest dimension_ = *(reinterpret_cast<const size_t*>(buf + DIMS_OFFSET)); CHECK(buf_size >= SIZE_OF_MKL_SERIAL_DATA(dimension_)) << "Bufsize too small in DeSerialize"; sizes_ = new size_t[dimension_]; strides_ = new size_t[dimension_]; tf_to_mkl_dim_map_ = new size_t[dimension_]; for (int i = 0; i < dimension_; i++) { sizes_[i] = reinterpret_cast<const size_t*>(buf + SIZES_OFFSET(dimension_))[i]; strides_[i] = reinterpret_cast<const size_t*>( buf + STRIDES_OFFSET(dimension_))[i]; tf_to_mkl_dim_map_[i] = reinterpret_cast<const size_t*>( buf + TF_TO_MKL_DIM_MAP_OFFSET(dimension_))[i]; } CHECK_EQ(dnnLayoutDeserialize_F32(&mklLayout_, buf + MKL_LAYOUT_OFFSET(dimension_)), E_SUCCESS); CHECK_EQ(dnnLayoutDeserialize_F32(&tfLayout_, buf + TF_LAYOUT_OFFSET(dimension_)), E_SUCCESS); } } void SerializeMklShape(unsigned char* buf, size_t buf_size) const { CHECK(buf_size >= SIZE_OF_MKL_SERIAL_DATA(dimension_)) << "Bufsize too small to Serialize"; *reinterpret_cast<size_t*>(buf + IS_MKL_TENSOR_OFFSET) = isMklTensor_ ? 1 : 0; if (isMklTensor_) { *(reinterpret_cast<size_t*>(buf + DIMS_OFFSET)) = dimension_; for (int i = 0; i < dimension_; i++) { reinterpret_cast<size_t*>(buf + SIZES_OFFSET(dimension_))[i] = sizes_[i]; reinterpret_cast<size_t*>(buf + STRIDES_OFFSET(dimension_))[i] = strides_[i]; reinterpret_cast<size_t*>(buf + TF_TO_MKL_DIM_MAP_OFFSET(dimension_))[i] = tf_to_mkl_dim_map_[i]; } CHECK_EQ(dnnLayoutSerialize_F32(mklLayout_, buf + MKL_LAYOUT_OFFSET(dimension_)), E_SUCCESS); CHECK_EQ( dnnLayoutSerialize_F32(tfLayout_, buf + TF_LAYOUT_OFFSET(dimension_)), E_SUCCESS); } } private: bool isMklTensor_ = false; // Flag to indicate if the tensor is an MKL tensor or not dnnLayout_t mklLayout_ = nullptr; // Pointer to the MKL layout dnnLayout_t tfLayout_ = nullptr; // Pointer to layout of corresponding // Tensorflow tensor, used when conversion from MKL to standard tensor size_t dimension_ = 0; size_t* sizes_ = nullptr; // Required by MKL for conversions size_t* strides_ = nullptr; // Required by MKL for conversions size_t* tf_to_mkl_dim_map_ = nullptr; // TF dimension corresponding to this MKL dimension }; #else // Forward decl TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format); memory::dims CalculateTFStrides(const memory::dims& dims_tf_order); memory::desc CreateBlockedMemDescHelper(const memory::dims& dim, const memory::dims& strides, memory::data_type dtype); class MklDnnShape { private: typedef struct { /// Flag to indicate if the tensor is an MKL tensor or not bool is_mkl_tensor_ = false; /// Number of dimensions in Tensorflow format size_t dimension_ = 0; /// Required by MKLDNN for conversions mkldnn_dims_t sizes_; // Required by MKL for conversions memory::format tf_data_format_ = memory::format::format_undef; memory::data_type T_ = memory::data_type::data_undef; // MKL layout mkldnn_memory_desc_t mkl_md_; /// TF dimension corresponding to this MKL dimension mkldnn_dims_t map_; } MklShapeData; MklShapeData data_; typedef std::remove_extent<mkldnn_dims_t>::type mkldnn_dim_t; #define INVALID_DIM_SIZE -1 public: MklDnnShape() { for (size_t i = 0; i < sizeof(data_.sizes_) / sizeof(data_.sizes_[0]); ++i) { data_.sizes_[i] = -1; } for (size_t i = 0; i < sizeof(data_.map_) / sizeof(data_.map_[0]); ++i) { data_.map_[i] = -1; } } ~MklDnnShape() {} TF_DISALLOW_COPY_AND_ASSIGN(MklDnnShape); // Cannot copy /// Helper function to compare memory::desc objects for MklDnn. /// May be this should go into MklDnn directly. inline bool CompareMklDnnLayouts(const memory::desc& md1, const memory::desc& md2) const { mkldnn_memory_desc_t mdd1 = md1.data; mkldnn_memory_desc_t mdd2 = md2.data; const char* d1 = reinterpret_cast<const char*>(&mdd1); const char* d2 = reinterpret_cast<const char*>(&mdd2); size_t md_size = sizeof(mdd1); for (size_t i = 0; i < md_size; i++) { if (*d1++ != *d2++) { return false; } } return true; } /// Equality function for MklDnnShape objects /// @return true if both are equal; false otherwise. inline bool operator==(const MklDnnShape& input_shape) const { if (this->IsMklTensor() != input_shape.IsMklTensor()) { return false; } // If input tensors are in Mkl layout, then we check for dimensions and // sizes. if (this->IsMklTensor()) { return this->GetTfShape() == input_shape.GetTfShape() && CompareMklDnnLayouts(this->GetMklLayout(), input_shape.GetMklLayout()); } return true; } /// Equality operator for MklDnnShape and TFShape. /// Returns: true if TF shapes for both are the same, false otherwise inline bool operator==(const TensorShape& input_shape) const { if (!this->IsMklTensor()) { return false; } return this->GetTfShape() == input_shape; } inline const bool IsMklTensor() const { return data_.is_mkl_tensor_; } inline void SetMklTensor(bool is_mkl_tensor) { data_.is_mkl_tensor_ = is_mkl_tensor; } inline void SetDimensions(const size_t dimension) { data_.dimension_ = dimension; } inline size_t GetDimension(char dimension) const { int index = GetMklDnnTensorDimIndex(dimension); CHECK(index >= 0 && index < this->GetDimension()) << "Invalid index from the dimension: " << index << ", " << dimension; return this->DimSize(index); } inline int32 GetMklDnnTensorDimIndex(char dimension) const { switch (dimension) { case 'N': return MklDnnDims::Dim_N; case 'C': return MklDnnDims::Dim_C; case 'H': return MklDnnDims::Dim_H; case 'W': return MklDnnDims::Dim_W; default: LOG(FATAL) << "Invalid dimension: " << dimension; return -1; // Avoid compiler warning about missing return value } } inline size_t GetDimension() const { return data_.dimension_; } inline const int* GetSizes() const { return reinterpret_cast<const int*>(&data_.sizes_[0]); } // Returns an mkldnn::memory::dims object that contains the sizes of this // MklDnnShape object. inline memory::dims GetSizesAsMklDnnDims() const { memory::dims retVal; if (data_.is_mkl_tensor_) { size_t dimensions = sizeof(data_.sizes_) / sizeof(data_.sizes_[0]); for (size_t i = 0; i < dimensions; i++) { if (data_.sizes_[i] != INVALID_DIM_SIZE) retVal.push_back(data_.sizes_[i]); } } else { CHECK_EQ(data_.is_mkl_tensor_, true); } return retVal; } inline int64 DimSize(int index) const { CHECK_LT(index, sizeof(data_.sizes_) / sizeof(data_.sizes_[0])); return data_.sizes_[index]; } /// Return TensorShape that describes the Tensorflow shape of the tensor /// represented by this MklShape. inline TensorShape GetTfShape() const { CHECK_EQ(data_.is_mkl_tensor_, true); std::vector<int32> shape(data_.dimension_, -1); if (data_.tf_data_format_ != memory::format::blocked) { for (size_t idx = 0; idx < data_.dimension_; ++idx) { shape[idx] = data_.sizes_[TfDimIdx(idx)]; } } else { // If Tensorflow shape is in Blocked format, then we don't have dimension // map for it. So we just create Tensorflow shape from sizes in the // specified order. for (size_t idx = 0; idx < data_.dimension_; ++idx) { shape[idx] = data_.sizes_[idx]; } } TensorShape ts; bool ret = TensorShapeUtils::MakeShape(shape, &ts).ok(); CHECK_EQ(ret, true); return ts; } inline void SetElemType(memory::data_type dt) { data_.T_ = dt; } inline const memory::data_type GetElemType() { return data_.T_; } inline void SetMklLayout(memory::primitive_desc* pd) { CHECK_NOTNULL(pd); data_.mkl_md_ = pd->desc().data; } inline void SetMklLayout(memory::desc* md) { CHECK_NOTNULL(md); data_.mkl_md_ = md->data; } inline const memory::desc GetMklLayout() const { return memory::desc(data_.mkl_md_); } inline memory::format GetTfDataFormat() const { return data_.tf_data_format_; } /// We don't create primitive_descriptor for TensorFlow layout now. /// We use lazy evaluation and create it only when needed. Input format can /// also be Blocked format. inline void SetTfLayout(size_t dims, const memory::dims& sizes, memory::format format) { CHECK_EQ(dims, sizes.size()); data_.dimension_ = dims; for (size_t ii = 0; ii < dims; ii++) { data_.sizes_[ii] = sizes[ii]; } data_.tf_data_format_ = format; if (format != memory::format::blocked) { SetTfDimOrder(dims, format); } } inline const memory::desc GetTfLayout() const { memory::dims dims; for (size_t ii = 0; ii < data_.dimension_; ii++) { dims.push_back(data_.sizes_[ii]); } // Create Blocked memory desc if input TF format was set like that. if (data_.tf_data_format_ == memory::format::blocked) { auto strides = CalculateTFStrides(dims); return CreateBlockedMemDescHelper(dims, strides, data_.T_); } else { return memory::desc(dims, data_.T_, data_.tf_data_format_); } } inline const memory::desc GetCurLayout() const { return IsMklTensor() ? GetMklLayout() : GetTfLayout(); } // nhasabni - I've removed SetTfDimOrder that was setting default order in // case of MKL-ML. We don't need a case of default dimension order because // when an operator that does not get data_format attribute gets all inputs // in Tensorflow format, it will produce output in Tensorflow format. inline void SetTfDimOrder(const size_t dimension, const mkldnn_dims_t map) { CHECK(dimension == data_.dimension_); for (size_t ii = 0; ii < dimension; ii++) { data_.map_[ii] = map[ii]; } } inline void SetTfDimOrder(const size_t dimension, TensorFormat data_format) { // TODO(nhasabni): Why do we restrict this to 4D? CHECK_EQ(dimension, 4); CHECK(dimension == data_.dimension_); data_.map_[GetTensorDimIndex<2>(data_format, 'W')] = MklDnnDims::Dim_W; data_.map_[GetTensorDimIndex<2>(data_format, 'H')] = MklDnnDims::Dim_H; data_.map_[GetTensorDimIndex<2>(data_format, 'C')] = MklDnnDims::Dim_C; data_.map_[GetTensorDimIndex<2>(data_format, 'N')] = MklDnnDims::Dim_N; } inline void SetTfDimOrder(const size_t dimension, memory::format format) { TensorFormat data_format = MklDnnDataFormatToTFDataFormat(format); SetTfDimOrder(dimension, data_format); } inline const mkldnn_dim_t* GetTfToMklDimMap() const { return &data_.map_[0]; } inline size_t TfDimIdx(int index) const { return data_.map_[index]; } inline int64 TfDimSize(int index) const { return data_.sizes_[TfDimIdx(index)]; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Channel dimension. inline bool IsMklChannelDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_C; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Batch dimension. inline bool IsMklBatchDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_N; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Width dimension. inline bool IsMklWidthDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_W; } /// Query TF-MKL dimension ordering map and check if Tensorflow dimension 'd' /// corresponds to MKL's Height dimension. inline bool IsMklHeightDim(int d) const { return TfDimIdx(d) == MklDnnDims::Dim_H; } /// Check if the TF-Mkl dimension ordering map specifies if the input /// tensor is in NCHW format. inline bool IsTensorInNCHWFormat() const { TensorFormat data_format = FORMAT_NCHW; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } /// Check if the TF-Mkl dimension ordering map specifies if the input /// tensor is in NHWC format. inline bool IsTensorInNHWCFormat() const { TensorFormat data_format = FORMAT_NHWC; return (IsMklBatchDim(GetTensorDimIndex<2>(data_format, 'N')) && IsMklChannelDim(GetTensorDimIndex<2>(data_format, 'C')) && IsMklHeightDim(GetTensorDimIndex<2>(data_format, 'H')) && IsMklWidthDim(GetTensorDimIndex<2>(data_format, 'W'))); } /// The following methods are used for serializing and de-serializing the /// contents of the mklshape object. /// The data is serialized in this order /// is_mkl_tensor_ : dimension_ : sizes_ : map_: format_ : T_ : mkl_pd_; /// Size of buffer to hold the serialized object, the size is computed by /// following above mentioned order inline size_t GetSerializeBufferSize() const { return sizeof(MklShapeData); } void SerializeMklDnnShape(unsigned char* buf, size_t buf_size) const { CHECK(buf_size >= GetSerializeBufferSize()) << "Buffer size is too small to SerializeMklDnnShape"; *reinterpret_cast<MklShapeData*>(buf) = data_; } void DeSerializeMklDnnShape(const unsigned char* buf, size_t buf_size) { // Make sure buffer holds at least is_mkl_tensor_. CHECK(buf_size >= sizeof(data_.is_mkl_tensor_)) << "Buffer size is too small in DeSerializeMklDnnShape"; const bool is_mkl_tensor = *reinterpret_cast<const bool*>(buf); if (is_mkl_tensor) { // If it is an MKL Tensor then read the rest CHECK(buf_size >= GetSerializeBufferSize()) << "Buffer size is too small in DeSerializeMklDnnShape"; data_ = *reinterpret_cast<const MklShapeData*>(buf); } } }; #endif // List of MklShape objects. Used in Concat/Split layers. #ifndef INTEL_MKL_ML typedef std::vector<MklDnnShape> MklDnnShapeList; #else typedef std::vector<MklShape> MklShapeList; #endif #ifdef INTEL_MKL_ML // Check if all tensors specified by MklShapes are MKL tensors. inline bool AreAllMklTensors(const MklShapeList& shapes) { for (auto& s : shapes) { if (!s.IsMklTensor()) { return false; } } return true; } template <typename T> inline Tensor ConvertMklToTF(OpKernelContext* context, const Tensor& mkl_tensor, const MklShape& mkl_shape) { Tensor output_tensor; TensorShape output_shape; for (size_t j = 0; j < mkl_shape.GetDimension(); j++) { // Outermost to innermost dimension output_shape.AddDim(mkl_shape.GetSizes()[mkl_shape.tf_dim_idx(j)]); } // Allocate output tensor. context->allocate_temp(DataTypeToEnum<T>::v(), output_shape, &output_tensor); dnnLayout_t output_layout = static_cast<dnnLayout_t>(mkl_shape.GetTfLayout()); void* input_buffer = const_cast<T*>(mkl_tensor.flat<T>().data()); void* output_buffer = const_cast<T*>(output_tensor.flat<T>().data()); if (mkl_tensor.NumElements() != 0) { mkl_shape.GetConvertedFlatData(output_layout, input_buffer, output_buffer); } return output_tensor; } #else using mkldnn::stream; template <typename T> class MklDnnData; template <typename T> inline Tensor ConvertMklToTF(OpKernelContext* context, const Tensor& mkl_tensor, const MklDnnShape& mkl_shape) { Tensor output_tensor; try { if (!mkl_shape.IsMklTensor()) return mkl_tensor; // return input since it is already TF tensor TensorShape output_shape = mkl_shape.GetTfShape();; // Allocate output tensor. context->allocate_temp(DataTypeToEnum<T>::v(), output_shape, &output_tensor); auto cpu_engine = engine(engine::cpu, 0); MklDnnData<T> input(&cpu_engine); // Get Mkl layout of input tensor. auto input_mkl_md = mkl_shape.GetMklLayout(); auto output_tf_md = mkl_shape.GetTfLayout(); auto output_tf_pd = memory::primitive_desc(output_tf_md, cpu_engine); input.SetUsrMem(input_mkl_md, &mkl_tensor); // reorder if (input.IsReorderNeeded(output_tf_pd)) { std::vector<primitive> net; CHECK_EQ(input.CheckReorderToOpMem(output_tf_pd, &output_tensor, &net), true); stream(stream::kind::eager).submit(net).wait(); } else { // If not, just forward input tensor to output tensor. CHECK(output_tensor.CopyFrom(mkl_tensor, output_shape)); } } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); LOG(FATAL) << "Operation received an exception: " << error_msg; } return output_tensor; } #endif // Get the MKL shape from the second string tensor #ifdef INTEL_MKL_ML inline void GetMklShape(OpKernelContext* ctext, int n, MklShape* mklshape) { mklshape->DeSerializeMklShape( ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .data(), ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .size() * sizeof(uint8)); } #else inline void GetMklShape(OpKernelContext* ctext, int n, MklDnnShape* mklshape) { mklshape->DeSerializeMklDnnShape( ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .data(), ctext->input(GetTensorMetaDataIndex(n, ctext->num_inputs())) .flat<uint8>() .size() * sizeof(uint8)); } #endif // Gets the actual input inline const Tensor& MklGetInput(OpKernelContext* ctext, int n) { return ctext->input(GetTensorDataIndex(n, ctext->num_inputs())); } inline void GetMklInputList(OpKernelContext* ctext, StringPiece name, OpInputList* input_tensors) { CHECK_NOTNULL(input_tensors); ctext->input_list(name, input_tensors); } #ifdef INTEL_MKL_ML inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name, MklShapeList* mkl_shapes) { OpInputList input_mkl_tensors; GetMklInputList(ctext, strings::StrCat("mkl_", name), &input_mkl_tensors); for (int i = 0; i < input_mkl_tensors.size(); i++) { (*mkl_shapes)[i].DeSerializeMklShape( input_mkl_tensors[i].flat<uint8>().data(), input_mkl_tensors[i].flat<uint8>().size() * sizeof(uint8)); } } #else inline void GetMklShapeList(OpKernelContext* ctext, StringPiece name, MklDnnShapeList* mkl_shapes) { OpInputList input_mkl_tensors; GetMklInputList(ctext, strings::StrCat("mkl_", name), &input_mkl_tensors); for (int i = 0; i < input_mkl_tensors.size(); i++) { (*mkl_shapes)[i].DeSerializeMklDnnShape( input_mkl_tensors[i].flat<uint8>().data(), input_mkl_tensors[i].flat<uint8>().size() * sizeof(uint8)); } } #endif #ifndef INTEL_MKL_ML /// Get shape of input tensor pointed by 'input_idx' in TensorShape format. /// If the input tensor is in MKL layout, then obtains TensorShape from /// MklShape. inline TensorShape GetTfShape(OpKernelContext* context, size_t input_idx) { // Sanity check. CHECK_NOTNULL(context); CHECK_LT(input_idx, context->num_inputs()); MklDnnShape input_mkl_shape; GetMklShape(context, input_idx, &input_mkl_shape); if (input_mkl_shape.IsMklTensor()) { return input_mkl_shape.GetTfShape(); } else { const Tensor& t = MklGetInput(context, input_idx); return t.shape(); } } #endif #ifdef INTEL_MKL_ML // Allocate the second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, const MklShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(SIZE_OF_MKL_SERIAL_DATA(mkl_shape.GetDimension())); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #else // Allocate the second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, const MklDnnShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(mkl_shape.GetSerializeBufferSize()); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklDnnShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #endif #ifdef INTEL_MKL_ML // Allocate the output tensor, create a second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, Tensor** output, const TensorShape& tf_shape, const MklShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(SIZE_OF_MKL_SERIAL_DATA(mkl_shape.GetDimension())); OP_REQUIRES_OK( ctext, ctext->allocate_output(GetTensorDataIndex(n, ctext->num_outputs()), tf_shape, output)); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #else // Allocate the output tensor, create a second output tensor that will contain // the MKL shape serialized inline void AllocateOutputSetMklShape(OpKernelContext* ctext, int n, Tensor** output, const TensorShape& tf_shape, const MklDnnShape& mkl_shape) { Tensor* second_tensor = nullptr; TensorShape second_shape; second_shape.AddDim(mkl_shape.GetSerializeBufferSize()); OP_REQUIRES_OK( ctext, ctext->allocate_output(GetTensorDataIndex(n, ctext->num_outputs()), tf_shape, output)); OP_REQUIRES_OK(ctext, ctext->allocate_output( GetTensorMetaDataIndex(n, ctext->num_outputs()), second_shape, &second_tensor)); mkl_shape.SerializeMklDnnShape( second_tensor->flat<uint8>().data(), second_tensor->flat<uint8>().size() * sizeof(uint8)); } #endif // Allocates a temp tensor and returns the data buffer for temporary storage. // Currently #ifndef INTEL_MKL_ML template <typename T> inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, const memory::primitive_desc& pd, void** buf_out) { TensorShape tf_shape; tf_shape.AddDim(pd.get_size() / sizeof(T) + 1); OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::v(), tf_shape, tensor_out)); *buf_out = static_cast<void*>(tensor_out->flat<T>().data()); } #else inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, dnnLayout_t lt_buff, void** buf_out) { TensorShape tf_shape; tf_shape.AddDim( dnnLayoutGetMemorySize_F32(static_cast<dnnLayout_t>(lt_buff)) / sizeof(float) + 1); OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<float>::v(), tf_shape, tensor_out)); *buf_out = static_cast<void*>(tensor_out->flat<float>().data()); } #endif template <typename T> inline void AllocTmpBuffer(OpKernelContext* context, Tensor* tensor_out, TensorShape tf_shape) { OP_REQUIRES_OK(context, context->allocate_temp(DataTypeToEnum<T>::v(), tf_shape, tensor_out)); } inline void GetStridesFromSizes(TensorFormat data_format, size_t* strides, const size_t* sizes) { // MKL requires strides in NCHW if (data_format == FORMAT_NHWC) { strides[0] = sizes[2]; strides[1] = sizes[0] * sizes[2]; strides[2] = 1; strides[3] = sizes[0] * sizes[1] * sizes[2]; } else { strides[0] = 1; strides[1] = sizes[0]; strides[2] = sizes[0] * sizes[1]; strides[3] = sizes[0] * sizes[1] * sizes[2]; } } #ifdef INTEL_MKL_ML inline void MklSizesToTFSizes(OpKernelContext* context, TensorFormat data_format_, const MklShape& mkl_shape, TensorShape* tf_shape) { size_t tf_dim = mkl_shape.GetDimension(); const size_t* tf_sizes = mkl_shape.GetSizes(); OP_REQUIRES(context, tf_dim == 4, errors::InvalidArgument("MKLSizesToTFSizes: size must be 4-dim")); std::vector<int32> sizes; sizes.push_back(tf_sizes[3]); if (data_format_ == FORMAT_NHWC) { sizes.push_back(tf_sizes[1]); sizes.push_back(tf_sizes[0]); sizes.push_back(tf_sizes[2]); } else { sizes.push_back(tf_sizes[2]); sizes.push_back(tf_sizes[1]); sizes.push_back(tf_sizes[0]); } OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(sizes, tf_shape)); } #endif inline int32 GetMklTensorDimIndex(char dimension) { switch (dimension) { case 'N': return MklDims::N; case 'C': return MklDims::C; case 'H': return MklDims::H; case 'W': return MklDims::W; default: LOG(FATAL) << "Invalid dimension: " << dimension; return -1; // Avoid compiler warning about missing return value } } #ifdef INTEL_MKL_ML inline int64 GetMklTensorDim(const MklShape& mkl_shape, char dimension) { int index = GetMklTensorDimIndex(dimension); CHECK(index >= 0 && index < mkl_shape.GetDimension()) << "Invalid index from the dimension: " << index << ", " << dimension; return mkl_shape.dim_size(index); } #endif inline void CopyMklTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_meta_in = GetTensorMetaDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); int idx_meta_out = GetTensorMetaDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); const Tensor& meta = context->input(idx_meta_in); Tensor output(data.dtype()); Tensor meta_output(meta.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, data.shape())); CHECK(meta_output.CopyFrom(meta, meta.shape())); context->set_output(idx_data_out, output); context->set_output(idx_meta_out, meta_output); } #ifdef INTEL_MKL_ML inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in, int idx_out, const TensorShape& shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); Tensor output(data.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, shape)); context->set_output(idx_data_out, output); } #else inline void CopyTfTensorInToOutWithShape(OpKernelContext* context, int idx_in, int idx_out, const TensorShape& shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); const Tensor& data = context->input(idx_data_in); MklDnnShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); Tensor output(data.dtype()); // TODO(intel_tf): alternatively, call forward_input_to_output_with_shape(...) CHECK(output.CopyFrom(data, shape)); context->set_output(idx_data_out, output); } #endif #ifdef INTEL_MKL_ML inline void ForwardTfTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, mkl_shape_output); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #else inline void ForwardTfTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); MklDnnShape dnn_shape_output; dnn_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_out, dnn_shape_output); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #endif inline void ForwardMklTensorInToOut(OpKernelContext* context, int idx_in, int idx_out) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_meta_in = GetTensorMetaDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); int idx_meta_out = GetTensorMetaDataIndex(idx_out, num_outputs); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); context->forward_ref_input_to_ref_output(idx_meta_in, idx_meta_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); context->set_output(idx_meta_out, context->input(idx_meta_in)); } } #ifndef INTEL_MKL_ML // Set a dummy MKLDNN shape (called when the output is in TF format) inline void SetDummyMklDnnShapeOutput(OpKernelContext* context, uint32 idx_data_out) { MklDnnShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_data_out, mkl_shape_output); } inline void ForwardMklTensorInToOutWithMklShape(OpKernelContext* context, int idx_in, int idx_out, const MklDnnShape& mkl_shape) { int num_inputs = context->num_inputs(); int num_outputs = context->num_outputs(); int idx_data_in = GetTensorDataIndex(idx_in, num_inputs); int idx_data_out = GetTensorDataIndex(idx_out, num_outputs); AllocateOutputSetMklShape(context, idx_out, mkl_shape); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_data_in, idx_data_out); } else { context->set_output(idx_data_out, context->input(idx_data_in)); } } #endif // Forward the MKL shape ONLY (used in elementwise and other ops where // we call the eigen implementation and MKL shape is not used) inline void ForwardMklMetaDataInToOut(OpKernelContext* context, uint32 idx_data_in, uint32_t idx_data_out) { uint32 idx_meta_in = GetTensorMetaDataIndex(idx_data_in, context->num_inputs()); uint32 idx_meta_out = GetTensorMetaDataIndex(idx_data_out, context->num_outputs()); if (IsRefType(context->input_dtype(idx_data_in))) { context->forward_ref_input_to_ref_output(idx_meta_in, idx_meta_out); } else { context->set_output(idx_meta_out, context->input(idx_meta_in)); } } #ifdef INTEL_MKL_ML // Set a dummy MKL shape (called when the output is in TF format) inline void SetDummyMklShapeOutput(OpKernelContext* context, uint32 idx_data_out) { MklShape mkl_shape_output; mkl_shape_output.SetMklTensor(false); AllocateOutputSetMklShape(context, idx_data_out, mkl_shape_output); } // We don't need these functions in MKLDNN. We have defined equality operator // on MklDnnShape class directly. // Checks if the TF shape for both MKL tensors is the same or not // Returns: true if both TF shapes are the same, false otherwise inline bool MklCompareShapes(const MklShape* input_shape_0, const MklShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->GetDimension() != input_shape_1->GetDimension()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->GetDimension(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const MklShape* input_shape_0, const TensorShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->GetDimension() != input_shape_1->dims()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->GetDimension(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->tf_dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const TensorShape* input_shape_0, const MklShape* input_shape_1) { return MklCompareShapes(input_shape_1, input_shape_0); } // Checks if the TF shape for both tensors is the same or not // Returns: true if TF shapes for both are the same, false otherwise inline bool MklCompareShapes(const TensorShape* input_shape_0, const TensorShape* input_shape_1) { // Check for number of dimensions if (input_shape_0->dims() != input_shape_1->dims()) { return false; } // Check size of each dimension size_t ndims = input_shape_0->dims(); for (size_t i = 0; i < ndims; i++) { if (input_shape_0->dim_size(i) != input_shape_1->dim_size(i)) { return false; } } return true; } // These functions do not compile with MKL-DNN since mkl.h is missing. // We may need to remove them later. // TODO(intel_tf): Remove this routine when faster MKL layout conversion is // out. inline void MklNHWCToNCHW(const Tensor& input, Tensor** output) { const float* buf_in = input.flat<float>().data(); float* buf_out = (*output)->flat<float>().data(); int64 N = input.dim_size(0); int64 H = input.dim_size(1); int64 W = input.dim_size(2); int64 C = input.dim_size(3); int64 stride_n = H * W * C; #pragma omp parallel for num_threads(16) for (int64 n = 0; n < N; ++n) { mkl_somatcopy('R', 'T', H * W, C, 1, buf_in + n * stride_n, C, buf_out + n * stride_n, H * W); } } inline void MklNCHWToNHWC(const Tensor& input, Tensor** output) { const float* buf_in = input.flat<float>().data(); float* buf_out = (*output)->flat<float>().data(); int64 N = (*output)->dim_size(0); int64 H = (*output)->dim_size(1); int64 W = (*output)->dim_size(2); int64 C = (*output)->dim_size(3); int64 stride_n = H * W * C; #pragma omp parallel for num_threads(16) for (int64 n = 0; n < N; ++n) { mkl_somatcopy('R', 'T', C, H * W, 1, buf_in + n * stride_n, H * W, buf_out + n * stride_n, C); } } #endif // ------------------------------------------------------------------- #ifndef INTEL_MKL_ML /// Return MKL-DNN data type (memory::data_type) for input type T /// /// @input None /// @return memory::data_type corresponding to type T template <typename T> static memory::data_type MklDnnType(); /// Instantiation for float type. Add similar instantiations for other /// type if needed. template <> memory::data_type MklDnnType<float>() { return memory::data_type::f32; } /// Map TensorFlow's data format into MKL-DNN data format /// /// @input: TensorFlow data format /// @return: memory::format corresponding to TensorFlow data format; /// Fails with an error if invalid data format. inline memory::format TFDataFormatToMklDnnDataFormat(TensorFormat format) { if (format == FORMAT_NHWC) return memory::format::nhwc; else if (format == FORMAT_NCHW) return memory::format::nchw; TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format")); // Return to get rid of compiler warning return memory::format::format_undef; } /// Map MKL-DNN data format to TensorFlow's data format /// /// @input: memory::format /// @return: Tensorflow data format corresponding to memory::format /// Fails with an error if invalid data format. inline TensorFormat MklDnnDataFormatToTFDataFormat(memory::format format) { if (format == memory::format::nhwc) return FORMAT_NHWC; else if (format == memory::format::nchw) return FORMAT_NCHW; TF_CHECK_OK(Status(error::Code::INVALID_ARGUMENT, "Unsupported data format")); // Return to prevent compiler warnings, otherwise TF_CHECK_OK will ensure // that we don't come here. return FORMAT_NHWC; } /// Map TensorShape object into memory::dims required by MKL-DNN /// /// This function will simply map input TensorShape into MKL-DNN dims /// naively. So it will preserve the order of dimensions. E.g., if /// input tensor is in NHWC format, then dims will be in NHWC format /// also. /// /// @input TensorShape object in shape /// @return memory::dims corresponding to TensorShape inline memory::dims TFShapeToMklDnnDims(const TensorShape& shape) { memory::dims dims(shape.dims()); for (int d = 0; d < shape.dims(); ++d) { dims[d] = shape.dim_size(d); } return dims; } /// Map TensorShape object into memory::dims in NCHW format required by MKL-DNN /// /// This function is a specific one than above function. It will map input /// TensorShape into MKL-DNN dims in NCHW format. So it may not preserve the /// order of dimensions. E.g., if input tensor is in NHWC format, then dims /// will be in NCHW format, and not in NHWC format. /// /// @input TensorShape object in shape /// @return memory::dims in MKL-DNN required NCHW format inline memory::dims TFShapeToMklDnnDimsInNCHW(const TensorShape& shape, TensorFormat format) { // Check validity of format. CHECK_NE(TFDataFormatToMklDnnDataFormat(format), memory::format::format_undef); int n = shape.dim_size(GetTensorDimIndex(format, 'N')); int c = shape.dim_size(GetTensorDimIndex(format, 'C')); int h = shape.dim_size(GetTensorDimIndex(format, 'H')); int w = shape.dim_size(GetTensorDimIndex(format, 'W')); // MKL-DNN requires dimensions in NCHW format. return memory::dims({n, c, h, w}); } /// Overloaded version of function above. Input parameters are /// self-explanatory. inline memory::dims MklDnnDimsInNCHW(const memory::dims& in_dims, TensorFormat format) { // Check validity of format. CHECK_NE(TFDataFormatToMklDnnDataFormat(format), memory::format::format_undef); int n = in_dims[GetTensorDimIndex(format, 'N')]; int c = in_dims[GetTensorDimIndex(format, 'C')]; int h = in_dims[GetTensorDimIndex(format, 'H')]; int w = in_dims[GetTensorDimIndex(format, 'W')]; // MKL-DNN requires dimensions in NCHW format. return memory::dims({n, c, h, w}); } /// Map MklDnn memory::dims object into TensorShape object. /// /// This function will simply map input shape in MKL-DNN memory::dims format /// in Tensorflow's TensorShape object by preserving dimension order. /// /// @input MKL-DNN memory::dims object /// @output TensorShape corresponding to memory::dims inline TensorShape MklDnnDimsToTFShape(const memory::dims& dims) { std::vector<int32> shape(dims.size(), -1); for (int d = 0; d < dims.size(); d++) { shape[d] = dims[d]; } TensorShape ret; CHECK_EQ(TensorShapeUtils::MakeShape(shape, &ret).ok(), true); return ret; } /// Function to calculate strides given tensor shape in Tensorflow order /// E.g., if dims_tf_order is {1, 2, 3, 4}, then as per Tensorflow convention, /// dimesion with size 1 is outermost dimension; while dimension with size 4 is /// innermost dimension. So strides for this tensor would be {4 * 3 * 2, /// 4 * 3, 4, 1}, i.e., {24, 12, 4, 1}. /// /// @input Tensorflow shape in memory::dims type /// @return memory::dims containing strides for the tensor. inline memory::dims CalculateTFStrides(const memory::dims& dims_tf_order) { CHECK_GT(dims_tf_order.size(), 0); memory::dims strides(dims_tf_order.size()); int last_dim_idx = dims_tf_order.size() - 1; strides[last_dim_idx] = 1; for (int d = last_dim_idx - 1; d >= 0; d--) { strides[d] = strides[d + 1] * dims_tf_order[d + 1]; } return strides; } inline padding_kind TFPaddingToMklDnnPadding(Padding pad) { // MKL-DNN only supports zero padding. return padding_kind::zero; } /// Helper function to create memory descriptor in Blocked format /// /// @input: Tensor dimensions /// @input: strides corresponding to dimensions. One can use utility /// function such as CalculateTFStrides to compute strides /// for given dimensions. /// @return: memory::desc object corresponding to blocked memory format /// for given dimensions and strides. inline memory::desc CreateBlockedMemDescHelper(const memory::dims& dim, const memory::dims& strides, memory::data_type dtype) { CHECK_EQ(dim.size(), strides.size()); // We have to construct memory descriptor in a C style. This is not at all // ideal but MKLDNN does not offer any API to construct descriptor in // blocked format except a copy constructor that accepts // mkldnn_memory_desc_t. mkldnn_memory_desc_t md; md.primitive_kind = mkldnn_memory; md.ndims = dim.size(); md.format = mkldnn_blocked; md.data_type = memory::convert_to_c(dtype); for (size_t i = 0; i < dim.size(); i++) { md.layout_desc.blocking.block_dims[i] = 1; md.layout_desc.blocking.strides[1][i] = 1; md.layout_desc.blocking.strides[0][i] = strides[i]; md.layout_desc.blocking.padding_dims[i] = dim[i]; md.layout_desc.blocking.offset_padding_to_data[i] = 0; md.dims[i] = dim[i]; } md.layout_desc.blocking.offset_padding = 0; return memory::desc(md); } /* * Class to represent all the resources corresponding to a tensor in TensorFlow * that are required to execute an operation (such as Convolution). */ template <typename T> class MklDnnData { private: /// MKL-DNN memory primitive for input user memory memory* user_memory_; /// MKL-DNN memory primitive in case input or output reorder is needed. memory* reorder_memory_; /// Operations memory descriptor memory::desc* op_md_; /// CPU engine on which operation will be executed const engine* cpu_engine_; public: explicit MklDnnData(const engine* e) : user_memory_(nullptr), reorder_memory_(nullptr), op_md_(nullptr), cpu_engine_(e) {} ~MklDnnData() { cpu_engine_ = nullptr; // We don't own this. delete (user_memory_); delete (reorder_memory_); delete (op_md_); } inline void* GetTensorBuffer(const Tensor* tensor) const { CHECK_NOTNULL(tensor); return const_cast<void*>( static_cast<const void*>(tensor->flat<T>().data())); } /// Set user memory primitive using specified dimensions, memory format and /// data_buffer. Function automatically uses element data type by using /// input type T used for creating call object. /// /// In a nutshell, function allows user to describe the input tensor to /// an operation. E.g., filter of Conv2D is of shape {1, 2, 3, 4}, and /// memory format HWIO, and the buffer that contains actual values is /// pointed by data_buffer. inline void SetUsrMem(const memory::dims& dim, memory::format fm, void* data_buffer = nullptr) { auto md = memory::desc(dim, MklDnnType<T>(), fm); SetUsrMem(md, data_buffer); } inline void SetUsrMem(const memory::dims& dim, memory::format fm, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(dim, fm, GetTensorBuffer(tensor)); } /// Helper function to create memory descriptor in Blocked format /// /// @input: Tensor dimensions /// @input: strides corresponding to dimensions. One can use utility /// function such as CalculateTFStrides to compute strides /// for given dimensions. /// @return: memory::desc object corresponding to blocked memory format /// for given dimensions and strides. static inline memory::desc CreateBlockedMemDesc(const memory::dims& dim, const memory::dims& strides) { return CreateBlockedMemDescHelper(dim, strides, MklDnnType<T>()); } /// A version of SetUsrMem call that allows user to create memory in blocked /// format. So in addition to accepting dimensions, it also accepts strides. /// This allows user to create memory for tensor in a format that is not /// supported by MKLDNN. E.g., MKLDNN does not support tensor format for 6 /// dimensional tensor as a native format. But by using blocked format, a user /// can create memory for 6D tensor. inline void SetUsrMem(const memory::dims& dim, const memory::dims& strides, void* data_buffer = nullptr) { CHECK_EQ(dim.size(), strides.size()); auto blocked_md = MklDnnData<T>::CreateBlockedMemDesc(dim, strides); SetUsrMem(blocked_md, data_buffer); } inline void SetUsrMem(const memory::dims& dim, const memory::dims& strides, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(dim, strides, GetTensorBuffer(tensor)); } /// A version of function to set user memory primitive that accepts memory /// descriptor directly, instead of accepting dimensions and format. This /// function is more generic that the one above, but the function above is /// sufficient in most cases. inline void SetUsrMem(const memory::desc& md, void* data_buffer = nullptr) { auto pd = memory::primitive_desc(md, *cpu_engine_); SetUsrMem(pd, data_buffer); } /// A version of SetUsrMem with memory descriptor and tensor inline void SetUsrMem(const memory::desc& md, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(md, GetTensorBuffer(tensor)); } /// A version of function to set user memory primitive that accepts primitive /// descriptor directly, instead of accepting dimensions and format. This /// function is more generic that the one above, but the function above is /// sufficient in most cases. inline void SetUsrMem(const memory::primitive_desc& pd, void* data_buffer = nullptr) { CHECK_NOTNULL(cpu_engine_); // TODO(nhasabni): can we remove dynamic memory allocation? if (data_buffer) { user_memory_ = new memory(pd, data_buffer); } else { user_memory_ = new memory(pd); } } /// A version of SetUsrMem with primitive descriptor and tensor inline void SetUsrMem(const memory::primitive_desc& pd, const Tensor* tensor) { CHECK_NOTNULL(tensor); SetUsrMem(pd, GetTensorBuffer(tensor)); } /// Get function for user memory primitive. inline const memory* GetUsrMem() const { return user_memory_; } /// Get function for primitive descriptor of user memory primitive. inline const memory::primitive_desc GetUsrMemPrimDesc() const { CHECK_NOTNULL(user_memory_); return user_memory_->get_primitive_desc(); } /// Get function for descriptor of user memory. inline memory::desc GetUsrMemDesc() { // This is ugly. Why MKL-DNN does not provide desc() method of const type?? const memory::primitive_desc pd = GetUsrMemPrimDesc(); return const_cast<memory::primitive_desc*>(&pd)->desc(); } /// Get function for data buffer of user memory primitive. inline void* GetUsrMemDataHandle() const { CHECK_NOTNULL(user_memory_); return user_memory_->get_data_handle(); } /// Set function for data buffer of user memory primitive. inline void SetUsrMemDataHandle(void* data_buffer) { CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(data_buffer); user_memory_->set_data_handle(data_buffer); } /// Set function for data buffer of user memory primitive. inline void SetUsrMemDataHandle(const Tensor* tensor) { CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(tensor); user_memory_->set_data_handle(GetTensorBuffer(tensor)); } /// Get the memory primitive for input and output of an op. If inputs /// to an op require reorders, then this function returns memory primitive /// for reorder. Otherwise, it will return memory primitive for user memory. /// /// E.g., Conv2D(I, F) is a primitive with I and F being inputs. Then to /// execute Conv2D, we need memory primitive for I and F. Buf if reorder is /// required for I and F (say I_r is reorder primitive for I; F_r is reorder /// primitive for F), then we need I_r and F_r to perform Conv2D. inline const memory& GetOpMem() const { return reorder_memory_ ? *reorder_memory_ : *user_memory_; } /// Set memory descriptor of an operation in terms of dimensions and memory /// format. E.g., For Conv2D, the dimensions would be same as user dimensions /// but memory::format would be mkldnn::any because we want MKL-DNN to choose /// best layout/format for given input dimensions. inline void SetOpMemDesc(const memory::dims& dim, memory::format fm) { // TODO(nhasabni): can we remove dynamic memory allocation? op_md_ = new memory::desc(dim, MklDnnType<T>(), fm); } /// Get function for memory descriptor for an operation inline const memory::desc& GetOpMemDesc() const { return *op_md_; } /// Predicate that checks if we need to reorder user's memory into memory /// pointed by op_pd. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @return: true in case reorder of input is needed; false, otherwise. inline bool IsReorderNeeded(const memory::primitive_desc& op_pd) const { CHECK_NOTNULL(user_memory_); return op_pd != user_memory_->get_primitive_desc(); } /// Predicate that checks if we need to reorder user's memory into memory /// based on the provided format. /// /// @input: target_format - memory format of the given input of an /// operation /// @return: true in case reorder of input is needed; false, otherwise. inline bool IsReorderNeeded(const memory::format& target_format) const { CHECK_NOTNULL(user_memory_); return target_format != user_memory_->get_primitive_desc().desc().data.format; } /// Function to create a reorder from memory pointed by from to memory pointed /// by to. Returns created primitive. inline primitive CreateReorder(const memory* from, const memory* to) const { CHECK_NOTNULL(from); CHECK_NOTNULL(to); return reorder(*from, *to); } /// Function to handle input reordering /// /// Check if we need to reorder this input of an operation. /// Return true and allocate reorder memory primitive if reorder is needed. /// Otherwise, return false and do not allocate reorder memory primitive. /// /// To check if reorder is needed, this function compares memory primitive /// descriptor of an operation (op_pd) for the given input with the /// user-specified memory primitive descriptor. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd); net->push_back(CreateReorder(user_memory_, reorder_memory_)); return true; } return false; } /// Overloaded version of above function that accepts memory buffer /// where output of reorder needs to be stored. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @reorder_data_handle - memory buffer where output of reorder needs to be /// stored. Primitive does not check if buffer is /// enough size to write. /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, void* reorder_data_handle, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(reorder_data_handle); CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd, reorder_data_handle); net->push_back(CreateReorder(user_memory_, reorder_memory_)); return true; } return false; } /// Another overloaded version of CheckReorderToOpMem that accepts Tensor /// where output of reorder needs to be stored. /// /// @input: op_pd - memory primitive descriptor of the given input of an /// operation /// @reorder_tensor - Tensor whose buffer is to be used to store output of /// reorder. Primitive does not check if buffer is /// enough size to write. /// @input: net - net to which to add reorder primitive in case it is needed. /// @return: true in case reorder of input is needed; false, otherwise. inline bool CheckReorderToOpMem(const memory::primitive_desc& op_pd, Tensor* reorder_tensor, std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(reorder_tensor); return CheckReorderToOpMem(op_pd, GetTensorBuffer(reorder_tensor), net); } /// Function to handle output reorder /// /// This function performs very similar functionality as input reordering /// function above. The only difference is that this function does not add /// reorder primitive to the net. The reason for this is: the reorder /// primitive for output needs to be added to the list only after operation /// has executed. But we need to prepare a temporary buffer in case output /// reorder is needed. And this temporary buffer will hold the output of /// an operation before it is fed to reorder primitive. /// /// @input memory primitive descriptor for the given output of an operation /// @return: true in case reorder of output is needed; false, otherwise. inline bool PrepareReorderToUserMemIfReq( const memory::primitive_desc& op_pd) { CHECK_NOTNULL(user_memory_); if (IsReorderNeeded(op_pd)) { // TODO(nhasabni): can we remove dynamic memory allocation? reorder_memory_ = new memory(op_pd); return true; } return false; } /// Function to actually insert reorder primitive in the net /// /// This function completes remaining part of output reordering. It inserts /// a reordering primitive from the temporary buffer that holds the output /// to the user-specified output buffer. /// /// @input: net - net to which to add reorder primitive inline void InsertReorderToUserMem(std::vector<primitive>* net) { CHECK_NOTNULL(net); CHECK_NOTNULL(user_memory_); CHECK_NOTNULL(reorder_memory_); net->push_back(CreateReorder(reorder_memory_, user_memory_)); } }; /// Base class for operations with reuse of primitives /// class MklPrimitive { public: virtual ~MklPrimitive() {} // Dummy data. Its size, hard-coded as 256 here, does // not matter since MKL should never operate on this buffer. unsigned char DummyData[256]; }; const mkldnn::memory::dims NONE_DIMS = {}; template <typename T> class MklPrimitiveFactory { public: MklPrimitiveFactory() {} ~MklPrimitiveFactory() {} MklPrimitive* GetOp(const std::string& key) { auto stream_iter = MklPrimitiveFactory<T>::GetHashMap().find(key); if (stream_iter == MklPrimitiveFactory<T>::GetHashMap().end()) { return nullptr; } else { return stream_iter->second; } } void SetOp(const std::string& key, MklPrimitive* op) { auto stream_iter = MklPrimitiveFactory<T>::GetHashMap().find(key); CHECK(stream_iter == MklPrimitiveFactory<T>::GetHashMap().end()); MklPrimitiveFactory<T>::GetHashMap()[key] = op; } private: static inline std::unordered_map<std::string, MklPrimitive*>& GetHashMap() { static thread_local std::unordered_map<std::string, MklPrimitive*> map_; return map_; } }; // utility class for creating keys of MKL primitive pool. class FactoryKeyCreator { public: FactoryKeyCreator() { key_.reserve(kMaxKeyLength); } ~FactoryKeyCreator() {} void AddAsKey(const string& str) { Append(str); } void AddAsKey(const mkldnn::memory::dims &dims) { for (unsigned int i = 0; i < dims.size(); i++) { AddAsKey<int>(dims[i]); } } template <typename T> void AddAsKey(const T data) { auto buffer = reinterpret_cast<const char *>(&data); Append(StringPiece(buffer, sizeof(T))); } std::string GetKey() { return key_; } private: string key_; const char delimiter = 'x'; const int kMaxKeyLength = 256; void Append(StringPiece s) { key_.append(s.ToString()); key_.append(1, delimiter); } }; #endif // INTEL_MKL_DNN } // namespace tensorflow #endif // INTEL_MKL #endif // TENSORFLOW_CORE_UTIL_MKL_UTIL_H_
prolong_mex.c
#include <inttypes.h> #include <omp.h> #include "mex.h" #include "prolong_mex.h" void prolongf(float *x, const float *x2, const uint8_t *G, const size_t *sz, const size_t *sz2); void prolongd(double *x, const double *x2, const uint8_t *G, const size_t *sz, const size_t *sz2); #ifdef PROLONG_MEX void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs != 3) || (nlhs > 1)) { mexErrMsgTxt("Usage: prolong_mex(x, x2, G);"); } const uint8_t *G = (const uint8_t *)mxGetData(prhs[2]); const size_t *sz = (const size_t *)mxGetDimensions(prhs[0]); const size_t *sz2 = (const size_t *)mxGetDimensions(prhs[1]); if (mxIsSingle(prhs[0])) { float *x = (float *)mxGetData(prhs[0]); const float *x2 = (const float *)mxGetData(prhs[1]); prolongf(x, x2, G, sz, sz2); } else { double *x = (double *)mxGetData(prhs[0]); const double *x2 = (const double *)mxGetData(prhs[1]); prolongd(x, x2, G, sz, sz2); } if (nlhs == 1) { plhs[0] = mxCreateDoubleScalar(1.0); } return; } #endif void mx_prolong(mxArray *mxx, const mxArray *mxx2, const mxArray *mxG) { const uint8_t *G = (const uint8_t *)mxGetData(mxG); const size_t *sz = (const size_t *)mxGetDimensions(mxx); const size_t *sz2 = (const size_t *)mxGetDimensions(mxx2); if (mxIsSingle(mxx)) { float *x = (float *)mxGetData(mxx); const float *x2 = (const float *)mxGetData(mxx2); prolongf(x, x2, G, sz, sz2); } else { double *x = (double *)mxGetData(mxx); const double *x2 = (const double *)mxGetData(mxx2); const uint8_t *G = (const uint8_t *)mxGetData(mxG); prolongd(x, x2, G, sz, sz2); } return; } void prolongf(float *x, const float *x2, const uint8_t *G, const size_t *sz, const size_t *sz2) { size_t i2, j2, k2; size_t l2, lk2; size_t l, lk; const size_t nx = sz[0]; const size_t ny = sz[1]; const size_t nz = sz[2]; const size_t nxny = nx*ny; const size_t nx2 = sz2[0]; const size_t ny2 = sz2[1]; const size_t nz2 = sz2[2]; const size_t nxny2 = nx2*ny2; const size_t NX2 = nx2-1; const size_t NY2 = ny2-1; const size_t NZ2 = nz2-1; /* offset indices */ const size_t o110 = 1 + nx + 0; const size_t o101 = 1 + 0 + nxny; const size_t o011 = 0 + nx + nxny; const size_t o111 = 1 + nx + nxny; const size_t o110_2 = 1 + nx2 + 0; const size_t o101_2 = 1 + 0 + nxny2; const size_t o011_2 = 0 + nx2 + nxny2; const size_t o111_2 = 1 + nx2 + nxny2; #pragma omp parallel for private(i2,j2,k2,l2,lk2,l,lk) schedule(static) \ if(nxny*nz > 32*32*32) for(k2 = 1; k2 < NZ2; ++k2) { lk2 = nxny2*k2; lk = nxny*((k2<<1)-1); for(j2 = 1; j2 < NY2; ++j2) { l2 = 1 + nx2*j2 + lk2; l = 1 + nx*((j2<<1)-1) + lk; for(i2 = 1; i2 < NX2; ++i2, ++l2, l += 2) { x[l] = G[l] ? x2[l2] : 0.0f; x[l+1] = G[l+1] ? 0.5f*( x2[l2] + x2[l2+1] ) : 0.0f; x[l+nx] = G[l+nx] ? 0.5f*( x2[l2] + x2[l2+nx2] ) : 0.0f; x[l+nxny] = G[l+nxny] ? 0.5f*( x2[l2] + x2[l2+nxny2] ) : 0.0f; x[l+o110] = G[l+o110] ? 0.25f*( x2[l2] + x2[l2+1] + x2[l2+nx2] + x2[l2+o110_2] ) : 0.0f; x[l+o101] = G[l+o101] ? 0.25f*( x2[l2] + x2[l2+1] + x2[l2+nxny2] + x2[l2+o101_2] ) : 0.0f; x[l+o011] = G[l+o011] ? 0.25f*( x2[l2] + x2[l2+nx2] + x2[l2+nxny2] + x2[l2+o011_2] ) : 0.0f; x[l+o111] = G[l+o111] ? 0.125f*( x2[l2] + x2[l2+1] + x2[l2+nx2] + x2[l2+nxny2] + x2[l2+o110_2] + x2[l2+o101_2] + x2[l2+o011_2] + x2[l2+o111_2] ) : 0.0f; } } } return; } void prolongd(double *x, const double *x2, const uint8_t *G, const size_t *sz, const size_t *sz2) { size_t i2, j2, k2; size_t l2, lk2; size_t l, lk; const size_t nx = sz[0]; const size_t ny = sz[1]; const size_t nz = sz[2]; const size_t nxny = nx*ny; const size_t nx2 = sz2[0]; const size_t ny2 = sz2[1]; const size_t nz2 = sz2[2]; const size_t nxny2 = nx2*ny2; const size_t NX2 = nx2-1; const size_t NY2 = ny2-1; const size_t NZ2 = nz2-1; /* offset indices */ const size_t o110 = 1 + nx + 0; const size_t o101 = 1 + 0 + nxny; const size_t o011 = 0 + nx + nxny; const size_t o111 = 1 + nx + nxny; const size_t o110_2 = 1 + nx2 + 0; const size_t o101_2 = 1 + 0 + nxny2; const size_t o011_2 = 0 + nx2 + nxny2; const size_t o111_2 = 1 + nx2 + nxny2; #pragma omp parallel for private(i2,j2,k2,l2,lk2,l,lk) schedule(static) \ if(nxny*nz > 32*32*32) for(k2 = 1; k2 < NZ2; ++k2) { lk2 = nxny2*k2; lk = nxny*((k2<<1)-1); for(j2 = 1; j2 < NY2; ++j2) { l2 = 1 + nx2*j2 + lk2; l = 1 + nx*((j2<<1)-1) + lk; for(i2 = 1; i2 < NX2; ++i2, ++l2, l += 2) { x[l] = G[l] ? x2[l2] : 0.0; x[l+1] = G[l+1] ? 0.5*( x2[l2] + x2[l2+1] ) : 0.0; x[l+nx] = G[l+nx] ? 0.5*( x2[l2] + x2[l2+nx2] ) : 0.0; x[l+nxny] = G[l+nxny] ? 0.5*( x2[l2] + x2[l2+nxny2] ) : 0.0; x[l+o110] = G[l+o110] ? 0.25*( x2[l2] + x2[l2+1] + x2[l2+nx2] + x2[l2+o110_2] ) : 0.0; x[l+o101] = G[l+o101] ? 0.25*( x2[l2] + x2[l2+1] + x2[l2+nxny2] + x2[l2+o101_2] ) : 0.0; x[l+o011] = G[l+o011] ? 0.25*( x2[l2] + x2[l2+nx2] + x2[l2+nxny2] + x2[l2+o011_2] ) : 0.0; x[l+o111] = G[l+o111] ? 0.125*( x2[l2] + x2[l2+1] + x2[l2+nx2] + x2[l2+nxny2] + x2[l2+o110_2] + x2[l2+o101_2] + x2[l2+o011_2] + x2[l2+o111_2] ) : 0.0; } } } return; }
DRB109-orderedmissing-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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 "omprace.h" #include <omp.h> #include <stdio.h> /* This is a program based on a test contributed by Yizi Gu@Rice Univ. * Missing the ordered clause * Data race pair: x@56:5 vs. x@56:5 * */ int main() { omprace_init(); int x =0; #pragma omp parallel for ordered for (int i = 0; i < 100; ++i) { x++; } printf ("x=%d\n",x); omprace_fini(); return 0; }
ratecontrol.c
/***************************************************-*- coding: iso-8859-1 -*- * ratecontrol.c: h264 encoder library (Rate Control) ***************************************************************************** * Copyright (C) 2005-2008 x264 project * * Authors: Loren Merritt <lorenm@u.washington.edu> * Michael Niedermayer <michaelni@gmx.at> * Gabriel Bouvigne <gabriel.bouvigne@joost.com> * Jason Garrett-Glaser <darkshikari@gmail.com> * M�ns Rullg�rd <mru@mru.ath.cx> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. *****************************************************************************/ #define _ISOC99_SOURCE #undef NDEBUG // always check asserts, the speed effect is far too small to disable them #include <math.h> #include <limits.h> #include <assert.h> #include "common/common.h" #include "common/cpu.h" #include "ratecontrol.h" typedef struct { int pict_type; int kept_as_ref; float qscale; int mv_bits; int tex_bits; int misc_bits; uint64_t expected_bits; /*total expected bits up to the current frame (current one excluded)*/ double expected_vbv; float new_qscale; int new_qp; int i_count; int p_count; int s_count; float blurred_complexity; char direct_mode; } ratecontrol_entry_t; typedef struct { double coeff; double count; double decay; } predictor_t; struct x264_ratecontrol_t { /* constants */ int b_abr; int b_2pass; int b_vbv; int b_vbv_min_rate; double fps; double bitrate; double rate_tolerance; int nmb; /* number of macroblocks in a frame */ int qp_constant[5]; /* current frame */ ratecontrol_entry_t *rce; int qp; /* qp for current frame */ int qpm; /* qp for current macroblock */ float f_qpm; /* qp for current macroblock: precise float for AQ */ float qpa_rc; /* average of macroblocks' qp before aq */ float qpa_aq; /* average of macroblocks' qp after aq */ int qp_force; /* VBV stuff */ double buffer_size; double buffer_fill_final; /* real buffer as of the last finished frame */ double buffer_fill; /* planned buffer, if all in-progress frames hit their bit budget */ double buffer_rate; /* # of bits added to buffer_fill after each frame */ predictor_t *pred; /* predict frame size from satd */ /* ABR stuff */ int last_satd; double last_rceq; double cplxr_sum; /* sum of bits*qscale/rceq */ double expected_bits_sum; /* sum of qscale2bits after rceq, ratefactor, and overflow, only includes finished frames */ double wanted_bits_window; /* target bitrate * window */ double cbr_decay; double short_term_cplxsum; double short_term_cplxcount; double rate_factor_constant; double ip_offset; double pb_offset; /* 2pass stuff */ FILE *p_stat_file_out; char *psz_stat_file_tmpname; int num_entries; /* number of ratecontrol_entry_ts */ ratecontrol_entry_t *entry; /* FIXME: copy needed data and free this once init is done */ double last_qscale; double last_qscale_for[5]; /* last qscale for a specific pict type, used for max_diff & ipb factor stuff */ int last_non_b_pict_type; double accum_p_qp; /* for determining I-frame quant */ double accum_p_norm; double last_accum_p_norm; double lmin[5]; /* min qscale by frame type */ double lmax[5]; double lstep; /* max change (multiply) in qscale per frame */ /* MBRC stuff */ double frame_size_estimated; double frame_size_planned; predictor_t *row_pred; predictor_t row_preds[5]; predictor_t *pred_b_from_p; /* predict B-frame size from P-frame satd */ int bframes; /* # consecutive B-frames before this P-frame */ int bframe_bits; /* total cost of those frames */ int i_zones; x264_zone_t *zones; x264_zone_t *prev_zone; }; static int parse_zones( x264_t *h ); static int init_pass2(x264_t *); static float rate_estimate_qscale( x264_t *h ); static void update_vbv( x264_t *h, int bits ); static void update_vbv_plan( x264_t *h ); static double predict_size( predictor_t *p, double q, double var ); static void update_predictor( predictor_t *p, double q, double var, double bits ); /* Terminology: * qp = h.264's quantizer * qscale = linearized quantizer = Lagrange multiplier */ static inline double qp2qscale(double qp) { return 0.85 * pow(2.0, ( qp - 12.0 ) / 6.0); } static inline double qscale2qp(double qscale) { return 12.0 + 6.0 * log(qscale/0.85) / log(2.0); } /* Texture bitrate is not quite inversely proportional to qscale, * probably due the the changing number of SKIP blocks. * MV bits level off at about qp<=12, because the lambda used * for motion estimation is constant there. */ static inline double qscale2bits(ratecontrol_entry_t *rce, double qscale) { if(qscale<0.1) qscale = 0.1; return (rce->tex_bits + .1) * pow( rce->qscale / qscale, 1.1 ) + rce->mv_bits * pow( X264_MAX(rce->qscale, 1) / X264_MAX(qscale, 1), 0.5 ) + rce->misc_bits; } // Find the total AC energy of the block in all planes. static NOINLINE int ac_energy_mb( x264_t *h, int mb_x, int mb_y, x264_frame_t *frame ) { /* This function contains annoying hacks because GCC has a habit of reordering emms * and putting it after floating point ops. As a result, we put the emms at the end of the * function and make sure that its always called before the float math. Noinline makes * sure no reordering goes on. */ unsigned int var=0, sad, i; for( i=0; i<3; i++ ) { int w = i ? 8 : 16; int stride = frame->i_stride[i]; int offset = h->mb.b_interlaced ? w * (mb_x + (mb_y&~1) * stride) + (mb_y&1) * stride : w * (mb_x + mb_y * stride); int pix = i ? PIXEL_8x8 : PIXEL_16x16; stride <<= h->mb.b_interlaced; var += h->pixf.var[pix]( frame->plane[i]+offset, stride, &sad ); } var = X264_MAX(var,1); x264_emms(); return var; } void x264_adaptive_quant_frame( x264_t *h, x264_frame_t *frame ) { int mb_x, mb_y; for( mb_y=0; mb_y<h->sps->i_mb_height; mb_y++ ) for( mb_x=0; mb_x<h->sps->i_mb_width; mb_x++ ) { int energy = ac_energy_mb( h, mb_x, mb_y, frame ); /* 10 constant chosen to result in approximately the same overall bitrate as without AQ. */ float qp_adj = h->param.rc.f_aq_strength * 1.5 * (logf(energy) - 10.0); frame->f_qp_offset[mb_x + mb_y*h->mb.i_mb_stride] = qp_adj; if( h->frames.b_have_lowres ) frame->i_inv_qscale_factor[mb_x+mb_y*h->mb.i_mb_stride] = FIX8(pow(2.0,-qp_adj/6.0)); } } /***************************************************************************** * x264_adaptive_quant: * adjust macroblock QP based on variance (AC energy) of the MB. * high variance = higher QP * low variance = lower QP * This generally increases SSIM and lowers PSNR. *****************************************************************************/ void x264_adaptive_quant( x264_t *h ) { float qp, qp_adj; x264_emms(); qp = h->rc->f_qpm; qp_adj = h->fenc->f_qp_offset[h->mb.i_mb_x + h->mb.i_mb_y*h->mb.i_mb_stride]; h->mb.i_qp = x264_clip3( qp + qp_adj + .5, h->param.rc.i_qp_min, h->param.rc.i_qp_max ); /* If the QP of this MB is within 1 of the previous MB, code the same QP as the previous MB, * to lower the bit cost of the qp_delta. */ if( abs(h->mb.i_qp - h->mb.i_last_qp) == 1 ) h->mb.i_qp = h->mb.i_last_qp; h->mb.i_chroma_qp = h->chroma_qp_table[h->mb.i_qp]; } int x264_ratecontrol_new( x264_t *h ) { x264_ratecontrol_t *rc; int i; x264_emms(); rc = h->rc = x264_malloc( h->param.i_threads * sizeof(x264_ratecontrol_t) ); memset( rc, 0, h->param.i_threads * sizeof(x264_ratecontrol_t) ); rc->b_abr = h->param.rc.i_rc_method != X264_RC_CQP && !h->param.rc.b_stat_read; rc->b_2pass = h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.b_stat_read; /* FIXME: use integers */ if(h->param.i_fps_num > 0 && h->param.i_fps_den > 0) rc->fps = (float) h->param.i_fps_num / h->param.i_fps_den; else rc->fps = 25.0; rc->bitrate = h->param.rc.i_bitrate * 1000.; rc->rate_tolerance = h->param.rc.f_rate_tolerance; rc->nmb = h->mb.i_mb_count; rc->last_non_b_pict_type = -1; rc->cbr_decay = 1.0; if( h->param.rc.i_rc_method == X264_RC_CRF && h->param.rc.b_stat_read ) { x264_log(h, X264_LOG_ERROR, "constant rate-factor is incompatible with 2pass.\n"); return -1; } if( h->param.rc.i_vbv_buffer_size ) { if( h->param.rc.i_rc_method == X264_RC_CQP ) { x264_log(h, X264_LOG_WARNING, "VBV is incompatible with constant QP, ignored.\n"); h->param.rc.i_vbv_max_bitrate = 0; h->param.rc.i_vbv_buffer_size = 0; } else if( h->param.rc.i_vbv_max_bitrate == 0 ) { x264_log( h, X264_LOG_DEBUG, "VBV maxrate unspecified, assuming CBR\n" ); h->param.rc.i_vbv_max_bitrate = h->param.rc.i_bitrate; } } if( h->param.rc.i_vbv_max_bitrate < h->param.rc.i_bitrate && h->param.rc.i_vbv_max_bitrate > 0) x264_log(h, X264_LOG_WARNING, "max bitrate less than average bitrate, ignored.\n"); else if( h->param.rc.i_vbv_max_bitrate > 0 && h->param.rc.i_vbv_buffer_size > 0 ) { if( h->param.rc.i_vbv_buffer_size < 3 * h->param.rc.i_vbv_max_bitrate / rc->fps ) { h->param.rc.i_vbv_buffer_size = 3 * h->param.rc.i_vbv_max_bitrate / rc->fps; x264_log( h, X264_LOG_WARNING, "VBV buffer size too small, using %d kbit\n", h->param.rc.i_vbv_buffer_size ); } if( h->param.rc.f_vbv_buffer_init > 1. ) h->param.rc.f_vbv_buffer_init = x264_clip3f( h->param.rc.f_vbv_buffer_init / h->param.rc.i_vbv_buffer_size, 0, 1 ); rc->buffer_rate = h->param.rc.i_vbv_max_bitrate * 1000. / rc->fps; rc->buffer_size = h->param.rc.i_vbv_buffer_size * 1000.; rc->buffer_fill_final = rc->buffer_size * h->param.rc.f_vbv_buffer_init; rc->cbr_decay = 1.0 - rc->buffer_rate / rc->buffer_size * 0.5 * X264_MAX(0, 1.5 - rc->buffer_rate * rc->fps / rc->bitrate); rc->b_vbv = 1; rc->b_vbv_min_rate = !rc->b_2pass && h->param.rc.i_rc_method == X264_RC_ABR && h->param.rc.i_vbv_max_bitrate <= h->param.rc.i_bitrate; } else if( h->param.rc.i_vbv_max_bitrate ) { x264_log(h, X264_LOG_WARNING, "VBV maxrate specified, but no bufsize.\n"); h->param.rc.i_vbv_max_bitrate = 0; } if(rc->rate_tolerance < 0.01) { x264_log(h, X264_LOG_WARNING, "bitrate tolerance too small, using .01\n"); rc->rate_tolerance = 0.01; } h->mb.b_variable_qp = rc->b_vbv || h->param.rc.i_aq_mode; if( rc->b_abr ) { /* FIXME ABR_INIT_QP is actually used only in CRF */ #define ABR_INIT_QP ( h->param.rc.i_rc_method == X264_RC_CRF ? h->param.rc.f_rf_constant : 24 ) rc->accum_p_norm = .01; rc->accum_p_qp = ABR_INIT_QP * rc->accum_p_norm; /* estimated ratio that produces a reasonable QP for the first I-frame */ rc->cplxr_sum = .01 * pow( 7.0e5, h->param.rc.f_qcompress ) * pow( h->mb.i_mb_count, 0.5 ); rc->wanted_bits_window = 1.0 * rc->bitrate / rc->fps; rc->last_non_b_pict_type = SLICE_TYPE_I; } if( h->param.rc.i_rc_method == X264_RC_CRF ) { /* arbitrary rescaling to make CRF somewhat similar to QP */ double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80); rc->rate_factor_constant = pow( base_cplx, 1 - h->param.rc.f_qcompress ) / qp2qscale( h->param.rc.f_rf_constant ); } rc->ip_offset = 6.0 * log(h->param.rc.f_ip_factor) / log(2.0); rc->pb_offset = 6.0 * log(h->param.rc.f_pb_factor) / log(2.0); rc->qp_constant[SLICE_TYPE_P] = h->param.rc.i_qp_constant; rc->qp_constant[SLICE_TYPE_I] = x264_clip3( h->param.rc.i_qp_constant - rc->ip_offset + 0.5, 0, 51 ); rc->qp_constant[SLICE_TYPE_B] = x264_clip3( h->param.rc.i_qp_constant + rc->pb_offset + 0.5, 0, 51 ); rc->lstep = pow( 2, h->param.rc.i_qp_step / 6.0 ); rc->last_qscale = qp2qscale(26); rc->pred = x264_malloc( 5*sizeof(predictor_t) ); rc->pred_b_from_p = x264_malloc( sizeof(predictor_t) ); for( i = 0; i < 5; i++ ) { rc->last_qscale_for[i] = qp2qscale( ABR_INIT_QP ); rc->lmin[i] = qp2qscale( h->param.rc.i_qp_min ); rc->lmax[i] = qp2qscale( h->param.rc.i_qp_max ); rc->pred[i].coeff= 2.0; rc->pred[i].count= 1.0; rc->pred[i].decay= 0.5; rc->row_preds[i].coeff= .25; rc->row_preds[i].count= 1.0; rc->row_preds[i].decay= 0.5; } *rc->pred_b_from_p = rc->pred[0]; if( parse_zones( h ) < 0 ) { x264_log( h, X264_LOG_ERROR, "failed to parse zones\n" ); return -1; } /* Load stat file and init 2pass algo */ if( h->param.rc.b_stat_read ) { char *p, *stats_in, *stats_buf; /* read 1st pass stats */ assert( h->param.rc.psz_stat_in ); stats_buf = stats_in = x264_slurp_file( h->param.rc.psz_stat_in ); if( !stats_buf ) { x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n"); return -1; } /* check whether 1st pass options were compatible with current options */ if( !strncmp( stats_buf, "#options:", 9 ) ) { int i; char *opts = stats_buf; stats_in = strchr( stats_buf, '\n' ); if( !stats_in ) return -1; *stats_in = '\0'; stats_in++; if( ( p = strstr( opts, "bframes=" ) ) && sscanf( p, "bframes=%d", &i ) && h->param.i_bframe != i ) { x264_log( h, X264_LOG_ERROR, "different number of B-frames than 1st pass (%d vs %d)\n", h->param.i_bframe, i ); return -1; } /* since B-adapt doesn't (yet) take into account B-pyramid, * the converse is not a problem */ if( strstr( opts, "b_pyramid=1" ) && !h->param.b_bframe_pyramid ) x264_log( h, X264_LOG_WARNING, "1st pass used B-pyramid, 2nd doesn't\n" ); if( ( p = strstr( opts, "keyint=" ) ) && sscanf( p, "keyint=%d", &i ) && h->param.i_keyint_max != i ) x264_log( h, X264_LOG_WARNING, "different keyint than 1st pass (%d vs %d)\n", h->param.i_keyint_max, i ); if( strstr( opts, "qp=0" ) && h->param.rc.i_rc_method == X264_RC_ABR ) x264_log( h, X264_LOG_WARNING, "1st pass was lossless, bitrate prediction will be inaccurate\n" ); if( ( p = strstr( opts, "b_adapt=" ) ) && sscanf( p, "b_adapt=%d", &i ) && i >= X264_B_ADAPT_NONE && i <= X264_B_ADAPT_TRELLIS ) h->param.i_bframe_adaptive = i; else if( h->param.i_bframe ) { x264_log( h, X264_LOG_ERROR, "b_adapt method specified in stats file not valid\n" ); return -1; } if( ( p = strstr( opts, "scenecut=" ) ) && sscanf( p, "scenecut=%d", &i ) && i >= -1 && i <= 100 ) { h->param.i_scenecut_threshold = i; h->param.b_pre_scenecut = !!strstr( p, "(pre)" ); } else { x264_log( h, X264_LOG_ERROR, "scenecut method specified in stats file not valid\n" ); return -1; } } /* find number of pics */ p = stats_in; for(i=-1; p; i++) p = strchr(p+1, ';'); if(i==0) { x264_log(h, X264_LOG_ERROR, "empty stats file\n"); return -1; } rc->num_entries = i; if( h->param.i_frame_total < rc->num_entries && h->param.i_frame_total > 0 ) { x264_log( h, X264_LOG_WARNING, "2nd pass has fewer frames than 1st pass (%d vs %d)\n", h->param.i_frame_total, rc->num_entries ); } if( h->param.i_frame_total > rc->num_entries ) { x264_log( h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d vs %d)\n", h->param.i_frame_total, rc->num_entries ); return -1; } rc->entry = (ratecontrol_entry_t*) x264_malloc(rc->num_entries * sizeof(ratecontrol_entry_t)); memset(rc->entry, 0, rc->num_entries * sizeof(ratecontrol_entry_t)); /* init all to skipped p frames */ for(i=0; i<rc->num_entries; i++) { ratecontrol_entry_t *rce = &rc->entry[i]; rce->pict_type = SLICE_TYPE_P; rce->qscale = rce->new_qscale = qp2qscale(20); rce->misc_bits = rc->nmb + 10; rce->new_qp = 0; } /* read stats */ p = stats_in; for(i=0; i < rc->num_entries; i++) { ratecontrol_entry_t *rce; int frame_number; char pict_type; int e; char *next; float qp; next= strchr(p, ';'); if(next) { (*next)=0; //sscanf is unbelievably slow on long strings next++; } e = sscanf(p, " in:%d ", &frame_number); if(frame_number < 0 || frame_number >= rc->num_entries) { x264_log(h, X264_LOG_ERROR, "bad frame number (%d) at stats line %d\n", frame_number, i); return -1; } rce = &rc->entry[frame_number]; rce->direct_mode = 0; e += sscanf(p, " in:%*d out:%*d type:%c q:%f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c", &pict_type, &qp, &rce->tex_bits, &rce->mv_bits, &rce->misc_bits, &rce->i_count, &rce->p_count, &rce->s_count, &rce->direct_mode); switch(pict_type) { case 'I': rce->kept_as_ref = 1; case 'i': rce->pict_type = SLICE_TYPE_I; break; case 'P': rce->pict_type = SLICE_TYPE_P; break; case 'B': rce->kept_as_ref = 1; case 'b': rce->pict_type = SLICE_TYPE_B; break; default: e = -1; break; } if(e < 10) { x264_log(h, X264_LOG_ERROR, "statistics are damaged at line %d, parser out=%d\n", i, e); return -1; } rce->qscale = qp2qscale(qp); p = next; } x264_free(stats_buf); if(h->param.rc.i_rc_method == X264_RC_ABR) { if(init_pass2(h) < 0) return -1; } /* else we're using constant quant, so no need to run the bitrate allocation */ } /* Open output file */ /* If input and output files are the same, output to a temp file * and move it to the real name only when it's complete */ if( h->param.rc.b_stat_write ) { char *p; rc->psz_stat_file_tmpname = x264_malloc( strlen(h->param.rc.psz_stat_out) + 6 ); strcpy( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ); strcat( rc->psz_stat_file_tmpname, ".temp" ); rc->p_stat_file_out = fopen( rc->psz_stat_file_tmpname, "wb" ); if( rc->p_stat_file_out == NULL ) { x264_log(h, X264_LOG_ERROR, "ratecontrol_init: can't open stats file\n"); return -1; } p = x264_param2string( &h->param, 1 ); fprintf( rc->p_stat_file_out, "#options: %s\n", p ); x264_free( p ); } for( i=0; i<h->param.i_threads; i++ ) { h->thread[i]->rc = rc+i; if( i ) { rc[i] = rc[0]; memcpy( &h->thread[i]->param, &h->param, sizeof( x264_param_t ) ); h->thread[i]->mb.b_variable_qp = h->mb.b_variable_qp; } } return 0; } static int parse_zone( x264_t *h, x264_zone_t *z, char *p ) { int len = 0; char *tok, *saveptr; z->param = NULL; z->f_bitrate_factor = 1; if( 3 <= sscanf(p, "%u,%u,q=%u%n", &z->i_start, &z->i_end, &z->i_qp, &len) ) z->b_force_qp = 1; else if( 3 <= sscanf(p, "%u,%u,b=%f%n", &z->i_start, &z->i_end, &z->f_bitrate_factor, &len) ) z->b_force_qp = 0; else if( 2 <= sscanf(p, "%u,%u%n", &z->i_start, &z->i_end, &len) ) z->b_force_qp = 0; else { x264_log( h, X264_LOG_ERROR, "invalid zone: \"%s\"\n", p ); return -1; } p += len; if( !*p ) return 0; z->param = malloc( sizeof(x264_param_t) ); memcpy( z->param, &h->param, sizeof(x264_param_t) ); while( (tok = strtok_r( p, ",", &saveptr )) ) { char *val = strchr( tok, '=' ); if( val ) { *val = '\0'; val++; } if( x264_param_parse( z->param, tok, val ) ) { x264_log( h, X264_LOG_ERROR, "invalid zone param: %s = %s\n", tok, val ); return -1; } p = NULL; } return 0; } static int parse_zones( x264_t *h ) { x264_ratecontrol_t *rc = h->rc; int i; if( h->param.rc.psz_zones && !h->param.rc.i_zones ) { char *p, *tok, *saveptr; char *psz_zones = x264_malloc( strlen(h->param.rc.psz_zones)+1 ); strcpy( psz_zones, h->param.rc.psz_zones ); h->param.rc.i_zones = 1; for( p = psz_zones; *p; p++ ) h->param.rc.i_zones += (*p == '/'); h->param.rc.zones = x264_malloc( h->param.rc.i_zones * sizeof(x264_zone_t) ); p = psz_zones; for( i = 0; i < h->param.rc.i_zones; i++ ) { tok = strtok_r( p, "/", &saveptr ); if( !tok || parse_zone( h, &h->param.rc.zones[i], tok ) ) return -1; p = NULL; } x264_free( psz_zones ); } if( h->param.rc.i_zones > 0 ) { for( i = 0; i < h->param.rc.i_zones; i++ ) { x264_zone_t z = h->param.rc.zones[i]; if( z.i_start < 0 || z.i_start > z.i_end ) { x264_log( h, X264_LOG_ERROR, "invalid zone: start=%d end=%d\n", z.i_start, z.i_end ); return -1; } else if( !z.b_force_qp && z.f_bitrate_factor <= 0 ) { x264_log( h, X264_LOG_ERROR, "invalid zone: bitrate_factor=%f\n", z.f_bitrate_factor ); return -1; } } rc->i_zones = h->param.rc.i_zones + 1; rc->zones = x264_malloc( rc->i_zones * sizeof(x264_zone_t) ); memcpy( rc->zones+1, h->param.rc.zones, (rc->i_zones-1) * sizeof(x264_zone_t) ); // default zone to fall back to if none of the others match rc->zones[0].i_start = 0; rc->zones[0].i_end = INT_MAX; rc->zones[0].b_force_qp = 0; rc->zones[0].f_bitrate_factor = 1; rc->zones[0].param = x264_malloc( sizeof(x264_param_t) ); memcpy( rc->zones[0].param, &h->param, sizeof(x264_param_t) ); for( i = 1; i < rc->i_zones; i++ ) { if( !rc->zones[i].param ) rc->zones[i].param = rc->zones[0].param; } } return 0; } static x264_zone_t *get_zone( x264_t *h, int frame_num ) { int i; for( i = h->rc->i_zones-1; i >= 0; i-- ) { x264_zone_t *z = &h->rc->zones[i]; if( frame_num >= z->i_start && frame_num <= z->i_end ) return z; } return NULL; } void x264_ratecontrol_summary( x264_t *h ) { x264_ratecontrol_t *rc = h->rc; if( rc->b_abr && h->param.rc.i_rc_method == X264_RC_ABR && rc->cbr_decay > .9999 ) { double base_cplx = h->mb.i_mb_count * (h->param.i_bframe ? 120 : 80); x264_log( h, X264_LOG_INFO, "final ratefactor: %.2f\n", qscale2qp( pow( base_cplx, 1 - h->param.rc.f_qcompress ) * rc->cplxr_sum / rc->wanted_bits_window ) ); } } void x264_ratecontrol_delete( x264_t *h ) { x264_ratecontrol_t *rc = h->rc; int i; if( rc->p_stat_file_out ) { fclose( rc->p_stat_file_out ); if( h->i_frame >= rc->num_entries ) if( rename( rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ) != 0 ) { x264_log( h, X264_LOG_ERROR, "failed to rename \"%s\" to \"%s\"\n", rc->psz_stat_file_tmpname, h->param.rc.psz_stat_out ); } x264_free( rc->psz_stat_file_tmpname ); } x264_free( rc->pred ); x264_free( rc->pred_b_from_p ); x264_free( rc->entry ); if( rc->zones ) { x264_free( rc->zones[0].param ); if( h->param.rc.psz_zones ) for( i=1; i<rc->i_zones; i++ ) if( rc->zones[i].param != rc->zones[0].param ) x264_free( rc->zones[i].param ); x264_free( rc->zones ); } x264_free( rc ); } void x264_ratecontrol_set_estimated_size( x264_t *h, int bits ) { #pragma omp critical h->rc->frame_size_estimated = bits; } int x264_ratecontrol_get_estimated_size( x264_t const *h) { int size; #pragma omp critical size = h->rc->frame_size_estimated; return size; } static void accum_p_qp_update( x264_t *h, float qp ) { x264_ratecontrol_t *rc = h->rc; rc->accum_p_qp *= .95; rc->accum_p_norm *= .95; rc->accum_p_norm += 1; if( h->sh.i_type == SLICE_TYPE_I ) rc->accum_p_qp += qp + rc->ip_offset; else rc->accum_p_qp += qp; } /* Before encoding a frame, choose a QP for it */ void x264_ratecontrol_start( x264_t *h, int i_force_qp ) { x264_ratecontrol_t *rc = h->rc; ratecontrol_entry_t *rce = NULL; x264_zone_t *zone = get_zone( h, h->fenc->i_frame ); float q; x264_emms(); if( zone && (!rc->prev_zone || zone->param != rc->prev_zone->param) ) x264_encoder_reconfig( h, zone->param ); rc->prev_zone = zone; rc->qp_force = i_force_qp; if( h->param.rc.b_stat_read ) { int frame = h->fenc->i_frame; assert( frame >= 0 && frame < rc->num_entries ); rce = h->rc->rce = &h->rc->entry[frame]; if( h->sh.i_type == SLICE_TYPE_B && h->param.analyse.i_direct_mv_pred == X264_DIRECT_PRED_AUTO ) { h->sh.b_direct_spatial_mv_pred = ( rce->direct_mode == 's' ); h->mb.b_direct_auto_read = ( rce->direct_mode == 's' || rce->direct_mode == 't' ); } } if( rc->b_vbv ) { memset( h->fdec->i_row_bits, 0, h->sps->i_mb_height * sizeof(int) ); rc->row_pred = &rc->row_preds[h->sh.i_type]; update_vbv_plan( h ); } if( h->sh.i_type != SLICE_TYPE_B ) { rc->bframes = 0; while( h->frames.current[rc->bframes] && IS_X264_TYPE_B(h->frames.current[rc->bframes]->i_type) ) rc->bframes++; } if( i_force_qp ) { q = i_force_qp - 1; } else if( rc->b_abr ) { q = qscale2qp( rate_estimate_qscale( h ) ); } else if( rc->b_2pass ) { rce->new_qscale = rate_estimate_qscale( h ); q = qscale2qp( rce->new_qscale ); } else /* CQP */ { if( h->sh.i_type == SLICE_TYPE_B && h->fdec->b_kept_as_ref ) q = ( rc->qp_constant[ SLICE_TYPE_B ] + rc->qp_constant[ SLICE_TYPE_P ] ) / 2; else q = rc->qp_constant[ h->sh.i_type ]; if( zone ) { if( zone->b_force_qp ) q += zone->i_qp - rc->qp_constant[SLICE_TYPE_P]; else q -= 6*log(zone->f_bitrate_factor)/log(2); } } rc->qpa_rc = rc->qpa_aq = 0; h->fdec->f_qp_avg_rc = h->fdec->f_qp_avg_aq = rc->qpm = rc->qp = x264_clip3( (int)(q + 0.5), 0, 51 ); rc->f_qpm = q; if( rce ) rce->new_qp = rc->qp; /* accum_p_qp needs to be here so that future frames can benefit from the * data before this frame is done. but this only works because threading * guarantees to not re-encode any frames. so the non-threaded case does * accum_p_qp later. */ if( h->param.i_threads > 1 ) accum_p_qp_update( h, rc->qp ); if( h->sh.i_type != SLICE_TYPE_B ) rc->last_non_b_pict_type = h->sh.i_type; } static double predict_row_size( x264_t *h, int y, int qp ) { /* average between two predictors: * absolute SATD, and scaled bit cost of the colocated row in the previous frame */ x264_ratecontrol_t *rc = h->rc; double pred_s = predict_size( rc->row_pred, qp2qscale(qp), h->fdec->i_row_satd[y] ); double pred_t = 0; if( h->sh.i_type != SLICE_TYPE_I && h->fref0[0]->i_type == h->fdec->i_type && h->fref0[0]->i_row_satd[y] > 0 && (abs(h->fref0[0]->i_row_satd[y] - h->fdec->i_row_satd[y]) < h->fdec->i_row_satd[y]/2)) { pred_t = h->fref0[0]->i_row_bits[y] * h->fdec->i_row_satd[y] / h->fref0[0]->i_row_satd[y] * qp2qscale(h->fref0[0]->i_row_qp[y]) / qp2qscale(qp); } if( pred_t == 0 ) pred_t = pred_s; return (pred_s + pred_t) / 2; } static double row_bits_so_far( x264_t *h, int y ) { int i; double bits = 0; for( i = 0; i <= y; i++ ) bits += h->fdec->i_row_bits[i]; return bits; } static double predict_row_size_sum( x264_t *h, int y, int qp ) { int i; double bits = row_bits_so_far(h, y); for( i = y+1; i < h->sps->i_mb_height; i++ ) bits += predict_row_size( h, i, qp ); return bits; } void x264_ratecontrol_mb( x264_t *h, int bits ) { x264_ratecontrol_t *rc = h->rc; const int y = h->mb.i_mb_y; x264_emms(); h->fdec->i_row_bits[y] += bits; rc->qpa_rc += rc->f_qpm; rc->qpa_aq += h->mb.i_qp; if( h->mb.i_mb_x != h->sps->i_mb_width - 1 || !rc->b_vbv) return; h->fdec->i_row_qp[y] = rc->qpm; if( h->sh.i_type == SLICE_TYPE_B ) { /* B-frames shouldn't use lower QP than their reference frames. * This code is a bit overzealous in limiting B-frame quantizers, but it helps avoid * underflows due to the fact that B-frames are not explicitly covered by VBV. */ if( y < h->sps->i_mb_height-1 ) { int i_estimated; int avg_qp = X264_MAX(h->fref0[0]->i_row_qp[y+1], h->fref1[0]->i_row_qp[y+1]) + rc->pb_offset * ((h->fenc->i_type == X264_TYPE_BREF) ? 0.5 : 1); rc->qpm = X264_MIN(X264_MAX( rc->qp, avg_qp), 51); //avg_qp could go higher than 51 due to pb_offset i_estimated = row_bits_so_far(h, y); //FIXME: compute full estimated size if (i_estimated > h->rc->frame_size_planned) x264_ratecontrol_set_estimated_size(h, i_estimated); } } else { update_predictor( rc->row_pred, qp2qscale(rc->qpm), h->fdec->i_row_satd[y], h->fdec->i_row_bits[y] ); /* tweak quality based on difference from predicted size */ if( y < h->sps->i_mb_height-1 && h->stat.i_slice_count[h->sh.i_type] > 0 ) { int prev_row_qp = h->fdec->i_row_qp[y]; int b0 = predict_row_size_sum( h, y, rc->qpm ); int b1 = b0; int i_qp_max = X264_MIN( prev_row_qp + h->param.rc.i_qp_step, h->param.rc.i_qp_max ); int i_qp_min = X264_MAX( prev_row_qp - h->param.rc.i_qp_step, h->param.rc.i_qp_min ); float buffer_left_planned = rc->buffer_fill - rc->frame_size_planned; float rc_tol = 1; float headroom = 0; /* Don't modify the row QPs until a sufficent amount of the bits of the frame have been processed, in case a flat */ /* area at the top of the frame was measured inaccurately. */ if(row_bits_so_far(h,y) < 0.05 * rc->frame_size_planned) return; headroom = buffer_left_planned/rc->buffer_size; if(h->sh.i_type != SLICE_TYPE_I) headroom /= 2; rc_tol += headroom; if( !rc->b_vbv_min_rate ) i_qp_min = X264_MAX( i_qp_min, h->sh.i_qp ); while( rc->qpm < i_qp_max && (b1 > rc->frame_size_planned * rc_tol || (rc->buffer_fill - b1 < buffer_left_planned * 0.5))) { rc->qpm ++; b1 = predict_row_size_sum( h, y, rc->qpm ); } /* avoid VBV underflow */ while( (rc->qpm < h->param.rc.i_qp_max) && (rc->buffer_fill - b1 < rc->buffer_size * 0.005)) { rc->qpm ++; b1 = predict_row_size_sum( h, y, rc->qpm ); } while( rc->qpm > i_qp_min && rc->qpm > h->fdec->i_row_qp[0] && ((b1 < rc->frame_size_planned * 0.8 && rc->qpm <= prev_row_qp) || b1 < (rc->buffer_fill - rc->buffer_size + rc->buffer_rate) * 1.1) ) { rc->qpm --; b1 = predict_row_size_sum( h, y, rc->qpm ); } x264_ratecontrol_set_estimated_size(h, b1); } } /* loses the fractional part of the frame-wise qp */ rc->f_qpm = rc->qpm; } int x264_ratecontrol_qp( x264_t *h ) { return h->rc->qpm; } /* In 2pass, force the same frame types as in the 1st pass */ int x264_ratecontrol_slice_type( x264_t *h, int frame_num ) { x264_ratecontrol_t *rc = h->rc; if( h->param.rc.b_stat_read ) { if( frame_num >= rc->num_entries ) { /* We could try to initialize everything required for ABR and * adaptive B-frames, but that would be complicated. * So just calculate the average QP used so far. */ int i; h->param.rc.i_qp_constant = (h->stat.i_slice_count[SLICE_TYPE_P] == 0) ? 24 : 1 + h->stat.f_slice_qp[SLICE_TYPE_P] / h->stat.i_slice_count[SLICE_TYPE_P]; rc->qp_constant[SLICE_TYPE_P] = x264_clip3( h->param.rc.i_qp_constant, 0, 51 ); rc->qp_constant[SLICE_TYPE_I] = x264_clip3( (int)( qscale2qp( qp2qscale( h->param.rc.i_qp_constant ) / fabs( h->param.rc.f_ip_factor )) + 0.5 ), 0, 51 ); rc->qp_constant[SLICE_TYPE_B] = x264_clip3( (int)( qscale2qp( qp2qscale( h->param.rc.i_qp_constant ) * fabs( h->param.rc.f_pb_factor )) + 0.5 ), 0, 51 ); x264_log(h, X264_LOG_ERROR, "2nd pass has more frames than 1st pass (%d)\n", rc->num_entries); x264_log(h, X264_LOG_ERROR, "continuing anyway, at constant QP=%d\n", h->param.rc.i_qp_constant); if( h->param.i_bframe_adaptive ) x264_log(h, X264_LOG_ERROR, "disabling adaptive B-frames\n"); for( i = 0; i < h->param.i_threads; i++ ) { h->thread[i]->rc->b_abr = 0; h->thread[i]->rc->b_2pass = 0; h->thread[i]->param.rc.i_rc_method = X264_RC_CQP; h->thread[i]->param.rc.b_stat_read = 0; h->thread[i]->param.i_bframe_adaptive = 0; h->thread[i]->param.b_pre_scenecut = 0; h->thread[i]->param.i_scenecut_threshold = -1; if( h->thread[i]->param.i_bframe > 1 ) h->thread[i]->param.i_bframe = 1; } return X264_TYPE_AUTO; } switch( rc->entry[frame_num].pict_type ) { case SLICE_TYPE_I: return rc->entry[frame_num].kept_as_ref ? X264_TYPE_IDR : X264_TYPE_I; case SLICE_TYPE_B: return rc->entry[frame_num].kept_as_ref ? X264_TYPE_BREF : X264_TYPE_B; case SLICE_TYPE_P: default: return X264_TYPE_P; } } else { return X264_TYPE_AUTO; } } /* After encoding one frame, save stats and update ratecontrol state */ void x264_ratecontrol_end( x264_t *h, int bits ) { x264_ratecontrol_t *rc = h->rc; const int *mbs = h->stat.frame.i_mb_count; int i; x264_emms(); h->stat.frame.i_mb_count_skip = mbs[P_SKIP] + mbs[B_SKIP]; h->stat.frame.i_mb_count_i = mbs[I_16x16] + mbs[I_8x8] + mbs[I_4x4]; h->stat.frame.i_mb_count_p = mbs[P_L0] + mbs[P_8x8]; for( i = B_DIRECT; i < B_8x8; i++ ) h->stat.frame.i_mb_count_p += mbs[i]; h->fdec->f_qp_avg_rc = rc->qpa_rc /= h->mb.i_mb_count; h->fdec->f_qp_avg_aq = rc->qpa_aq /= h->mb.i_mb_count; if( h->param.rc.b_stat_write ) { char c_type = h->sh.i_type==SLICE_TYPE_I ? (h->fenc->i_poc==0 ? 'I' : 'i') : h->sh.i_type==SLICE_TYPE_P ? 'P' : h->fenc->b_kept_as_ref ? 'B' : 'b'; int dir_frame = h->stat.frame.i_direct_score[1] - h->stat.frame.i_direct_score[0]; int dir_avg = h->stat.i_direct_score[1] - h->stat.i_direct_score[0]; char c_direct = h->mb.b_direct_auto_write ? ( dir_frame>0 ? 's' : dir_frame<0 ? 't' : dir_avg>0 ? 's' : dir_avg<0 ? 't' : '-' ) : '-'; fprintf( rc->p_stat_file_out, "in:%d out:%d type:%c q:%.2f tex:%d mv:%d misc:%d imb:%d pmb:%d smb:%d d:%c;\n", h->fenc->i_frame, h->i_frame, c_type, rc->qpa_rc, h->stat.frame.i_tex_bits, h->stat.frame.i_mv_bits, h->stat.frame.i_misc_bits, h->stat.frame.i_mb_count_i, h->stat.frame.i_mb_count_p, h->stat.frame.i_mb_count_skip, c_direct); } if( rc->b_abr ) { if( h->sh.i_type != SLICE_TYPE_B ) rc->cplxr_sum += bits * qp2qscale(rc->qpa_rc) / rc->last_rceq; else { /* Depends on the fact that B-frame's QP is an offset from the following P-frame's. * Not perfectly accurate with B-refs, but good enough. */ rc->cplxr_sum += bits * qp2qscale(rc->qpa_rc) / (rc->last_rceq * fabs(h->param.rc.f_pb_factor)); } rc->cplxr_sum *= rc->cbr_decay; rc->wanted_bits_window += rc->bitrate / rc->fps; rc->wanted_bits_window *= rc->cbr_decay; if( h->param.i_threads == 1 ) accum_p_qp_update( h, rc->qpa_rc ); } if( rc->b_2pass ) { rc->expected_bits_sum += qscale2bits( rc->rce, qp2qscale(rc->rce->new_qp) ); } if( h->mb.b_variable_qp ) { if( h->sh.i_type == SLICE_TYPE_B ) { rc->bframe_bits += bits; if( !h->frames.current[0] || !IS_X264_TYPE_B(h->frames.current[0]->i_type) ) { update_predictor( rc->pred_b_from_p, qp2qscale(rc->qpa_rc), h->fref1[h->i_ref1-1]->i_satd, rc->bframe_bits / rc->bframes ); rc->bframe_bits = 0; } } } update_vbv( h, bits ); } /**************************************************************************** * 2 pass functions ***************************************************************************/ /** * modify the bitrate curve from pass1 for one frame */ static double get_qscale(x264_t *h, ratecontrol_entry_t *rce, double rate_factor, int frame_num) { x264_ratecontrol_t *rcc= h->rc; double q; x264_zone_t *zone = get_zone( h, frame_num ); q = pow( rce->blurred_complexity, 1 - h->param.rc.f_qcompress ); // avoid NaN's in the rc_eq if(!isfinite(q) || rce->tex_bits + rce->mv_bits == 0) q = rcc->last_qscale; else { rcc->last_rceq = q; q /= rate_factor; rcc->last_qscale = q; } if( zone ) { if( zone->b_force_qp ) q = qp2qscale(zone->i_qp); else q /= zone->f_bitrate_factor; } return q; } static double get_diff_limited_q(x264_t *h, ratecontrol_entry_t *rce, double q) { x264_ratecontrol_t *rcc = h->rc; const int pict_type = rce->pict_type; // force I/B quants as a function of P quants const double last_p_q = rcc->last_qscale_for[SLICE_TYPE_P]; const double last_non_b_q= rcc->last_qscale_for[rcc->last_non_b_pict_type]; if( pict_type == SLICE_TYPE_I ) { double iq = q; double pq = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm ); double ip_factor = fabs( h->param.rc.f_ip_factor ); /* don't apply ip_factor if the following frame is also I */ if( rcc->accum_p_norm <= 0 ) q = iq; else if( h->param.rc.f_ip_factor < 0 ) q = iq / ip_factor; else if( rcc->accum_p_norm >= 1 ) q = pq / ip_factor; else q = rcc->accum_p_norm * pq / ip_factor + (1 - rcc->accum_p_norm) * iq; } else if( pict_type == SLICE_TYPE_B ) { if( h->param.rc.f_pb_factor > 0 ) q = last_non_b_q; if( !rce->kept_as_ref ) q *= fabs( h->param.rc.f_pb_factor ); } else if( pict_type == SLICE_TYPE_P && rcc->last_non_b_pict_type == SLICE_TYPE_P && rce->tex_bits == 0 ) { q = last_p_q; } /* last qscale / qdiff stuff */ if(rcc->last_non_b_pict_type==pict_type && (pict_type!=SLICE_TYPE_I || rcc->last_accum_p_norm < 1)) { double last_q = rcc->last_qscale_for[pict_type]; double max_qscale = last_q * rcc->lstep; double min_qscale = last_q / rcc->lstep; if (q > max_qscale) q = max_qscale; else if(q < min_qscale) q = min_qscale; } rcc->last_qscale_for[pict_type] = q; if(pict_type!=SLICE_TYPE_B) rcc->last_non_b_pict_type = pict_type; if(pict_type==SLICE_TYPE_I) { rcc->last_accum_p_norm = rcc->accum_p_norm; rcc->accum_p_norm = 0; rcc->accum_p_qp = 0; } if(pict_type==SLICE_TYPE_P) { float mask = 1 - pow( (float)rce->i_count / rcc->nmb, 2 ); rcc->accum_p_qp = mask * (qscale2qp(q) + rcc->accum_p_qp); rcc->accum_p_norm = mask * (1 + rcc->accum_p_norm); } return q; } static double predict_size( predictor_t *p, double q, double var ) { return p->coeff*var / (q*p->count); } static void update_predictor( predictor_t *p, double q, double var, double bits ) { if( var < 10 ) return; p->count *= p->decay; p->coeff *= p->decay; p->count ++; p->coeff += bits*q / var; } // update VBV after encoding a frame static void update_vbv( x264_t *h, int bits ) { x264_ratecontrol_t *rcc = h->rc; x264_ratecontrol_t *rct = h->thread[0]->rc; if( rcc->last_satd >= h->mb.i_mb_count ) update_predictor( &rct->pred[h->sh.i_type], qp2qscale(rcc->qpa_rc), rcc->last_satd, bits ); if( !rcc->b_vbv ) return; rct->buffer_fill_final += rct->buffer_rate - bits; if( rct->buffer_fill_final < 0 ) x264_log( h, X264_LOG_WARNING, "VBV underflow (%.0f bits)\n", rct->buffer_fill_final ); rct->buffer_fill_final = x264_clip3f( rct->buffer_fill_final, 0, rct->buffer_size ); } // provisionally update VBV according to the planned size of all frames currently in progress static void update_vbv_plan( x264_t *h ) { x264_ratecontrol_t *rcc = h->rc; rcc->buffer_fill = h->thread[0]->rc->buffer_fill_final; if( h->param.i_threads > 1 ) { int j = h->rc - h->thread[0]->rc; int i; for( i=1; i<h->param.i_threads; i++ ) { x264_t *t = h->thread[ (j+i)%h->param.i_threads ]; double bits = t->rc->frame_size_planned; if( !t->b_thread_active ) continue; bits = X264_MAX(bits, x264_ratecontrol_get_estimated_size(t)); rcc->buffer_fill += rcc->buffer_rate - bits; rcc->buffer_fill = x264_clip3( rcc->buffer_fill, 0, rcc->buffer_size ); } } } // apply VBV constraints and clip qscale to between lmin and lmax static double clip_qscale( x264_t *h, int pict_type, double q ) { x264_ratecontrol_t *rcc = h->rc; double lmin = rcc->lmin[pict_type]; double lmax = rcc->lmax[pict_type]; double q0 = q; /* B-frames are not directly subject to VBV, * since they are controlled by the P-frames' QPs. * FIXME: in 2pass we could modify previous frames' QP too, * instead of waiting for the buffer to fill */ if( rcc->b_vbv && ( pict_type == SLICE_TYPE_P || ( pict_type == SLICE_TYPE_I && rcc->last_non_b_pict_type == SLICE_TYPE_I ) ) ) { if( rcc->buffer_fill/rcc->buffer_size < 0.5 ) q /= x264_clip3f( 2.0*rcc->buffer_fill/rcc->buffer_size, 0.5, 1.0 ); } if( rcc->b_vbv && rcc->last_satd > 0 ) { /* Now a hard threshold to make sure the frame fits in VBV. * This one is mostly for I-frames. */ double bits = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd ); double qf = 1.0; if( bits > rcc->buffer_fill/2 ) qf = x264_clip3f( rcc->buffer_fill/(2*bits), 0.2, 1.0 ); q /= qf; bits *= qf; if( bits < rcc->buffer_rate/2 ) q *= bits*2/rcc->buffer_rate; q = X264_MAX( q0, q ); /* Check B-frame complexity, and use up any bits that would * overflow before the next P-frame. */ if( h->sh.i_type == SLICE_TYPE_P ) { int nb = rcc->bframes; double pbbits = bits; double bbits = predict_size( rcc->pred_b_from_p, q * h->param.rc.f_pb_factor, rcc->last_satd ); double space; if( bbits > rcc->buffer_rate ) nb = 0; pbbits += nb * bbits; space = rcc->buffer_fill + (1+nb)*rcc->buffer_rate - rcc->buffer_size; if( pbbits < space ) { q *= X264_MAX( pbbits / space, bits / (0.5 * rcc->buffer_size) ); } q = X264_MAX( q0-5, q ); } if( !rcc->b_vbv_min_rate ) q = X264_MAX( q0, q ); } if(lmin==lmax) return lmin; else if(rcc->b_2pass) { double min2 = log(lmin); double max2 = log(lmax); q = (log(q) - min2)/(max2-min2) - 0.5; q = 1.0/(1.0 + exp(-4*q)); q = q*(max2-min2) + min2; return exp(q); } else return x264_clip3f(q, lmin, lmax); } // update qscale for 1 frame based on actual bits used so far static float rate_estimate_qscale( x264_t *h ) { float q; x264_ratecontrol_t *rcc = h->rc; ratecontrol_entry_t rce; int pict_type = h->sh.i_type; double lmin = rcc->lmin[pict_type]; double lmax = rcc->lmax[pict_type]; int64_t total_bits = 8*(h->stat.i_slice_size[SLICE_TYPE_I] + h->stat.i_slice_size[SLICE_TYPE_P] + h->stat.i_slice_size[SLICE_TYPE_B]); if( rcc->b_2pass ) { rce = *rcc->rce; if(pict_type != rce.pict_type) { x264_log(h, X264_LOG_ERROR, "slice=%c but 2pass stats say %c\n", slice_type_to_char[pict_type], slice_type_to_char[rce.pict_type]); } } if( pict_type == SLICE_TYPE_B ) { /* B-frames don't have independent ratecontrol, but rather get the * average QP of the two adjacent P-frames + an offset */ int i0 = IS_X264_TYPE_I(h->fref0[0]->i_type); int i1 = IS_X264_TYPE_I(h->fref1[0]->i_type); int dt0 = abs(h->fenc->i_poc - h->fref0[0]->i_poc); int dt1 = abs(h->fenc->i_poc - h->fref1[0]->i_poc); float q0 = h->fref0[0]->f_qp_avg_rc; float q1 = h->fref1[0]->f_qp_avg_rc; if( h->fref0[0]->i_type == X264_TYPE_BREF ) q0 -= rcc->pb_offset/2; if( h->fref1[0]->i_type == X264_TYPE_BREF ) q1 -= rcc->pb_offset/2; if(i0 && i1) q = (q0 + q1) / 2 + rcc->ip_offset; else if(i0) q = q1; else if(i1) q = q0; else q = (q0*dt1 + q1*dt0) / (dt0 + dt1); if(h->fenc->b_kept_as_ref) q += rcc->pb_offset/2; else q += rcc->pb_offset; rcc->frame_size_planned = predict_size( rcc->pred_b_from_p, q, h->fref1[h->i_ref1-1]->i_satd ); x264_ratecontrol_set_estimated_size(h, rcc->frame_size_planned); rcc->last_satd = 0; return qp2qscale(q); } else { double abr_buffer = 2 * rcc->rate_tolerance * rcc->bitrate; if( rcc->b_2pass ) { //FIXME adjust abr_buffer based on distance to the end of the video int64_t diff; int64_t predicted_bits = total_bits; if( rcc->b_vbv ) { if( h->param.i_threads > 1 ) { int j = h->rc - h->thread[0]->rc; int i; for( i=1; i<h->param.i_threads; i++ ) { x264_t *t = h->thread[ (j+i)%h->param.i_threads ]; double bits = t->rc->frame_size_planned; if( !t->b_thread_active ) continue; bits = X264_MAX(bits, x264_ratecontrol_get_estimated_size(t)); predicted_bits += (int64_t)bits; } } } else { if( h->fenc->i_frame < h->param.i_threads ) predicted_bits += (int64_t)h->fenc->i_frame * rcc->bitrate / rcc->fps; else predicted_bits += (int64_t)(h->param.i_threads - 1) * rcc->bitrate / rcc->fps; } diff = predicted_bits - (int64_t)rce.expected_bits; q = rce.new_qscale; q /= x264_clip3f((double)(abr_buffer - diff) / abr_buffer, .5, 2); if( ((h->fenc->i_frame + 1 - h->param.i_threads) >= rcc->fps) && (rcc->expected_bits_sum > 0)) { /* Adjust quant based on the difference between * achieved and expected bitrate so far */ double time = (double)h->fenc->i_frame / rcc->num_entries; double w = x264_clip3f( time*100, 0.0, 1.0 ); q *= pow( (double)total_bits / rcc->expected_bits_sum, w ); } if( rcc->b_vbv ) { /* Do not overflow vbv */ double expected_size = qscale2bits(&rce, q); double expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size; double expected_fullness = rce.expected_vbv / rcc->buffer_size; double qmax = q*(2 - expected_fullness); double size_constraint = 1 + expected_fullness; qmax = X264_MAX(qmax, rce.new_qscale); if (expected_fullness < .05) qmax = lmax; qmax = X264_MIN(qmax, lmax); while( ((expected_vbv < rce.expected_vbv/size_constraint) && (q < qmax)) || ((expected_vbv < 0) && (q < lmax))) { q *= 1.05; expected_size = qscale2bits(&rce, q); expected_vbv = rcc->buffer_fill + rcc->buffer_rate - expected_size; } rcc->last_satd = x264_rc_analyse_slice( h ); } q = x264_clip3f( q, lmin, lmax ); } else /* 1pass ABR */ { /* Calculate the quantizer which would have produced the desired * average bitrate if it had been applied to all frames so far. * Then modulate that quant based on the current frame's complexity * relative to the average complexity so far (using the 2pass RCEQ). * Then bias the quant up or down if total size so far was far from * the target. * Result: Depending on the value of rate_tolerance, there is a * tradeoff between quality and bitrate precision. But at large * tolerances, the bit distribution approaches that of 2pass. */ double wanted_bits, overflow=1, lmin, lmax; rcc->last_satd = x264_rc_analyse_slice( h ); rcc->short_term_cplxsum *= 0.5; rcc->short_term_cplxcount *= 0.5; rcc->short_term_cplxsum += rcc->last_satd; rcc->short_term_cplxcount ++; rce.tex_bits = rcc->last_satd; rce.blurred_complexity = rcc->short_term_cplxsum / rcc->short_term_cplxcount; rce.mv_bits = 0; rce.p_count = rcc->nmb; rce.i_count = 0; rce.s_count = 0; rce.qscale = 1; rce.pict_type = pict_type; if( h->param.rc.i_rc_method == X264_RC_CRF ) { q = get_qscale( h, &rce, rcc->rate_factor_constant, h->fenc->i_frame ); } else { int i_frame_done = h->fenc->i_frame + 1 - h->param.i_threads; q = get_qscale( h, &rce, rcc->wanted_bits_window / rcc->cplxr_sum, h->fenc->i_frame ); // FIXME is it simpler to keep track of wanted_bits in ratecontrol_end? wanted_bits = i_frame_done * rcc->bitrate / rcc->fps; if( wanted_bits > 0 ) { abr_buffer *= X264_MAX( 1, sqrt(i_frame_done/25) ); overflow = x264_clip3f( 1.0 + (total_bits - wanted_bits) / abr_buffer, .5, 2 ); q *= overflow; } } if( pict_type == SLICE_TYPE_I && h->param.i_keyint_max > 1 /* should test _next_ pict type, but that isn't decided yet */ && rcc->last_non_b_pict_type != SLICE_TYPE_I ) { q = qp2qscale( rcc->accum_p_qp / rcc->accum_p_norm ); q /= fabs( h->param.rc.f_ip_factor ); } else if( h->i_frame > 0 ) { /* Asymmetric clipping, because symmetric would prevent * overflow control in areas of rapidly oscillating complexity */ lmin = rcc->last_qscale_for[pict_type] / rcc->lstep; lmax = rcc->last_qscale_for[pict_type] * rcc->lstep; if( overflow > 1.1 && h->i_frame > 3 ) lmax *= rcc->lstep; else if( overflow < 0.9 ) lmin /= rcc->lstep; q = x264_clip3f(q, lmin, lmax); } else if( h->param.rc.i_rc_method == X264_RC_CRF ) { q = qp2qscale( ABR_INIT_QP ) / fabs( h->param.rc.f_ip_factor ); } //FIXME use get_diff_limited_q() ? q = clip_qscale( h, pict_type, q ); } rcc->last_qscale_for[pict_type] = rcc->last_qscale = q; if( !(rcc->b_2pass && !rcc->b_vbv) && h->fenc->i_frame == 0 ) rcc->last_qscale_for[SLICE_TYPE_P] = q; if( rcc->b_2pass && rcc->b_vbv) rcc->frame_size_planned = qscale2bits(&rce, q); else rcc->frame_size_planned = predict_size( &rcc->pred[h->sh.i_type], q, rcc->last_satd ); x264_ratecontrol_set_estimated_size(h, rcc->frame_size_planned); return q; } } void x264_thread_sync_ratecontrol( x264_t *cur, x264_t *prev, x264_t *next ) { if( cur != prev ) { #define COPY(var) memcpy(&cur->rc->var, &prev->rc->var, sizeof(cur->rc->var)) /* these vars are updated in x264_ratecontrol_start() * so copy them from the context that most recently started (prev) * to the context that's about to start (cur). */ COPY(accum_p_qp); COPY(accum_p_norm); COPY(last_satd); COPY(last_rceq); COPY(last_qscale_for); COPY(last_non_b_pict_type); COPY(short_term_cplxsum); COPY(short_term_cplxcount); COPY(bframes); COPY(prev_zone); #undef COPY } if( cur != next ) { #define COPY(var) next->rc->var = cur->rc->var /* these vars are updated in x264_ratecontrol_end() * so copy them from the context that most recently ended (cur) * to the context that's about to end (next) */ COPY(cplxr_sum); COPY(expected_bits_sum); COPY(wanted_bits_window); COPY(bframe_bits); #undef COPY } //FIXME row_preds[] (not strictly necessary, but would improve prediction) /* the rest of the variables are either constant or thread-local */ } static int find_underflow( x264_t *h, double *fills, int *t0, int *t1, int over ) { /* find an interval ending on an overflow or underflow (depending on whether * we're adding or removing bits), and starting on the earliest frame that * can influence the buffer fill of that end frame. */ x264_ratecontrol_t *rcc = h->rc; const double buffer_min = (over ? .1 : .1) * rcc->buffer_size; const double buffer_max = .9 * rcc->buffer_size; double fill = fills[*t0-1]; double parity = over ? 1. : -1.; int i, start=-1, end=-1; for(i = *t0; i < rcc->num_entries; i++) { fill += (rcc->buffer_rate - qscale2bits(&rcc->entry[i], rcc->entry[i].new_qscale)) * parity; fill = x264_clip3f(fill, 0, rcc->buffer_size); fills[i] = fill; if(fill <= buffer_min || i == 0) { if(end >= 0) break; start = i; } else if(fill >= buffer_max && start >= 0) end = i; } *t0 = start; *t1 = end; return start>=0 && end>=0; } static int fix_underflow( x264_t *h, int t0, int t1, double adjustment, double qscale_min, double qscale_max) { x264_ratecontrol_t *rcc = h->rc; double qscale_orig, qscale_new; int i; int adjusted = 0; if(t0 > 0) t0++; for(i = t0; i <= t1; i++) { qscale_orig = rcc->entry[i].new_qscale; qscale_orig = x264_clip3f(qscale_orig, qscale_min, qscale_max); qscale_new = qscale_orig * adjustment; qscale_new = x264_clip3f(qscale_new, qscale_min, qscale_max); rcc->entry[i].new_qscale = qscale_new; adjusted = adjusted || (qscale_new != qscale_orig); } return adjusted; } static double count_expected_bits( x264_t *h ) { x264_ratecontrol_t *rcc = h->rc; double expected_bits = 0; int i; for(i = 0; i < rcc->num_entries; i++) { ratecontrol_entry_t *rce = &rcc->entry[i]; rce->expected_bits = expected_bits; expected_bits += qscale2bits(rce, rce->new_qscale); } return expected_bits; } static void vbv_pass2( x264_t *h ) { /* for each interval of buffer_full .. underflow, uniformly increase the qp of all * frames in the interval until either buffer is full at some intermediate frame or the * last frame in the interval no longer underflows. Recompute intervals and repeat. * Then do the converse to put bits back into overflow areas until target size is met */ x264_ratecontrol_t *rcc = h->rc; double *fills = x264_malloc((rcc->num_entries+1)*sizeof(double)); double all_available_bits = h->param.rc.i_bitrate * 1000. * rcc->num_entries / rcc->fps; double expected_bits = 0; double adjustment; double prev_bits = 0; int i, t0, t1; double qscale_min = qp2qscale(h->param.rc.i_qp_min); double qscale_max = qp2qscale(h->param.rc.i_qp_max); int iterations = 0; int adj_min, adj_max; fills++; /* adjust overall stream size */ do { iterations++; prev_bits = expected_bits; if(expected_bits != 0) { /* not first iteration */ adjustment = X264_MAX(X264_MIN(expected_bits / all_available_bits, 0.999), 0.9); fills[-1] = rcc->buffer_size * h->param.rc.f_vbv_buffer_init; t0 = 0; /* fix overflows */ adj_min = 1; while(adj_min && find_underflow(h, fills, &t0, &t1, 1)) { adj_min = fix_underflow(h, t0, t1, adjustment, qscale_min, qscale_max); t0 = t1; } } fills[-1] = rcc->buffer_size * (1. - h->param.rc.f_vbv_buffer_init); t0 = 0; /* fix underflows -- should be done after overflow, as we'd better undersize target than underflowing VBV */ adj_max = 1; while(adj_max && find_underflow(h, fills, &t0, &t1, 0)) adj_max = fix_underflow(h, t0, t1, 1.001, qscale_min, qscale_max); expected_bits = count_expected_bits(h); } while((expected_bits < .995*all_available_bits) && ((int)(expected_bits+.5) > (int)(prev_bits+.5)) ); if (!adj_max) x264_log( h, X264_LOG_WARNING, "vbv-maxrate issue, qpmax or vbv-maxrate too low\n"); /* store expected vbv filling values for tracking when encoding */ for(i = 0; i < rcc->num_entries; i++) rcc->entry[i].expected_vbv = rcc->buffer_size - fills[i]; x264_free(fills-1); } static int init_pass2( x264_t *h ) { x264_ratecontrol_t *rcc = h->rc; uint64_t all_const_bits = 0; uint64_t all_available_bits = (uint64_t)(h->param.rc.i_bitrate * 1000. * rcc->num_entries / rcc->fps); double rate_factor, step, step_mult; double qblur = h->param.rc.f_qblur; double cplxblur = h->param.rc.f_complexity_blur; const int filter_size = (int)(qblur*4) | 1; double expected_bits; double *qscale, *blurred_qscale; int i; /* find total/average complexity & const_bits */ for(i=0; i<rcc->num_entries; i++) { ratecontrol_entry_t *rce = &rcc->entry[i]; all_const_bits += rce->misc_bits; } if( all_available_bits < all_const_bits) { x264_log(h, X264_LOG_ERROR, "requested bitrate is too low. estimated minimum is %d kbps\n", (int)(all_const_bits * rcc->fps / (rcc->num_entries * 1000.))); return -1; } /* Blur complexities, to reduce local fluctuation of QP. * We don't blur the QPs directly, because then one very simple frame * could drag down the QP of a nearby complex frame and give it more * bits than intended. */ for(i=0; i<rcc->num_entries; i++) { ratecontrol_entry_t *rce = &rcc->entry[i]; double weight_sum = 0; double cplx_sum = 0; double weight = 1.0; double gaussian_weight; int j; /* weighted average of cplx of future frames */ for(j=1; j<cplxblur*2 && j<rcc->num_entries-i; j++) { ratecontrol_entry_t *rcj = &rcc->entry[i+j]; weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 ); if(weight < .0001) break; gaussian_weight = weight * exp(-j*j/200.0); weight_sum += gaussian_weight; cplx_sum += gaussian_weight * (qscale2bits(rcj, 1) - rcj->misc_bits); } /* weighted average of cplx of past frames */ weight = 1.0; for(j=0; j<=cplxblur*2 && j<=i; j++) { ratecontrol_entry_t *rcj = &rcc->entry[i-j]; gaussian_weight = weight * exp(-j*j/200.0); weight_sum += gaussian_weight; cplx_sum += gaussian_weight * (qscale2bits(rcj, 1) - rcj->misc_bits); weight *= 1 - pow( (float)rcj->i_count / rcc->nmb, 2 ); if(weight < .0001) break; } rce->blurred_complexity = cplx_sum / weight_sum; } qscale = x264_malloc(sizeof(double)*rcc->num_entries); if(filter_size > 1) blurred_qscale = x264_malloc(sizeof(double)*rcc->num_entries); else blurred_qscale = qscale; /* Search for a factor which, when multiplied by the RCEQ values from * each frame, adds up to the desired total size. * There is no exact closed-form solution because of VBV constraints and * because qscale2bits is not invertible, but we can start with the simple * approximation of scaling the 1st pass by the ratio of bitrates. * The search range is probably overkill, but speed doesn't matter here. */ expected_bits = 1; for(i=0; i<rcc->num_entries; i++) expected_bits += qscale2bits(&rcc->entry[i], get_qscale(h, &rcc->entry[i], 1.0, i)); step_mult = all_available_bits / expected_bits; rate_factor = 0; for(step = 1E4 * step_mult; step > 1E-7 * step_mult; step *= 0.5) { expected_bits = 0; rate_factor += step; rcc->last_non_b_pict_type = -1; rcc->last_accum_p_norm = 1; rcc->accum_p_norm = 0; /* find qscale */ for(i=0; i<rcc->num_entries; i++) { qscale[i] = get_qscale(h, &rcc->entry[i], rate_factor, i); } /* fixed I/B qscale relative to P */ for(i=rcc->num_entries-1; i>=0; i--) { qscale[i] = get_diff_limited_q(h, &rcc->entry[i], qscale[i]); assert(qscale[i] >= 0); } /* smooth curve */ if(filter_size > 1) { assert(filter_size%2==1); for(i=0; i<rcc->num_entries; i++) { ratecontrol_entry_t *rce = &rcc->entry[i]; int j; double q=0.0, sum=0.0; for(j=0; j<filter_size; j++) { int index = i+j-filter_size/2; double d = index-i; double coeff = qblur==0 ? 1.0 : exp(-d*d/(qblur*qblur)); if(index < 0 || index >= rcc->num_entries) continue; if(rce->pict_type != rcc->entry[index].pict_type) continue; q += qscale[index] * coeff; sum += coeff; } blurred_qscale[i] = q/sum; } } /* find expected bits */ for(i=0; i<rcc->num_entries; i++) { ratecontrol_entry_t *rce = &rcc->entry[i]; rce->new_qscale = clip_qscale(h, rce->pict_type, blurred_qscale[i]); assert(rce->new_qscale >= 0); expected_bits += qscale2bits(rce, rce->new_qscale); } if(expected_bits > all_available_bits) rate_factor -= step; } x264_free(qscale); if(filter_size > 1) x264_free(blurred_qscale); if(rcc->b_vbv) vbv_pass2(h); expected_bits = count_expected_bits(h); if(fabs(expected_bits/all_available_bits - 1.0) > 0.01) { double avgq = 0; for(i=0; i<rcc->num_entries; i++) avgq += rcc->entry[i].new_qscale; avgq = qscale2qp(avgq / rcc->num_entries); if ((expected_bits > all_available_bits) || (!rcc->b_vbv)) x264_log(h, X264_LOG_WARNING, "Error: 2pass curve failed to converge\n"); x264_log(h, X264_LOG_WARNING, "target: %.2f kbit/s, expected: %.2f kbit/s, avg QP: %.4f\n", (float)h->param.rc.i_bitrate, expected_bits * rcc->fps / (rcc->num_entries * 1000.), avgq); if(expected_bits < all_available_bits && avgq < h->param.rc.i_qp_min + 2) { if(h->param.rc.i_qp_min > 0) x264_log(h, X264_LOG_WARNING, "try reducing target bitrate or reducing qp_min (currently %d)\n", h->param.rc.i_qp_min); else x264_log(h, X264_LOG_WARNING, "try reducing target bitrate\n"); } else if(expected_bits > all_available_bits && avgq > h->param.rc.i_qp_max - 2) { if(h->param.rc.i_qp_max < 51) x264_log(h, X264_LOG_WARNING, "try increasing target bitrate or increasing qp_max (currently %d)\n", h->param.rc.i_qp_max); else x264_log(h, X264_LOG_WARNING, "try increasing target bitrate\n"); } else if(!(rcc->b_2pass && rcc->b_vbv)) x264_log(h, X264_LOG_WARNING, "internal error\n"); } return 0; }
atomic-3.c
/* { dg-do run } */ /* { dg-options "-fopenmp -O0" } */ #include <omp.h> #include <stdlib.h> short e[64]; int g; _Complex double d, f; int num_threads; __attribute__((noinline)) void foo (int x, long long y) { #pragma omp parallel num_threads (4) { int i; #pragma omp barrier for (i = 0; i < 2400; i++) { if (i == 0) num_threads = omp_get_num_threads (); #pragma omp atomic e[0] += x; #pragma omp atomic e[16] += x; #pragma omp atomic g += y; #pragma omp atomic __real__ d += x; #pragma omp atomic __imag__ f += x; } } } int main (void) { int i; foo (3, 3LL); if (g != 3 * 2400 * num_threads || __real__ d != g || __imag__ d != 0 || __real__ f != 0 || __imag__ f != g) abort (); for (i = 0; i < 64; i++) if (e[i] != ((i && i != 16) ? 0 : g)) abort (); return 0; }
GB_binop__lxor_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_08__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_02__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_04__lxor_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_int64) // A*D function (colscale): GB (_AxD__lxor_int64) // D*A function (rowscale): GB (_DxB__lxor_int64) // C+=B function (dense accum): GB (_Cdense_accumB__lxor_int64) // C+=b function (dense accum): GB (_Cdense_accumb__lxor_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_int64) // C=scalar+B GB (_bind1st__lxor_int64) // C=scalar+B' GB (_bind1st_tran__lxor_int64) // C=A+scalar GB (_bind2nd__lxor_int64) // C=A'+scalar GB (_bind2nd_tran__lxor_int64) // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = ((x != 0) != (y != 0)) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LXOR || GxB_NO_INT64 || GxB_NO_LXOR_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__lxor_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__lxor_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__lxor_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__lxor_int64) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__lxor_int64) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__lxor_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__lxor_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__lxor_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__lxor_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__lxor_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__lxor_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = ((x != 0) != (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__lxor_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = ((aij != 0) != (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB (_bind1st_tran__lxor_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB (_bind2nd_tran__lxor_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
profile.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % 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 declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/linked-list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/option-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/tree.h> #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType,ExceptionInfo *); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* Typedef declarations */ struct _ProfileInfo { char *name; size_t length; unsigned char *info; size_t signature; }; typedef struct _CMSExceptionInfo { Image *image; ExceptionInfo *exception; } CMSExceptionInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) typedef struct _LCMSInfo { ColorspaceType colorspace; cmsUInt32Number type; size_t channels; cmsHPROFILE profile; int intent; double scale, translate; void **magick_restrict pixels; } LCMSInfo; #if LCMS_VERSION < 2060 static void* cmsGetContextUserData(cmsContext ContextID) { return(ContextID); } static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData) { magick_unreferenced(Plugin); return((cmsContext) UserData); } static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID), cmsLogErrorHandlerFunction Fn) { magick_unreferenced(ContextID); cmsSetLogErrorHandler(Fn); } static void cmsDeleteContext(cmsContext magick_unused(ContextID)) { magick_unreferenced(ContextID); } #endif static void **DestroyPixelThreadSet(void **pixels) { register ssize_t i; if (pixels == (void **) NULL) return((void **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (void *) NULL) pixels[i]=RelinquishMagickMemory(pixels[i]); pixels=(void **) RelinquishMagickMemory(pixels); return(pixels); } static void **AcquirePixelThreadSet(const size_t columns, const size_t channels,MagickBooleanType highres) { register ssize_t i; size_t number_threads; size_t size; void **pixels; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(void **) AcquireQuantumMemory(number_threads,sizeof(*pixels)); if (pixels == (void **) NULL) return((void **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); size=sizeof(double); if (highres == MagickFalse) size=sizeof(Quantum); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=AcquireQuantumMemory(columns,channels*size); if (pixels[i] == (void *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { register ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info, const LCMSInfo *target_info,const cmsUInt32Number flags, cmsContext cms_context) { cmsHTRANSFORM *transform; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) memset(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile, source_info->type,target_info->profile,target_info->type, target_info->intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { CMSExceptionInfo *cms_exception; ExceptionInfo *exception; Image *image; cms_exception=(CMSExceptionInfo *) cmsGetContextUserData(context); if (cms_exception == (CMSExceptionInfo *) NULL) return; exception=cms_exception->exception; if (exception == (ExceptionInfo *) NULL) return; image=cms_exception->image; if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s'","unknown context"); return; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s', %s (#%u)",image->filename, message != (char *) NULL ? message : "no message",severity); } static void TransformDoublePixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { #define GetLCMSPixel(source_info,pixel) \ (source_info->scale*QuantumScale*(pixel)+source_info->translate) #define SetLCMSPixel(target_info,pixel) \ ClampToQuantum(target_info->scale*QuantumRange*(pixel)+target_info->translate) register double *p; register ssize_t x; p=(double *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetLCMSPixel(source_info,GetPixelRed(image,q)); if (source_info->channels > 1) { *p++=GetLCMSPixel(source_info,GetPixelGreen(image,q)); *p++=GetLCMSPixel(source_info,GetPixelBlue(image,q)); } if (source_info->channels > 3) *p++=GetLCMSPixel(source_info,GetPixelBlack(image,q)); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(double *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,SetLCMSPixel(target_info,*p),q); else SetPixelRed(image,SetLCMSPixel(target_info,*p),q); p++; if (target_info->channels > 1) { SetPixelGreen(image,SetLCMSPixel(target_info,*p),q); p++; SetPixelBlue(image,SetLCMSPixel(target_info,*p),q); p++; } if (target_info->channels > 3) { SetPixelBlack(image,SetLCMSPixel(target_info,*p),q); p++; } q+=GetPixelChannels(image); } } static void TransformQuantumPixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { register Quantum *p; register ssize_t x; p=(Quantum *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetPixelRed(image,q); if (source_info->channels > 1) { *p++=GetPixelGreen(image,q); *p++=GetPixelBlue(image,q); } if (source_info->channels > 3) *p++=GetPixelBlack(image,q); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(Quantum *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,*p++,q); else SetPixelRed(image,*p++,q); if (target_info->channels > 1) { SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); } if (target_info->channels > 3) SetPixelBlack(image,*p++,q); q+=GetPixelChannels(image); } } #endif static MagickBooleanType SetsRGBImageProfile(Image *image, ExceptionInfo *exception) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length,ExceptionInfo *exception) { #define ProfileImageTag "Profile/Image" #ifndef TYPE_XYZ_8 #define TYPE_XYZ_8 (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(1)) #endif #define ThrowProfileException(severity,tag,context) \ { \ if (profile != (StringInfo *) NULL) \ profile=DestroyStringInfo(profile); \ if (cms_context != (cmsContext) NULL) \ cmsDeleteContext(cms_context); \ if (source_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_info.profile); \ if (target_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_info.profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile,exception); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace",exception); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image,exception); value=GetImageProperty(image,"exif:InteroperabilityIndex",exception); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image,exception); icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (LCMS)",image->filename); #else { cmsContext cms_context; CMSExceptionInfo cms_exception; LCMSInfo source_info, target_info; /* Transform pixel colors as defined by the color profiles. */ cms_exception.image=image; cms_exception.exception=exception; cms_context=cmsCreateContext(NULL,&cms_exception); if (cms_context == (cmsContext) NULL) ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); cmsSetLogErrorHandlerTHR(cms_context,CMSExceptionHandler); source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_info.profile == (cmsHPROFILE) NULL) { cmsDeleteContext(cms_context); ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile,exception); else { CacheView *image_view; cmsColorSpaceSignature signature; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags; #if !defined(MAGICKCORE_HDRI_SUPPORT) const char *artifact; #endif MagickBooleanType highres; MagickOffsetType progress; ssize_t y; target_info.profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_info.profile=source_info.profile; source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(icc_profile), (cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_info.profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } highres=MagickTrue; #if !defined(MAGICKCORE_HDRI_SUPPORT) artifact=GetImageArtifact(image,"profile:highres-transform"); if (IsStringFalse(artifact) != MagickFalse) highres=MagickFalse; #endif source_info.scale=1.0; source_info.translate=0.0; source_info.colorspace=sRGBColorspace; source_info.channels=3; switch (cmsGetColorSpace(source_info.profile)) { case cmsSigCmykData: { source_info.colorspace=CMYKColorspace; source_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; source_info.scale=100.0; } break; } case cmsSigGrayData: { source_info.colorspace=GRAYColorspace; source_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { source_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_Lab_DBL; source_info.scale=100.0; source_info.translate=(-0.5); } break; } case cmsSigRgbData: { source_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif source_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { source_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } signature=cmsGetPCS(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_info.profile); target_info.scale=1.0; target_info.translate=0.0; target_info.channels=3; switch (signature) { case cmsSigCmykData: { target_info.colorspace=CMYKColorspace; target_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; target_info.scale=0.01; } break; } case cmsSigGrayData: { target_info.colorspace=GRAYColorspace; target_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { target_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_Lab_DBL; target_info.scale=0.01; target_info.translate=0.5; } break; } case cmsSigRgbData: { target_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif target_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { target_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } switch (image->rendering_intent) { case AbsoluteIntent: { target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC; break; } case PerceptualIntent: { target_info.intent=INTENT_PERCEPTUAL; break; } case RelativeIntent: { target_info.intent=INTENT_RELATIVE_COLORIMETRIC; break; } case SaturationIntent: { target_info.intent=INTENT_SATURATION; break; } default: { target_info.intent=INTENT_PERCEPTUAL; break; } } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(&source_info,&target_info, flags,cms_context); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_info.pixels=AcquirePixelThreadSet(image->columns, source_info.channels,highres); target_info.pixels=AcquirePixelThreadSet(image->columns, target_info.channels,highres); if ((source_info.pixels == (void **) NULL) || (target_info.pixels == (void **) NULL)) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if (source_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); return(MagickFalse); } if (target_info.colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_info.colorspace,exception); progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } if (highres != MagickFalse) TransformDoublePixels(id,image,&source_info,&target_info,transform,q); else TransformQuantumPixels(id,image,&source_info,&target_info,transform,q); sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,ProfileImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_info.colorspace,exception); switch (signature) { case cmsSigRgbData: { image->type=image->alpha_trait == UndefinedPixelTrait ? TrueColorType : TrueColorAlphaType; break; } case cmsSigCmykData: { image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; break; } case cmsSigGrayData: { image->type=image->alpha_trait == UndefinedPixelTrait ? GrayscaleType : GrayscaleAlphaType; break; } default: break; } target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) && (cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile,exception); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); } (void) cmsCloseProfile(source_info.profile); cmsDeleteContext(cms_context); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) memcpy(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) memcpy(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) memcpy(extract_profile->datum,datum,offset-4); WriteResourceLong(extract_profile->datum+offset-4,(unsigned int) profile->length); (void) memcpy(extract_profile->datum+offset, profile->datum,profile->length); } (void) memcpy(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block,ExceptionInfo *exception) { const unsigned char *datum; register const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ if (count < 10) break; p=ReadResourceLong(p,&resolution); image->resolution.x=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->resolution.y=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } static void PatchCorruptProfile(const char *name,StringInfo *profile) { register unsigned char *p; size_t length; /* Detect corrupt profiles and if discovered, repair. */ if (LocaleCompare(name,"xmp") == 0) { /* Remove garbage after xpacket end. */ p=GetStringInfoDatum(profile); p=(unsigned char *) strstr((const char *) p,"<?xpacket end=\"w\"?>"); if (p != (unsigned char *) NULL) { p+=19; length=p-GetStringInfoDatum(profile); if (length != GetStringInfoLength(profile)) { *p='\0'; SetStringInfoLength(profile,length); } } return; } if (LocaleCompare(name,"exif") == 0) { /* Check if profile starts with byte order marker instead of Exif. */ p=GetStringInfoDatum(profile); if ((LocaleNCompare((const char *) p,"MM",2) == 0) || (LocaleNCompare((const char *) p,"II",2) == 0)) { const unsigned char profile_start[] = "Exif\0\0"; StringInfo *exif_profile; exif_profile=AcquireStringInfo(6); if (exif_profile != (StringInfo *) NULL) { SetStringInfoDatum(exif_profile,profile_start); ConcatenateStringInfo(exif_profile,profile); SetStringInfoLength(profile,GetStringInfoLength(exif_profile)); SetStringInfo(profile,exif_profile); exif_profile=DestroyStringInfo(exif_profile); } } } } #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType ValidateXMPProfile(Image *image, const StringInfo *profile,ExceptionInfo *exception) { xmlDocPtr document; /* Parse XML profile. */ document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int) GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (document == (xmlDocPtr) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "CorruptImageProfile","`%s' (XMP)",image->filename); return(MagickFalse); } xmlFreeDoc(document); return(MagickTrue); } #else static MagickBooleanType ValidateXMPProfile(Image *image, const StringInfo *profile,ExceptionInfo *exception) { (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","'%s' (XML)",image->filename); return(MagickFalse); } #endif static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive, ExceptionInfo *exception) { char key[MagickPathExtent]; MagickBooleanType status; StringInfo *clone_profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); clone_profile=CloneStringInfo(profile); PatchCorruptProfile(name,clone_profile); if ((LocaleCompare(name,"xmp") == 0) && (ValidateXMPProfile(image,clone_profile,exception) == MagickFalse)) { clone_profile=DestroyStringInfo(clone_profile); return(MagickTrue); } if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MagickPathExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),clone_profile); if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,clone_profile,exception); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,clone_profile); } return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { return(SetImageProfileInternal(image,name,profile,MagickFalse,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) memcpy(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) memcpy(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) memcpy(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) memcpy(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count >= (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; length-=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*2.54* 65536.0),p); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(int) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((offset < 0) || ((size_t) (offset+number_bytes) > length)) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickPrivate MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); } static void UpdateClipPath(unsigned char *blob,size_t length, const size_t old_columns,const size_t old_rows, const RectangleInfo *new_geometry) { register ssize_t i; ssize_t knot_count, selector; knot_count=0; while (length != 0) { selector=(ssize_t) ReadProfileMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadProfileMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot. */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { double x, y; signed int xx, yy; y=(double) ReadProfileMSBLong(&blob,&length); y=y*old_rows/4096/4096; y-=new_geometry->y; yy=(signed int) ((y*4096*4096)/new_geometry->height); WriteProfileLong(MSBEndian,(size_t) yy,blob-4); x=(double) ReadProfileMSBLong(&blob,&length); x=x*old_columns/4096/4096; x-=new_geometry->x; xx=(signed int) ((x*4096*4096)/new_geometry->width); WriteProfileLong(MSBEndian,(size_t) xx,blob-4); } knot_count--; break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } } MagickPrivate void Update8BIMClipPath(const Image *image, const size_t old_columns,const size_t old_rows, const RectangleInfo *new_geometry) { const StringInfo *profile; size_t length; ssize_t count, id; unsigned char *info; assert(image != (Image *) NULL); assert(new_geometry != (RectangleInfo *) NULL); profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while (length > 0) { if (ReadProfileByte(&info,&length) != (unsigned char) '8') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'B') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'I') continue; if (ReadProfileByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadProfileMSBShort(&info,&length); count=(ssize_t) ReadProfileByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { info+=count; length-=count; } if ((count & 0x01) == 0) (void) ReadProfileByte(&info,&length); count=(ssize_t) ReadProfileMSBLong(&info,&length); if ((count < 0) || ((size_t) count > length)) { length=0; continue; } if ((id > 1999) && (id < 2999)) UpdateClipPath(info,(size_t) count,old_columns,old_rows,new_geometry); info+=count; length-=MagickMin(count,(ssize_t) length); } }
parallel_boruvka.h
#ifndef __BORUVKA_H #define __BORUVKA_H #include <algorithm> #include <limits> #include <omp.h> #include <parallel/algorithm> #include <parallel/numeric> #include <unordered_map> #include "parallel_dsu.h" #include "graph.h" #include "parallel_array.h" struct ParallelBoruvkaMST { /** * I use the same atomic pair that I use in dsu.h */ const u32 EDGE_BINARY_BUCKET_SIZE = 32; const u64 EDGE_WEIGHT_MASK = 0xFFFFFFFF00000000ULL; u64 encode_edge(u32 id, u32 weight) { return (static_cast<u64>(weight) << EDGE_BINARY_BUCKET_SIZE) | id; } u32 get_id(u64 encoded_edge) { return static_cast<u32>(encoded_edge); } u32 get_weight(u64 encoded_edge) { return static_cast<u32>(encoded_edge >> EDGE_BINARY_BUCKET_SIZE); } /** * Calculates MST of given graph and returns a ParallelArray<Edge> object * Graph edges must be sorted beforehand */ ParallelArray<Edge> calculate_mst(Graph graph, u32 NUM_THREADS = omp_get_max_threads()) { ParallelDSU node_sets(graph.num_nodes(), NUM_THREADS); ParallelArray<Edge> mst(graph.num_nodes() - 1, NUM_THREADS); u32 current_mst_size = 0; u32 initial_num_nodes = graph.num_nodes(); while (graph.num_nodes() != 1) { ParallelArray<atomic_u64> shortest_edges(initial_num_nodes, NUM_THREADS); /* Calculating shortest edges from each node */ #pragma omp parallel num_threads(NUM_THREADS) { ParallelArray<std::pair<u32, u32>> local_shortest_edges(initial_num_nodes); ParallelArray<u32> local_nodes(graph.num_nodes()); u32 local_size = 0; u32 last_node = initial_num_nodes + 1; /* Assuming there is no node bigger than N in G */ for (u32 i = 0; i < graph.num_nodes(); ++i) { shortest_edges[graph.nodes[i]] = encode_edge(0, std::numeric_limits<u32>::max()); } #pragma omp for for (u32 i = 0; i < graph.num_edges(); ++i) { const Edge& e = graph.edges[i]; if (e.from != last_node || local_shortest_edges[e.from].first > e.weight) { local_shortest_edges[e.from] = { e.weight, i }; if (e.from != last_node) { local_nodes[local_size++] = e.from; last_node = e.from; } } } for (u32 i = 0; i < local_size; ++i) { /* O(M / p) operations in each thread */ u32 node = local_nodes[i]; u64 old = shortest_edges[node]; auto shortest_edge = local_shortest_edges[node]; /* p.second = { weight, id } */ u64 encoded_edge = encode_edge(shortest_edge.second, shortest_edge.first); while (true) { /* This loop is wait-free */ if (get_weight(old) < shortest_edge.first || shortest_edges[node].compare_exchange_strong(old, encoded_edge)) { break; } } } } /* Calculating selected edges */ ParallelArray<u32> edge_selected(graph.num_edges(), NUM_THREADS); #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_edges(); ++i) { edge_selected[i] = 0; } #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_nodes(); ++i) { u32 u = graph.nodes[i]; u32 v = graph.edges[get_id(shortest_edges[u])].to; /* If smallest edge from v goes to u or u < v */ if (graph.edges[get_id(shortest_edges[v])].to != u || u < v) { node_sets.unite(u, v); edge_selected[get_id(shortest_edges[u])] = true; } } /* Adding edges to MST */ ParallelArray<u32> edge_selected_prefix(graph.num_edges(), NUM_THREADS); __gnu_parallel::partial_sum(edge_selected.begin(), edge_selected.end(), edge_selected_prefix.begin()); #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_edges(); ++i) { if (edge_selected[i]) { mst[current_mst_size + edge_selected_prefix[i] - 1] = graph.edges[i]; } } current_mst_size += edge_selected_prefix[graph.num_edges() - 1]; /* Calculating remaining edges */ ParallelArray<u32> edge_remains(graph.num_edges(), NUM_THREADS); #pragma omp parallel for for (u32 i = 0; i < graph.num_edges(); ++i) { edge_remains[i] = !node_sets.same_set(graph.edges[i].from, graph.edges[i].to); } ParallelArray<u32> edge_remains_prefix(graph.num_edges(), NUM_THREADS); __gnu_parallel::partial_sum(edge_remains.begin(), edge_remains.end(), edge_remains_prefix.begin()); ParallelArray<Edge> new_edges(edge_remains_prefix[graph.num_edges() - 1], NUM_THREADS); #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_edges(); ++i) { if (edge_remains[i]) { const Edge& old_edge = graph.edges[i]; new_edges[edge_remains_prefix[i] - 1] = Edge(node_sets.find_root(old_edge.from), node_sets.find_root(old_edge.to), old_edge.weight); } } /* Calculating remaining nodes */ ParallelArray<u32> node_remains(graph.num_nodes(), NUM_THREADS); #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_nodes(); ++i) { node_remains[i] = ( node_sets.find_root(graph.nodes[i]) == graph.nodes[i] ); } ParallelArray<u32> node_remains_prefix(graph.num_nodes(), NUM_THREADS); __gnu_parallel::partial_sum(node_remains.begin(), node_remains.end(), node_remains_prefix.begin()); ParallelArray<u32> new_nodes(node_remains_prefix[graph.num_nodes() - 1]); #pragma omp parallel for num_threads(NUM_THREADS) for (u32 i = 0; i < graph.num_nodes(); ++i) { if (node_remains[i]) { new_nodes[node_remains_prefix[i] - 1] = graph.nodes[i]; } } /* Swapping old graph for new graph */ graph.nodes.swap(new_nodes); graph.edges.swap(new_edges); graph.sort_edges(); } return mst; } }; #endif
array_args.h
#ifndef LIGHTGBM_UTILS_ARRAY_AGRS_H_ #define LIGHTGBM_UTILS_ARRAY_AGRS_H_ #include <vector> #include <algorithm> #include <LightGBM/utils/openmp_wrapper.h> namespace LightGBM { /*! * \brief Contains some operation for a array, e.g. ArgMax, TopK. */ template<typename VAL_T> class ArrayArgs { public: inline static size_t ArgMaxMT(const std::vector<VAL_T>& array) { int num_threads = 1; #pragma omp parallel #pragma omp master { num_threads = omp_get_num_threads(); } int step = std::max(1, (static_cast<int>(array.size()) + num_threads - 1) / num_threads); std::vector<size_t> arg_maxs(num_threads, 0); #pragma omp parallel for schedule(static,1) for (int i = 0; i < num_threads; ++i) { size_t start = step * i; if (start >= array.size()) { continue; } size_t end = std::min(array.size(), start + step); size_t arg_max = start; for (size_t j = start + 1; j < end; ++j) { if (array[j] > array[arg_max]) { arg_max = j; } } arg_maxs[i] = arg_max; } size_t ret = arg_maxs[0]; for (int i = 1; i < num_threads; ++i) { if (array[arg_maxs[i]] > array[ret]) { ret = arg_maxs[i]; } } return ret; } inline static size_t ArgMax(const std::vector<VAL_T>& array) { if (array.empty()) { return 0; } if (array.size() > 100) { return ArgMaxMT(array); } else { size_t arg_max = 0; for (size_t i = 1; i < array.size(); ++i) { if (array[i] > array[arg_max]) { arg_max = i; } } return arg_max; } } inline static size_t ArgMin(const std::vector<VAL_T>& array) { if (array.empty()) { return 0; } size_t arg_min = 0; for (size_t i = 1; i < array.size(); ++i) { if (array[i] < array[arg_min]) { arg_min = i; } } return arg_min; } inline static size_t ArgMax(const VAL_T* array, size_t n) { if (n <= 0) { return 0; } size_t arg_max = 0; for (size_t i = 1; i < n; ++i) { if (array[i] > array[arg_max]) { arg_max = i; } } return arg_max; } inline static size_t ArgMin(const VAL_T* array, size_t n) { if (n <= 0) { return 0; } size_t arg_min = 0; for (size_t i = 1; i < n; ++i) { if (array[i] < array[arg_min]) { arg_min = i; } } return arg_min; } inline static void Partition(std::vector<VAL_T>* arr, int start, int end, int* l, int* r) { int i = start - 1; int j = end - 1; int p = i; int q = j; if (start >= end) { return; } std::vector<VAL_T>& ref = *arr; VAL_T v = ref[end - 1]; for (;;) { while (ref[++i] > v); while (v > ref[--j]) { if (j == start) { break; } } if (i >= j) { break; } std::swap(ref[i], ref[j]); if (ref[i] == v) { p++; std::swap(ref[p], ref[i]); } if (v == ref[j]) { q--; std::swap(ref[j], ref[q]); } } std::swap(ref[i], ref[end - 1]); j = i - 1; i = i + 1; for (int k = start; k <= p; k++, j--) { std::swap(ref[k], ref[j]); } for (int k = end - 2; k >= q; k--, i++) { std::swap(ref[i], ref[k]); } *l = j; *r = i; }; inline static int ArgMaxAtK(std::vector<VAL_T>* arr, int start, int end, int k) { if (start >= end - 1) { return start; } int l = start; int r = end - 1; Partition(arr, start, end, &l, &r); if ((k > l && k < r) || l == 0 || r == end - 1) { return k; } else if (k <= l) { return ArgMaxAtK(arr, start, l, k); } else { return ArgMaxAtK(arr, r, end, k); } } inline static void MaxK(const std::vector<VAL_T>& array, int k, std::vector<VAL_T>* out) { out->clear(); if (k <= 0) { return; } for (auto val : array) { out->push_back(val); } if (static_cast<size_t>(k) >= array.size()) { return; } ArgMaxAtK(out, 0, static_cast<int>(out->size()), k - 1); out->erase(out->begin() + k, out->end()); } }; } // namespace LightGBM #endif // LightGBM_UTILS_ARRAY_AGRS_H_
convolution_3x3_pack8to1_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. static void conv3x3s1_winograd42_transform_kernel_pack8to1_int8_neon(const Mat& kernel, Mat& kernel_tm_pack8to1, int inch, int outch, const Option& opt) { // winograd42 transform kernel Mat kernel_tm(6 * 6, inch, outch, (size_t)2u); const short ktm[6][3] = { {6, 0, 0}, {-4, -4, -4}, {-4, 4, -4}, {1, 2, 4}, {1, -2, 4}, {0, 0, 6} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const signed char* kernel0 = (const signed char*)kernel + p * inch * 9 + q * 9; short* kernel_tm0 = kernel_tm.channel(p).row<short>(q); // transform kernel const signed char* k0 = kernel0; const signed char* k1 = kernel0 + 3; const signed char* k2 = kernel0 + 6; // h short tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { short* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = 8a-inch/8a-36-outch kernel_tm_pack8to1.create(8 * inch / 8, 36, outch / 8 + outch % 8, (size_t)2u * 8, 8); int p = 0; for (; p + 7 < outch; p += 8) { const Mat k0 = kernel_tm.channel(p); const Mat k1 = kernel_tm.channel(p + 1); const Mat k2 = kernel_tm.channel(p + 2); const Mat k3 = kernel_tm.channel(p + 3); const Mat k4 = kernel_tm.channel(p + 4); const Mat k5 = kernel_tm.channel(p + 5); const Mat k6 = kernel_tm.channel(p + 6); const Mat k7 = kernel_tm.channel(p + 7); Mat g0 = kernel_tm_pack8to1.channel(p / 8); for (int k = 0; k < 36; k++) { short* g00 = g0.row<short>(k); for (int q = 0; q + 7 < inch; q += 8) { for (int i = 0; i < 8; i++) { g00[0] = k0.row<const short>(q + i)[k]; g00[1] = k1.row<const short>(q + i)[k]; g00[2] = k2.row<const short>(q + i)[k]; g00[3] = k3.row<const short>(q + i)[k]; g00[4] = k4.row<const short>(q + i)[k]; g00[5] = k5.row<const short>(q + i)[k]; g00[6] = k6.row<const short>(q + i)[k]; g00[7] = k7.row<const short>(q + i)[k]; g00 += 8; } } } } for (; p < outch; p++) { const Mat k0 = kernel_tm.channel(p); Mat g0 = kernel_tm_pack8to1.channel(p / 8 + p % 8); for (int k = 0; k < 36; k++) { short* g00 = g0.row<short>(k); for (int q = 0; q + 7 < inch; q += 8) { for (int i = 0; i < 8; i++) { g00[0] = k0.row<const short>(q + i)[k]; g00 += 1; } } } } } static void conv3x3s1_winograd42_pack8to1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; // size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; bottom_blob_tm.create(tiles, 36, inch, 2u * elempack, elempack, opt.workspace_allocator); // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r04 + r03 // 2 = 4 * (r01 - r02) + r04 - r03 // 3 = -2 * (r01 - r03) + r04 - r02 // 4 = 2 * (r01 - r03) + r04 - r02 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); short tmp[6][6][8]; // tile for (int i = 0; i < h_tm / 6; i++) { for (int j = 0; j < w_tm / 6; j++) { const signed char* r0 = img0.row<const signed char>(i * 4) + (j * 4) * 8; for (int m = 0; m < 6; m++) { int8x8_t _r00 = vld1_s8(r0); int8x8_t _r01 = vld1_s8(r0 + 8); int8x8_t _r02 = vld1_s8(r0 + 16); int8x8_t _r03 = vld1_s8(r0 + 24); int8x8_t _r04 = vld1_s8(r0 + 32); int8x8_t _r05 = vld1_s8(r0 + 40); int8x8_t _v4s8 = vdup_n_s8(4); int8x8_t _v5s8 = vdup_n_s8(5); int16x8_t _v2 = vdupq_n_s16(2); int16x8_t _v4 = vdupq_n_s16(4); // int16x8_t _tmp0m = vfmsq_n_f16(vfmaq_n_f16(_r04, _r00, 4.f), _r02, 5.f); int16x8_t _tmp0m = vsubq_s16(vaddw_s8(vmull_s8(_r00, _v4s8), _r04), vmull_s8(_r02, _v5s8)); // int16x8_t _tmp1m = vfmsq_n_f16(vaddq_f16(_r04, _r03), vaddq_f16(_r01, _r02), 4.f); int16x8_t _tmp1m = vmlsq_s16(vaddl_s8(_r04, _r03), vaddl_s8(_r01, _r02), _v4); // int16x8_t _tmp2m = vfmaq_n_f16(vsubq_f16(_r04, _r03), vsubq_f16(_r01, _r02), 4.f); int16x8_t _tmp2m = vmlaq_s16(vsubl_s8(_r04, _r03), vsubl_s8(_r01, _r02), _v4); // int16x8_t _tmp3m = vfmsq_n_f16(vsubq_f16(_r04, _r02), vsubq_f16(_r01, _r03), 2.f); int16x8_t _tmp3m = vmlsq_s16(vsubl_s8(_r04, _r02), vsubl_s8(_r01, _r03), _v2); // int16x8_t _tmp4m = vfmaq_n_f16(vsubq_f16(_r04, _r02), vsubq_f16(_r01, _r03), 2.f); int16x8_t _tmp4m = vmlaq_s16(vsubl_s8(_r04, _r02), vsubl_s8(_r01, _r03), _v2); // int16x8_t _tmp5m = vfmsq_n_f16(vfmaq_n_f16(_r05, _r01, 4.f), _r03, 5.f); int16x8_t _tmp5m = vsubq_s16(vaddw_s8(vmull_s8(_r01, _v4s8), _r05), vmull_s8(_r03, _v5s8)); vst1q_s16(tmp[0][m], _tmp0m); vst1q_s16(tmp[1][m], _tmp1m); vst1q_s16(tmp[2][m], _tmp2m); vst1q_s16(tmp[3][m], _tmp3m); vst1q_s16(tmp[4][m], _tmp4m); vst1q_s16(tmp[5][m], _tmp5m); r0 += w * 8; } short* r0_tm_0 = (short*)img0_tm + (i * w_tm / 6 + j) * 8; short* r0_tm_1 = r0_tm_0 + tiles * 8; short* r0_tm_2 = r0_tm_0 + tiles * 16; short* r0_tm_3 = r0_tm_0 + tiles * 24; short* r0_tm_4 = r0_tm_0 + tiles * 32; short* r0_tm_5 = r0_tm_0 + tiles * 40; for (int m = 0; m < 6; m++) { int16x8_t _tmp00 = vld1q_s16(tmp[m][0]); int16x8_t _tmp01 = vld1q_s16(tmp[m][1]); int16x8_t _tmp02 = vld1q_s16(tmp[m][2]); int16x8_t _tmp03 = vld1q_s16(tmp[m][3]); int16x8_t _tmp04 = vld1q_s16(tmp[m][4]); int16x8_t _tmp05 = vld1q_s16(tmp[m][5]); int16x8_t _v2 = vdupq_n_s16(2); int16x8_t _v4 = vdupq_n_s16(4); int16x8_t _v5 = vdupq_n_s16(5); int16x8_t _r0tm0 = vmlsq_s16(vmlaq_s16(_tmp04, _tmp00, _v4), _tmp02, _v5); int16x8_t _r0tm1 = vmlsq_s16(vaddq_s16(_tmp04, _tmp03), vaddq_s16(_tmp01, _tmp02), _v4); int16x8_t _r0tm2 = vmlaq_s16(vsubq_s16(_tmp04, _tmp03), vsubq_s16(_tmp01, _tmp02), _v4); int16x8_t _r0tm3 = vmlsq_s16(vsubq_s16(_tmp04, _tmp02), vsubq_s16(_tmp01, _tmp03), _v2); int16x8_t _r0tm4 = vmlaq_s16(vsubq_s16(_tmp04, _tmp02), vsubq_s16(_tmp01, _tmp03), _v2); int16x8_t _r0tm5 = vmlsq_s16(vmlaq_s16(_tmp05, _tmp01, _v4), _tmp03, _v5); vst1q_s16(r0_tm_0, _r0tm0); vst1q_s16(r0_tm_1, _r0tm1); vst1q_s16(r0_tm_2, _r0tm2); vst1q_s16(r0_tm_3, _r0tm3); vst1q_s16(r0_tm_4, _r0tm4); vst1q_s16(r0_tm_5, _r0tm5); r0_tm_0 += tiles * 48; r0_tm_1 += tiles * 48; r0_tm_2 += tiles * 48; r0_tm_3 += tiles * 48; r0_tm_4 += tiles * 48; r0_tm_5 += tiles * 48; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute // bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __aarch64__ if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + tiles % 4, 36, 2u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 36, 2u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 2u * elempack, elempack, opt.workspace_allocator); #endif // __aarch64__ #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __aarch64__ for (; i + 7 < tiles; i += 8) { short* tm2p = tm2.row<short>(i / 8); const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { // transpose 8x8 asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0], #64 \n" "ld4 {v4.8h, v5.8h, v6.8h, v7.8h}, [%0] \n" "sub %0, %0, #64 \n" "uzp1 v16.8h, v0.8h, v4.8h \n" "uzp2 v20.8h, v0.8h, v4.8h \n" "uzp1 v17.8h, v1.8h, v5.8h \n" "uzp2 v21.8h, v1.8h, v5.8h \n" "uzp1 v18.8h, v2.8h, v6.8h \n" "uzp2 v22.8h, v2.8h, v6.8h \n" "uzp1 v19.8h, v3.8h, v7.8h \n" "uzp2 v23.8h, v3.8h, v7.8h \n" "st1 {v16.8h, v17.8h, v18.8h, v19.8h}, [%1], #64 \n" "st1 {v20.8h, v21.8h, v22.8h, v23.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); r0 += bottom_blob_tm.cstep * 8; } } #endif for (; i + 3 < tiles; i += 4) { #if __aarch64__ short* tm2p = tm2.row<short>(i / 8 + (i % 8) / 4); #else short* tm2p = tm2.row<short>(i / 4); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { // transpose 8x4 #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%0] \n" "st4 {v0.8h, v1.8h, v2.8h, v3.8h}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); #else asm volatile( "pld [%0, #512] \n" "vldm %0, {d0-d7} \n" "vswp d1, d2 \n" "vswp d5, d6 \n" "vswp q1, q2 \n" "vst4.s16 {d0-d3}, [%1 :64]! \n" "vst4.s16 {d4-d7}, [%1 :64]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 8; } } for (; i < tiles; i++) { #if __aarch64__ short* tm2p = tm2.row<short>(i / 8 + (i % 8) / 4 + i % 4); #else short* tm2p = tm2.row<short>(i / 4 + i % 4); #endif const short* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 8; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.8h}, [%0] \n" "st1 {v0.8h}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0"); #else asm volatile( "pld [%0, #128] \n" "vld1.s16 {d0-d1}, [%0 :64] \n" "vst1.s16 {d0-d1}, [%1 :64]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 8; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; int* output0_tm = top_blob_tm.channel(p); int* output1_tm = top_blob_tm.channel(p + 1); int* output2_tm = top_blob_tm.channel(p + 2); int* output3_tm = top_blob_tm.channel(p + 3); int* output4_tm = top_blob_tm.channel(p + 4); int* output5_tm = top_blob_tm.channel(p + 5); int* output6_tm = top_blob_tm.channel(p + 6); int* output7_tm = top_blob_tm.channel(p + 7); const Mat kernel01_tm = kernel_tm.channel(p / 8); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 7 < tiles; i += 8) { const short* r0 = bb2.row<const short>(i / 8); const short* kptr = kernel01_tm.row<const short>(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v8.8h, v9.8h, v10.8h, v11.8h}, [%9], #64 \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v0.8h, v1.8h, v2.8h, v3.8h}, [%10], #64 \n" "smlal v16.4s, v8.4h, v0.h[0] \n" "smlal2 v17.4s, v8.8h, v0.h[0] \n" "smlal v18.4s, v8.4h, v0.h[1] \n" "smlal2 v19.4s, v8.8h, v0.h[1] \n" "smlal v20.4s, v8.4h, v0.h[2] \n" "smlal2 v21.4s, v8.8h, v0.h[2] \n" "smlal v22.4s, v8.4h, v0.h[3] \n" "smlal2 v23.4s, v8.8h, v0.h[3] \n" "smlal v24.4s, v8.4h, v0.h[4] \n" "smlal2 v25.4s, v8.8h, v0.h[4] \n" "smlal v26.4s, v8.4h, v0.h[5] \n" "smlal2 v27.4s, v8.8h, v0.h[5] \n" "smlal v28.4s, v8.4h, v0.h[6] \n" "smlal2 v29.4s, v8.8h, v0.h[6] \n" "smlal v30.4s, v8.4h, v0.h[7] \n" "smlal2 v31.4s, v8.8h, v0.h[7] \n" "smlal v16.4s, v9.4h, v1.h[0] \n" "smlal2 v17.4s, v9.8h, v1.h[0] \n" "smlal v18.4s, v9.4h, v1.h[1] \n" "smlal2 v19.4s, v9.8h, v1.h[1] \n" "smlal v20.4s, v9.4h, v1.h[2] \n" "smlal2 v21.4s, v9.8h, v1.h[2] \n" "smlal v22.4s, v9.4h, v1.h[3] \n" "smlal2 v23.4s, v9.8h, v1.h[3] \n" "smlal v24.4s, v9.4h, v1.h[4] \n" "smlal2 v25.4s, v9.8h, v1.h[4] \n" "smlal v26.4s, v9.4h, v1.h[5] \n" "smlal2 v27.4s, v9.8h, v1.h[5] \n" "smlal v28.4s, v9.4h, v1.h[6] \n" "smlal2 v29.4s, v9.8h, v1.h[6] \n" "smlal v30.4s, v9.4h, v1.h[7] \n" "smlal2 v31.4s, v9.8h, v1.h[7] \n" "prfm pldl1keep, [%9, #512] \n" "ld1 {v12.8h, v13.8h, v14.8h, v15.8h}, [%9], #64 \n" "smlal v16.4s, v10.4h, v2.h[0] \n" "smlal2 v17.4s, v10.8h, v2.h[0] \n" "smlal v18.4s, v10.4h, v2.h[1] \n" "smlal2 v19.4s, v10.8h, v2.h[1] \n" "smlal v20.4s, v10.4h, v2.h[2] \n" "smlal2 v21.4s, v10.8h, v2.h[2] \n" "smlal v22.4s, v10.4h, v2.h[3] \n" "smlal2 v23.4s, v10.8h, v2.h[3] \n" "smlal v24.4s, v10.4h, v2.h[4] \n" "smlal2 v25.4s, v10.8h, v2.h[4] \n" "smlal v26.4s, v10.4h, v2.h[5] \n" "smlal2 v27.4s, v10.8h, v2.h[5] \n" "smlal v28.4s, v10.4h, v2.h[6] \n" "smlal2 v29.4s, v10.8h, v2.h[6] \n" "smlal v30.4s, v10.4h, v2.h[7] \n" "smlal2 v31.4s, v10.8h, v2.h[7] \n" "prfm pldl1keep, [%10, #512] \n" "ld1 {v4.8h, v5.8h, v6.8h, v7.8h}, [%10], #64 \n" "smlal v16.4s, v11.4h, v3.h[0] \n" "smlal2 v17.4s, v11.8h, v3.h[0] \n" "smlal v18.4s, v11.4h, v3.h[1] \n" "smlal2 v19.4s, v11.8h, v3.h[1] \n" "smlal v20.4s, v11.4h, v3.h[2] \n" "smlal2 v21.4s, v11.8h, v3.h[2] \n" "smlal v22.4s, v11.4h, v3.h[3] \n" "smlal2 v23.4s, v11.8h, v3.h[3] \n" "smlal v24.4s, v11.4h, v3.h[4] \n" "smlal2 v25.4s, v11.8h, v3.h[4] \n" "smlal v26.4s, v11.4h, v3.h[5] \n" "smlal2 v27.4s, v11.8h, v3.h[5] \n" "smlal v28.4s, v11.4h, v3.h[6] \n" "smlal2 v29.4s, v11.8h, v3.h[6] \n" "smlal v30.4s, v11.4h, v3.h[7] \n" "smlal2 v31.4s, v11.8h, v3.h[7] \n" "smlal v16.4s, v12.4h, v4.h[0] \n" "smlal2 v17.4s, v12.8h, v4.h[0] \n" "smlal v18.4s, v12.4h, v4.h[1] \n" "smlal2 v19.4s, v12.8h, v4.h[1] \n" "smlal v20.4s, v12.4h, v4.h[2] \n" "smlal2 v21.4s, v12.8h, v4.h[2] \n" "smlal v22.4s, v12.4h, v4.h[3] \n" "smlal2 v23.4s, v12.8h, v4.h[3] \n" "smlal v24.4s, v12.4h, v4.h[4] \n" "smlal2 v25.4s, v12.8h, v4.h[4] \n" "smlal v26.4s, v12.4h, v4.h[5] \n" "smlal2 v27.4s, v12.8h, v4.h[5] \n" "smlal v28.4s, v12.4h, v4.h[6] \n" "smlal2 v29.4s, v12.8h, v4.h[6] \n" "smlal v30.4s, v12.4h, v4.h[7] \n" "smlal2 v31.4s, v12.8h, v4.h[7] \n" "smlal v16.4s, v13.4h, v5.h[0] \n" "smlal2 v17.4s, v13.8h, v5.h[0] \n" "smlal v18.4s, v13.4h, v5.h[1] \n" "smlal2 v19.4s, v13.8h, v5.h[1] \n" "smlal v20.4s, v13.4h, v5.h[2] \n" "smlal2 v21.4s, v13.8h, v5.h[2] \n" "smlal v22.4s, v13.4h, v5.h[3] \n" "smlal2 v23.4s, v13.8h, v5.h[3] \n" "smlal v24.4s, v13.4h, v5.h[4] \n" "smlal2 v25.4s, v13.8h, v5.h[4] \n" "smlal v26.4s, v13.4h, v5.h[5] \n" "smlal2 v27.4s, v13.8h, v5.h[5] \n" "smlal v28.4s, v13.4h, v5.h[6] \n" "smlal2 v29.4s, v13.8h, v5.h[6] \n" "smlal v30.4s, v13.4h, v5.h[7] \n" "smlal2 v31.4s, v13.8h, v5.h[7] \n" "smlal v16.4s, v14.4h, v6.h[0] \n" "smlal2 v17.4s, v14.8h, v6.h[0] \n" "smlal v18.4s, v14.4h, v6.h[1] \n" "smlal2 v19.4s, v14.8h, v6.h[1] \n" "smlal v20.4s, v14.4h, v6.h[2] \n" "smlal2 v21.4s, v14.8h, v6.h[2] \n" "smlal v22.4s, v14.4h, v6.h[3] \n" "smlal2 v23.4s, v14.8h, v6.h[3] \n" "smlal v24.4s, v14.4h, v6.h[4] \n" "smlal2 v25.4s, v14.8h, v6.h[4] \n" "smlal v26.4s, v14.4h, v6.h[5] \n" "smlal2 v27.4s, v14.8h, v6.h[5] \n" "smlal v28.4s, v14.4h, v6.h[6] \n" "smlal2 v29.4s, v14.8h, v6.h[6] \n" "smlal v30.4s, v14.4h, v6.h[7] \n" "smlal2 v31.4s, v14.8h, v6.h[7] \n" "subs %w0, %w0, #1 \n" "smlal v16.4s, v15.4h, v7.h[0] \n" "smlal2 v17.4s, v15.8h, v7.h[0] \n" "smlal v18.4s, v15.4h, v7.h[1] \n" "smlal2 v19.4s, v15.8h, v7.h[1] \n" "smlal v20.4s, v15.4h, v7.h[2] \n" "smlal2 v21.4s, v15.8h, v7.h[2] \n" "smlal v22.4s, v15.4h, v7.h[3] \n" "smlal2 v23.4s, v15.8h, v7.h[3] \n" "smlal v24.4s, v15.4h, v7.h[4] \n" "smlal2 v25.4s, v15.8h, v7.h[4] \n" "smlal v26.4s, v15.4h, v7.h[5] \n" "smlal2 v27.4s, v15.8h, v7.h[5] \n" "smlal v28.4s, v15.4h, v7.h[6] \n" "smlal2 v29.4s, v15.8h, v7.h[6] \n" "smlal v30.4s, v15.4h, v7.h[7] \n" "smlal2 v31.4s, v15.8h, v7.h[7] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" "st1 {v18.4s, v19.4s}, [%2], #32 \n" "st1 {v20.4s, v21.4s}, [%3], #32 \n" "st1 {v22.4s, v23.4s}, [%4], #32 \n" "st1 {v24.4s, v25.4s}, [%5], #32 \n" "st1 {v26.4s, v27.4s}, [%6], #32 \n" "st1 {v28.4s, v29.4s}, [%7], #32 \n" "st1 {v30.4s, v31.4s}, [%8], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(output4_tm), // %5 "=r"(output5_tm), // %6 "=r"(output6_tm), // %7 "=r"(output7_tm), // %8 "=r"(r0), // %9 "=r"(kptr) // %10 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(output4_tm), "6"(output5_tm), "7"(output6_tm), "8"(output7_tm), "9"(r0), "10"(kptr) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } #endif for (; i + 3 < tiles; i += 4) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 8 + (i % 8) / 4); #else const short* r0 = bb2.row<const short>(i / 4); #endif const short* k0 = kernel01_tm.row<const short>(r); int nn = inch; // inch always > 0 int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); int32x4_t _sum2 = vdupq_n_s32(0); int32x4_t _sum3 = vdupq_n_s32(0); int32x4_t _sum4 = vdupq_n_s32(0); int32x4_t _sum5 = vdupq_n_s32(0); int32x4_t _sum6 = vdupq_n_s32(0); int32x4_t _sum7 = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _val1 = vld1q_s16(r0 + 8); int16x8_t _val2 = vld1q_s16(r0 + 16); int16x8_t _val3 = vld1q_s16(r0 + 24); int16x8_t _w0 = vld1q_s16(k0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_val0), vget_low_s16(_w0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_low_s16(_val0), vget_low_s16(_w0), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_val0), vget_low_s16(_w0), 2); _sum3 = vmlal_lane_s16(_sum3, vget_low_s16(_val0), vget_low_s16(_w0), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_val0), vget_high_s16(_w0), 0); _sum5 = vmlal_lane_s16(_sum5, vget_low_s16(_val0), vget_high_s16(_w0), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_val0), vget_high_s16(_w0), 2); _sum7 = vmlal_lane_s16(_sum7, vget_low_s16(_val0), vget_high_s16(_w0), 3); int16x8_t _w1 = vld1q_s16(k0 + 8); _sum0 = vmlal_lane_s16(_sum0, vget_high_s16(_val0), vget_low_s16(_w1), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_val0), vget_low_s16(_w1), 1); _sum2 = vmlal_lane_s16(_sum2, vget_high_s16(_val0), vget_low_s16(_w1), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_val0), vget_low_s16(_w1), 3); _sum4 = vmlal_lane_s16(_sum4, vget_high_s16(_val0), vget_high_s16(_w1), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_val0), vget_high_s16(_w1), 1); _sum6 = vmlal_lane_s16(_sum6, vget_high_s16(_val0), vget_high_s16(_w1), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_val0), vget_high_s16(_w1), 3); int16x8_t _w2 = vld1q_s16(k0 + 16); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_val1), vget_low_s16(_w2), 0); _sum1 = vmlal_lane_s16(_sum1, vget_low_s16(_val1), vget_low_s16(_w2), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_val1), vget_low_s16(_w2), 2); _sum3 = vmlal_lane_s16(_sum3, vget_low_s16(_val1), vget_low_s16(_w2), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_val1), vget_high_s16(_w2), 0); _sum5 = vmlal_lane_s16(_sum5, vget_low_s16(_val1), vget_high_s16(_w2), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_val1), vget_high_s16(_w2), 2); _sum7 = vmlal_lane_s16(_sum7, vget_low_s16(_val1), vget_high_s16(_w2), 3); int16x8_t _w3 = vld1q_s16(k0 + 24); _sum0 = vmlal_lane_s16(_sum0, vget_high_s16(_val1), vget_low_s16(_w3), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_val1), vget_low_s16(_w3), 1); _sum2 = vmlal_lane_s16(_sum2, vget_high_s16(_val1), vget_low_s16(_w3), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_val1), vget_low_s16(_w3), 3); _sum4 = vmlal_lane_s16(_sum4, vget_high_s16(_val1), vget_high_s16(_w3), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_val1), vget_high_s16(_w3), 1); _sum6 = vmlal_lane_s16(_sum6, vget_high_s16(_val1), vget_high_s16(_w3), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_val1), vget_high_s16(_w3), 3); int16x8_t _w4 = vld1q_s16(k0 + 32); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_val2), vget_low_s16(_w4), 0); _sum1 = vmlal_lane_s16(_sum1, vget_low_s16(_val2), vget_low_s16(_w4), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_val2), vget_low_s16(_w4), 2); _sum3 = vmlal_lane_s16(_sum3, vget_low_s16(_val2), vget_low_s16(_w4), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_val2), vget_high_s16(_w4), 0); _sum5 = vmlal_lane_s16(_sum5, vget_low_s16(_val2), vget_high_s16(_w4), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_val2), vget_high_s16(_w4), 2); _sum7 = vmlal_lane_s16(_sum7, vget_low_s16(_val2), vget_high_s16(_w4), 3); int16x8_t _w5 = vld1q_s16(k0 + 40); _sum0 = vmlal_lane_s16(_sum0, vget_high_s16(_val2), vget_low_s16(_w5), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_val2), vget_low_s16(_w5), 1); _sum2 = vmlal_lane_s16(_sum2, vget_high_s16(_val2), vget_low_s16(_w5), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_val2), vget_low_s16(_w5), 3); _sum4 = vmlal_lane_s16(_sum4, vget_high_s16(_val2), vget_high_s16(_w5), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_val2), vget_high_s16(_w5), 1); _sum6 = vmlal_lane_s16(_sum6, vget_high_s16(_val2), vget_high_s16(_w5), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_val2), vget_high_s16(_w5), 3); int16x8_t _w6 = vld1q_s16(k0 + 48); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_val3), vget_low_s16(_w6), 0); _sum1 = vmlal_lane_s16(_sum1, vget_low_s16(_val3), vget_low_s16(_w6), 1); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_val3), vget_low_s16(_w6), 2); _sum3 = vmlal_lane_s16(_sum3, vget_low_s16(_val3), vget_low_s16(_w6), 3); _sum4 = vmlal_lane_s16(_sum4, vget_low_s16(_val3), vget_high_s16(_w6), 0); _sum5 = vmlal_lane_s16(_sum5, vget_low_s16(_val3), vget_high_s16(_w6), 1); _sum6 = vmlal_lane_s16(_sum6, vget_low_s16(_val3), vget_high_s16(_w6), 2); _sum7 = vmlal_lane_s16(_sum7, vget_low_s16(_val3), vget_high_s16(_w6), 3); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_high_s16(_val3), vget_low_s16(_w7), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_val3), vget_low_s16(_w7), 1); _sum2 = vmlal_lane_s16(_sum2, vget_high_s16(_val3), vget_low_s16(_w7), 2); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_val3), vget_low_s16(_w7), 3); _sum4 = vmlal_lane_s16(_sum4, vget_high_s16(_val3), vget_high_s16(_w7), 0); _sum5 = vmlal_lane_s16(_sum5, vget_high_s16(_val3), vget_high_s16(_w7), 1); _sum6 = vmlal_lane_s16(_sum6, vget_high_s16(_val3), vget_high_s16(_w7), 2); _sum7 = vmlal_lane_s16(_sum7, vget_high_s16(_val3), vget_high_s16(_w7), 3); r0 += 32; k0 += 64; } vst1q_s32(output0_tm, _sum0); vst1q_s32(output1_tm, _sum1); vst1q_s32(output2_tm, _sum2); vst1q_s32(output3_tm, _sum3); vst1q_s32(output4_tm, _sum4); vst1q_s32(output5_tm, _sum5); vst1q_s32(output6_tm, _sum6); vst1q_s32(output7_tm, _sum7); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; output4_tm += 4; output5_tm += 4; output6_tm += 4; output7_tm += 4; } for (; i < tiles; i++) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 8 + (i % 8) / 4 + i % 4); #else const short* r0 = bb2.row<const short>(i / 4 + i % 4); #endif const short* k0 = kernel01_tm.row<const short>(r); int nn = inch; // inch always > 0 int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); for (int j = 0; j < nn; j++) { int16x8_t _val0 = vld1q_s16(r0); int16x8_t _w0 = vld1q_s16(k0); int16x8_t _w1 = vld1q_s16(k0 + 8); int16x8_t _w2 = vld1q_s16(k0 + 16); int16x8_t _w3 = vld1q_s16(k0 + 24); int16x8_t _w4 = vld1q_s16(k0 + 32); int16x8_t _w5 = vld1q_s16(k0 + 40); int16x8_t _w6 = vld1q_s16(k0 + 48); int16x8_t _w7 = vld1q_s16(k0 + 56); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w0), vget_low_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w0), vget_low_s16(_val0), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w1), vget_low_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w1), vget_low_s16(_val0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w2), vget_low_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w2), vget_low_s16(_val0), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w3), vget_low_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w3), vget_low_s16(_val0), 3); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w4), vget_high_s16(_val0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w4), vget_high_s16(_val0), 0); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w5), vget_high_s16(_val0), 1); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w5), vget_high_s16(_val0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w6), vget_high_s16(_val0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w6), vget_high_s16(_val0), 2); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_w7), vget_high_s16(_val0), 3); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_w7), vget_high_s16(_val0), 3); r0 += 8; k0 += 64; } output0_tm[0] = vgetq_lane_s32(_sum0, 0); output1_tm[0] = vgetq_lane_s32(_sum0, 1); output2_tm[0] = vgetq_lane_s32(_sum0, 2); output3_tm[0] = vgetq_lane_s32(_sum0, 3); output4_tm[0] = vgetq_lane_s32(_sum1, 0); output5_tm[0] = vgetq_lane_s32(_sum1, 1); output6_tm[0] = vgetq_lane_s32(_sum1, 2); output7_tm[0] = vgetq_lane_s32(_sum1, 3); output0_tm += 1; output1_tm += 1; output2_tm += 1; output3_tm += 1; output4_tm += 1; output5_tm += 1; output6_tm += 1; output7_tm += 1; } } } remain_outch_start += nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { int* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p / 8 + p % 8); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 7 < tiles; i += 8) { const short* r0 = bb2.row<const short>(i / 8); const short* kptr = kernel0_tm.row<const short>(r); int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); int32x4_t _sum2 = vdupq_n_s32(0); int32x4_t _sum3 = vdupq_n_s32(0); for (int q = 0; q < inch; q++) { int16x8_t _r0 = vld1q_s16(r0); int16x8_t _r1 = vld1q_s16(r0 + 8); int16x8_t _r2 = vld1q_s16(r0 + 16); int16x8_t _r3 = vld1q_s16(r0 + 24); int16x8_t _r4 = vld1q_s16(r0 + 32); int16x8_t _r5 = vld1q_s16(r0 + 40); int16x8_t _r6 = vld1q_s16(r0 + 48); int16x8_t _r7 = vld1q_s16(r0 + 56); int16x8_t _k0 = vld1q_s16(kptr); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r0), vget_low_s16(_k0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r0), vget_low_s16(_k0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_r1), vget_low_s16(_k0), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_r1), vget_low_s16(_k0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r2), vget_low_s16(_k0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r2), vget_low_s16(_k0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_r3), vget_low_s16(_k0), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_r3), vget_low_s16(_k0), 3); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r4), vget_high_s16(_k0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r4), vget_high_s16(_k0), 0); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_r5), vget_high_s16(_k0), 1); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_r5), vget_high_s16(_k0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r6), vget_high_s16(_k0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r6), vget_high_s16(_k0), 2); _sum2 = vmlal_lane_s16(_sum2, vget_low_s16(_r7), vget_high_s16(_k0), 3); _sum3 = vmlal_lane_s16(_sum3, vget_high_s16(_r7), vget_high_s16(_k0), 3); kptr += 8; r0 += 64; } _sum0 = vaddq_s32(_sum0, _sum2); _sum1 = vaddq_s32(_sum1, _sum3); vst1q_s32(output0_tm, _sum0); vst1q_s32(output0_tm + 4, _sum1); output0_tm += 8; } #endif for (; i + 3 < tiles; i += 4) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 8 + (i % 8) / 4); #else const short* r0 = bb2.row<const short>(i / 4); #endif const short* kptr = kernel0_tm.row<const short>(r); int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); for (int q = 0; q < inch; q++) { int16x8_t _r0 = vld1q_s16(r0); int16x8_t _r1 = vld1q_s16(r0 + 8); int16x8_t _r2 = vld1q_s16(r0 + 16); int16x8_t _r3 = vld1q_s16(r0 + 24); int16x8_t _k0 = vld1q_s16(kptr); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r0), vget_low_s16(_k0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r0), vget_low_s16(_k0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r1), vget_low_s16(_k0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r1), vget_low_s16(_k0), 3); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r2), vget_high_s16(_k0), 0); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r2), vget_high_s16(_k0), 1); _sum0 = vmlal_lane_s16(_sum0, vget_low_s16(_r3), vget_high_s16(_k0), 2); _sum1 = vmlal_lane_s16(_sum1, vget_high_s16(_r3), vget_high_s16(_k0), 3); kptr += 8; r0 += 32; } int32x4_t _sum01 = vaddq_s32(_sum0, _sum1); vst1q_s32(output0_tm, _sum01); output0_tm += 4; } for (; i < tiles; i++) { #if __aarch64__ const short* r0 = bb2.row<const short>(i / 8 + (i % 8) / 4 + i % 4); #else const short* r0 = bb2.row<const short>(i / 4 + i % 4); #endif const short* kptr = kernel0_tm.row<const short>(r); int32x4_t _sum0 = vdupq_n_s32(0); int32x4_t _sum1 = vdupq_n_s32(0); for (int q = 0; q < inch; q++) { int16x8_t _r0 = vld1q_s16(r0); int16x8_t _k0 = vld1q_s16(kptr); _sum0 = vmlal_s16(_sum0, vget_low_s16(_r0), vget_low_s16(_k0)); _sum1 = vmlal_s16(_sum1, vget_high_s16(_r0), vget_high_s16(_k0)); kptr += 8; r0 += 8; } int32x4_t _sum = vaddq_s32(_sum0, _sum1); #if __aarch64__ int sum = vaddvq_s32(_sum); // dot #else int32x2_t _ss = vadd_s32(vget_low_s32(_sum), vget_high_s32(_sum)); _ss = vpadd_s32(_ss, _ss); int sum = vget_lane_s32(_ss, 0); #endif output0_tm[0] = sum; output0_tm++; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, 1, opt.workspace_allocator); } { // const float otm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); int tmp[4][6]; // tile for (int i = 0; i < outh / 4; i++) { for (int j = 0; j < outw / 4; j++) { // top_blob_tm.create(tiles, 36, outch, 4u, 1, opt.workspace_allocator); const int* output0_tm_0 = (const int*)out0_tm + (i * w_tm / 6 + j) * 1; const int* output0_tm_1 = output0_tm_0 + tiles * 1; const int* output0_tm_2 = output0_tm_0 + tiles * 2; const int* output0_tm_3 = output0_tm_0 + tiles * 3; const int* output0_tm_4 = output0_tm_0 + tiles * 4; const int* output0_tm_5 = output0_tm_0 + tiles * 5; int* output0 = out0.row<int>(i * 4) + j * 4; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 // TODO neon optimize for (int m = 0; m < 5; m++) { int tmp02a = output0_tm_1[0] + output0_tm_2[0]; int tmp13a = output0_tm_1[0] - output0_tm_2[0]; int tmp02b = output0_tm_3[0] + output0_tm_4[0]; int tmp13b = output0_tm_3[0] - output0_tm_4[0]; tmp[0][m] = output0_tm_0[0] + tmp02a + tmp02b; tmp[1][m] = tmp13a + tmp13b * 2; tmp[2][m] = tmp02a + tmp02b * 4; tmp[3][m] = output0_tm_5[0] * 4 + tmp13a + tmp13b * 8; output0_tm_0 += tiles * 6; output0_tm_1 += tiles * 6; output0_tm_2 += tiles * 6; output0_tm_3 += tiles * 6; output0_tm_4 += tiles * 6; output0_tm_5 += tiles * 6; } for (int m = 5; m < 6; m++) { int tmp02a = output0_tm_1[0] + output0_tm_2[0]; int tmp13a = output0_tm_1[0] - output0_tm_2[0]; int tmp02b = output0_tm_3[0] + output0_tm_4[0]; int tmp13b = output0_tm_3[0] - output0_tm_4[0]; tmp[0][m] = (output0_tm_0[0] + tmp02a + tmp02b) * 4; tmp[1][m] = (tmp13a + tmp13b * 2) * 4; tmp[2][m] = (tmp02a + tmp02b * 4) * 4; tmp[3][m] = (output0_tm_5[0] * 4 + tmp13a + tmp13b * 8) * 4; output0_tm_0 += tiles * 6; output0_tm_1 += tiles * 6; output0_tm_2 += tiles * 6; output0_tm_3 += tiles * 6; output0_tm_4 += tiles * 6; output0_tm_5 += tiles * 6; } for (int m = 0; m < 4; m++) { const int* tmp0 = tmp[m]; int tmp02a = tmp0[1] + tmp0[2]; int tmp13a = tmp0[1] - tmp0[2]; int tmp02b = tmp0[3] + tmp0[4]; int tmp13b = tmp0[3] - tmp0[4]; output0[0] = (tmp0[0] + tmp02a + tmp02b) / 576; output0[1] = (tmp13a + tmp13b * 2) / 576; output0[2] = (tmp02a + tmp02b * 4) / 576; output0[3] = (tmp0[5] + tmp13a + tmp13b * 8) / 576; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
benchmark.c
/** * @file benchmark.c * @brief benchmark the amount of time saved by parallel program * @note compile with '--std=c99' * @author Lumin <cdluminate@gmail.com> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <omp.h> #include <sys/time.h> // high precision timer, gettimeofday() #include <assert.h> /** * @brief flag, set 1 to dump all debug information */ int debug = 0; /** * @brief vector length used in L-1 benchmarks */ #define VLEN 1024*1024*16 /** * @brief matrix size used in L-2 benchmarks */ #define MVLEN 1024*4 /** * @brief matrix size used in L-3 benchmarks */ #define MMLEN 256 /** * @brief IMLEN image size, KLEN kernel size, FLEN(IM,K) feature map size */ #define IMLEN 512 #define KLEN 17 #define FLEN(im,k) ((im-k+1)) /** * @breif dcopy, L-1 BLAS, serial */ void dcopy_serial (const double * src, double * dest, size_t n) { for (long i = 0; i < n; i++) dest[i] = src[i]; return; } /** * @brief dcopy, L-1 BLAS, parallel */ void dcopy_parallel (const double * src, double * dest, size_t n) { #pragma omp parallel for shared(src, dest) for (long i = 0; i < n; i++) dest[i] = src[i]; return; } /** * @brief dasum, L-1 BLAS, serial */ double dasum_serial (const double * a, size_t n) { double ret = 0.; for (long i = 0; i < n; i++) { ret += (a[i]>0.)?(a[i]):(-a[i]); //if (0 == i % 1000000) printf (" iter %ld, n = %lf\n", i, ret); // debug } return ret; } /** * @brief dasum, L-1 BLAS, parallel */ double dasum_parallel (const double * a, size_t n) { double ret = 0.; #pragma omp parallel for reduction (+:ret) for (long i = 0; i < n; i++) ret += (a[i]>0.)?(a[i]):(-a[i]); return ret; } /** * @brief dscal, L-1 BLAS, serial */ void dscal_serial (double * x, const double a, size_t n) { for (size_t i = 0; i < n; i++) x[i] *= a; } /** * @brief dscal, L-1 BLAS, parallel */ void dscal_parallel (double * x, const double a, size_t n) { #pragma omp parallel for shared(x) for (size_t i = 0; i < n; i++) x[i] *= a; } /** * @brief ddot, L-1 BLAS, serial */ double ddot_serial (const double * a, const double * b, size_t n) { double ret = 0.; for (long i = 0; i < n; i++) ret += a[i] * b[i]; return ret; } /** * @brief ddot, L-1 BLAS, parallel */ double ddot_parallel (const double * a, const double * b, size_t n) { double ret = 0.; #pragma omp parallel for reduction (+:ret) for (long i = 0; i < n; i++) ret += a[i] * b[i]; return ret; } /** * @brief daxpby, L-1 BLAS Extension, serial */ void daxpby_serial (const double * x, const double a, double * y, const double b, size_t n) { // a x + b y -> y for (long i = 0; i < n; i++) y[i] += a * x[i] + b * y[i]; } /** * @brief daxpby, L-1 BLAS Extension, parallel */ void daxpby_parallel (const double * x, const double a, double * y, const double b, size_t n) { // a x + b y -> y #pragma omp parallel for shared(x, y) for (long i = 0; i < n; i++) y[i] += a * x[i] + b * y[i]; } /** * @brief dgemv, L-2 BLAS, serial * @f[ a x * b y -> dest @f] */ void dgemv_serial (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { // note, x is matrix ! for (size_t i = 0; i < n; i++) { // for each row of x dest[i] = y[i]; for (size_t j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; } } } /** * @brief dgemv, L-2 BLAS, parallel * @f[ a x * b y -> dest @f] */ void dgemv_parallel (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { size_t j = 0; #pragma omp parallel for shared(x, y, dest) private(j) for (size_t i = 0; i < n; i++) { // for each row of x dest[i] = y[i]; for (j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; } } } /** * @brief dgemv, L-2 BLAS, parallel version 2 * @f[ a x * b y -> dest @f] */ void dgemv_parallelv2 (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { size_t j = 0; size_t i = 0; dcopy_parallel(y, dest, n); #pragma omp parallel for collapse(2) shared(x, y, dest) private(i,j) for (i = 0; i < n; i++) { // for each row of x for (j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; }} } /** * @brief dgemm, L-3 BLAS, serial version * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_serial (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } } } } /** * @brief dgemm, L-3 BLAS, parallel version * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_parallel (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; #pragma omp parallel for collapse(2) shared(A, B) private(nn) // Note, dynamic scheduler seems to reduce performance here for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } }} } /** * @brief dgemm, L-3 BLAS, parallel version 2 * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_parallelv2 (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; #pragma omp parallel for shared(A, B) private(kk,nn) for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } } } } /** * @brief 2-D convolution in serial * (Computer Vision Convolution, not Signal Convolution) * @param[in] smap source map * @param[in] dmap destination map * @param[in] m smap size * @param[in] k kernel size * @note no padding */ void conv2_serial (const double * smap, const double * kernel, size_t ssize, size_t ksize, double * dmap) { for (unsigned int i = 0; i < FLEN(ssize,ksize); i++) { // for each row of output map for (unsigned int j = 0; j < FLEN(ssize,ksize); j++) { // for each column of output map // element wise mult, smap part with kernel double sum = 0.; for (unsigned int m = 0; m < ksize; m++) { for (unsigned int n = 0; n < ksize; n++) { sum += kernel[m*ksize +n] * smap[(i+m)*ssize + j+n]; }} // finish (i,j) of output feature map dmap[i*FLEN(ssize,ksize)+j] = sum; }} return; } /** * @brief 2-D convolution in parallel * (Computer Vision Convolution, not Signal Convolution) */ void conv2_parallel (const double * smap, const double * kernel, size_t ssize, size_t ksize, double * dmap) { double sum = 0.; #pragma omp parallel for collapse(2) shared(smap,kernel,dmap) private(sum) for (unsigned int i = 0; i < FLEN(ssize,ksize); i++) { // for each row of output map for (unsigned int j = 0; j < FLEN(ssize,ksize); j++) { // for each column of output map // element wise mult, smap part with kernel sum = 0.; for (unsigned int m = 0; m < ksize; m++) { for (unsigned int n = 0; n < ksize; n++) { sum += kernel[m*ksize +n] * smap[(i+m)*ssize + j+n]; }} // finish (i,j) of output feature map dmap[i*FLEN(ssize,ksize)+j] = sum; }} return; } /** * @brief tell user the time difference in second. * @param tvs the starting time stamp. * @param tve the ending timp stamp. * @see sys/time.h, gettimeofday(2) */ void timediff (struct timeval tvs, struct timeval tve, char * msg) { long diff_sec = tve.tv_sec - tvs.tv_sec; long diff_usec = tve.tv_usec - tvs.tv_usec; double dtime = diff_sec + diff_usec/1e+6; fprintf (stdout, "I: [%s] time cost is %1.6f seconds.\n", (msg==NULL)?"":msg, dtime); } /** * @brief print a spliting line on screen */ void hrulefill (void) { for (int i = 0; i < 80; i++) fprintf (stdout, "-"); fprintf (stdout, "\n"); return; } /** * @brief dump a vector to screen */ void dump_vector (double * v, size_t size) { for (size_t i = 0; i < size; i++) fprintf (stdout, " %.3lf", v[i]); fprintf (stdout, "\n"); return; } /** * @brief dump a matrix to screen */ void dump_matrix (double * m, size_t row, size_t col) { for (size_t i = 0; i < row; i++) { for (size_t j = 0; j < col; j++) fprintf (stdout, " %.3lf", m[i*col+j]); fprintf (stdout, "\n"); } return; } /** * @brief allocate a vector in double * @note values of vector not initialized on allocation. */ double * new_vector (size_t len) { double * ret = (double *)malloc(len*sizeof(double)); assert(ret != NULL); return ret; } /** * @brief delete a vector in double */ void del_vector (double * v) { free(v); } /** * @brief fill a double vector with a value */ void fill_vector (double * v, size_t len, double val) { for (size_t i = 0; i < len; i++) v[i] = val; return; } /** * @brief allocate a double matrix */ double * new_matrix (size_t row, size_t col) { double * ret = (double *)malloc(row*col*sizeof(double)); assert(ret != NULL); return ret; } /** * @brief delete a matrix in double */ void del_matrix (double * m) { free(m); } /** * @brief fill a double matrix with a value */ void fill_matrix (double * m, size_t row, size_t col, double val) { for (size_t i = 0; i < row; i++) for (size_t j = 0; j < col; j++) m[i*col+j] = val; return; } /** * @brief Lumin's benchmark */ int main (int argc, char ** argv, char ** envp) { fprintf (stdout, "Lumin's serial/parallel benchmark\nI: init ... "); fflush(stdout); struct timeval tvs; // tv_s, for starting point struct timeval tve; // tv_e, for ending point // init times struct timeval tvi; // tv_init struct timeval tvt; // tv_terminate gettimeofday(&tvi, NULL); fprintf(stdout, "[OK]\n"); hrulefill(); { // copy test // data double * A = new_vector(VLEN); double * C = new_vector(VLEN); fill_vector(A, VLEN, 1.); fill_vector(C, VLEN, 0.); // serial gettimeofday(&tvs, NULL); dcopy_serial (A, C, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dcopy in serial"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // parallel gettimeofday(&tvs, NULL); dcopy_parallel (A, C, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dcopy in parallel"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // post-test del_vector(A); del_vector(C); } hrulefill(); { // asum test // data double * A = new_vector(VLEN); fill_vector(A, VLEN, 1.); // serial double resA; gettimeofday(&tvs, NULL); resA = dasum_serial (A, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dasum serial"); if (debug) dump_vector(A, VLEN); if (debug) fprintf (stdout, " dasum(A) = %lf\n", resA); // parallel double resB; gettimeofday(&tvs, NULL); resB = dasum_parallel (A, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dasum parallel"); if (debug) dump_vector(A, VLEN); if (debug) fprintf (stdout, " dasum(A) = %lf\n", resB); // post-test del_vector(A); } hrulefill(); { // dot test // data double * A = new_vector(VLEN); double * C = new_vector(VLEN); fill_vector(A, VLEN, 1.); fill_vector(C, VLEN, 1.); // serial double resA; gettimeofday(&tvs, NULL); resA = ddot_serial (A, C, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "ddot in serial"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); if (debug) fprintf (stdout, " ddot(A, C) = %lf\n", resA); // parallel double resB; gettimeofday(&tvs, NULL); resB = ddot_parallel (A, C, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "ddot in parallel"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); if (debug) fprintf (stdout, " ddot(A, C) = %lf\n", resB); // post-test del_vector(A); del_vector(C); } hrulefill(); { // scal test // data double * A = new_vector(VLEN); fill_vector(A, VLEN, 1.); // serial gettimeofday(&tvs, NULL); dscal_serial (A, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dscal in serial"); if (debug) dump_vector(A, VLEN); // parallel gettimeofday(&tvs, NULL); dscal_parallel (A, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "dscal in parallel"); if (debug) dump_vector(A, VLEN); // post-test del_vector(A); } hrulefill(); { // axpby test // data double * A = new_vector(VLEN); double * C = new_vector(VLEN); fill_vector(A, VLEN, 1.); fill_vector(C, VLEN, 1.); // serial gettimeofday(&tvs, NULL); daxpby_serial (A, 0.5, C, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "daxpby in serial"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // parallel gettimeofday(&tvs, NULL); daxpby_parallel (A, 0.5, C, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "daxpby in parallel"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // post-test del_vector(A); del_vector(C); } hrulefill(); { // gemv test // data double * M = new_matrix(MVLEN, MVLEN); double * A = new_vector(MVLEN); double * Y = new_vector(MVLEN); fill_matrix(M, MVLEN, MVLEN, 1.); fill_vector(A, MVLEN, 1.); fill_vector(Y, MVLEN, 1.); if (debug) dump_matrix(M, MVLEN, MVLEN); if (debug) dump_vector(A, MVLEN); // serial gettimeofday(&tvs, NULL); dgemv_serial (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in serial"); if (debug) dump_vector(Y, MVLEN); // parallel gettimeofday(&tvs, NULL); dgemv_parallel (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in parallel"); if (debug) dump_vector(Y, MVLEN); // parallelv2 gettimeofday(&tvs, NULL); dgemv_parallelv2 (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in parallelv2"); if (debug) dump_vector(Y, MVLEN); // post-test del_matrix(M); del_vector(A); del_vector(Y); } hrulefill(); { // gemm // data double * X = new_matrix(MMLEN, MMLEN); double * Y = new_matrix(MMLEN, MMLEN); double * Z = new_matrix(MMLEN, MMLEN); fill_matrix(X, MMLEN, MMLEN, 1.); fill_matrix(Y, MMLEN, MMLEN, 1.); fill_matrix(Z, MMLEN, MMLEN, 0.); if (debug) dump_matrix(X, MMLEN, MMLEN); if (debug) dump_matrix(Y, MMLEN, MMLEN); // serial gettimeofday(&tvs, NULL); dgemm_serial (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in serial"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // parallel gettimeofday(&tvs, NULL); dgemm_parallel (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in parallel"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // parallel v2 gettimeofday(&tvs, NULL); dgemm_parallelv2 (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in parallelv2"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // post-test del_matrix(X); del_matrix(Y); del_matrix(Z); } hrulefill(); { // convolution // data double * image = new_matrix(IMLEN, IMLEN); double * kernel = new_matrix(KLEN, KLEN); double * fmap = new_matrix(FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); fill_matrix(image, IMLEN, IMLEN, 1.); fill_matrix(kernel, KLEN, KLEN, 1.); fill_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN), 0.); if (debug) dump_matrix(image, IMLEN, IMLEN); if (debug) dump_matrix(kernel, KLEN, KLEN); // serial gettimeofday(&tvs, NULL); conv2_serial (image, kernel, IMLEN, KLEN, fmap); gettimeofday(&tve, NULL); timediff (tvs, tve, "conv2 in serial"); if (debug) dump_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); // parallel gettimeofday(&tvs, NULL); conv2_parallel (image, kernel, IMLEN, KLEN, fmap); gettimeofday(&tve, NULL); timediff (tvs, tve, "conv2 in parallel"); if (debug) dump_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); // post-test del_matrix(image); del_matrix(kernel); del_matrix(fmap); } hrulefill(); // how long all the benchmarks take gettimeofday(&tvt, NULL); timediff(tvi, tvt, "All benchmark"); return 0; }
count_func.c
/******************************************************************************* * 2pt_box/count_func.c: this file is part of the FCFC program. * FCFC: Fast Correlation Function Calculator. * Github repository: https://github.com/cheng-zhao/FCFC * Copyright (c) 2020 -- 2021 Cheng Zhao <zhaocheng03@gmail.com> [MIT license] *******************************************************************************/ #include "define.h" #include "load_conf.h" #include "count_func.h" #include "kdtree.h" #include <string.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #ifdef OMP #include <omp.h> #endif /*============================================================================*\ Data structure for storing dual nodes \*============================================================================*/ typedef struct { const void *a; const void *b; } DUAL_NODE; typedef struct { DUAL_NODE *nodes; size_t size; size_t capacity; } STACK_DUAL_NODE; /*============================================================================*\ Functions for stack manipulation \*============================================================================*/ /****************************************************************************** Function `stack_push`: Push an element to the stack for dual nodes. Arguments: * `s`: pointer to the stack; * `a`: the first node to be pushed to the stack; * `b`: the second node to be pushed to the stack. ******************************************************************************/ static void stack_push(STACK_DUAL_NODE *s, const void *a, const void *b) { if (s->size >= s->capacity) { /* Enlarge the memory allocated for the stack. */ if (s->capacity) { if ((FCFC_STACK_MAX_SIZE >> 1) <= s->capacity) { P_EXT("too many elements to be pushed to the stack of dual nodes\n"); exit(FCFC_ERR_MEMORY); } s->capacity <<= 1; } else { /* initialise the stack */ s->nodes = NULL; s->capacity = FCFC_STACK_INIT_SIZE; } if (s->capacity <= s->size) { P_EXT("unable to expand the size of the stack of dual nodes\n"); exit(FCFC_ERR_UNKNOWN); } DUAL_NODE *tmp = realloc(s->nodes, s->capacity * sizeof *tmp); if (!tmp) { P_EXT("failed to allocate memory for the stack of dual nodes\n"); exit(FCFC_ERR_MEMORY); } s->nodes = tmp; } s->nodes[s->size].a = a; s->nodes[s->size++].b = b; } /****************************************************************************** Function `stack_pop`: Pop one pair of nodes from the stack for dual nodes. Arguments: * `s`: pointer to the stack. Return: Address of the dual nodes on the top of the stack on success; NULL on error. ******************************************************************************/ static inline DUAL_NODE *stack_pop(STACK_DUAL_NODE *s) { if (!s->size) return NULL; s->size -= 1; return s->nodes + s->size; } /****************************************************************************** Function `stack_destroy`: Deconstruct the stack for dual nodes. Arguments: * `s`: pointer to the stack. ******************************************************************************/ static void stack_destroy(STACK_DUAL_NODE *s) { if (!s->capacity) return; s->size = s->capacity = 0; if (s->nodes) free(s->nodes); } /*============================================================================*\ Functions for distance evaluations \*============================================================================*/ /****************************************************************************** Function `squared_distance`: Compute the squared Euclidean distance between two points in 3-D space. Arguments: * `a`: pointer to the first data point; * `b`: pointer to the second data point; * `bsize`: side length of the periodic box. Return: The squared Euclidean distance of the two points. ******************************************************************************/ static inline real squared_distance(const DATA *restrict a, const DATA *restrict b, const real bsize) { register real dx = a->x[0] - b->x[0]; if (dx * 2 > bsize) dx -= bsize; else if (dx * 2 < -bsize) dx += bsize; register real dy = a->x[1] - b->x[1]; if (dy * 2 > bsize) dy -= bsize; else if (dy * 2 < -bsize) dy += bsize; register real dz = a->x[2] - b->x[2]; if (dz * 2 > bsize) dz -= bsize; else if (dz * 2 < -bsize) dz += bsize; return dx * dx + dy * dy + dz * dz; } /****************************************************************************** Function `squared_distance_with_pi`: Compute the squared Euclidean distance between two points in 3-D space, and report also the squared radial distance. Arguments: * `a`: pointer to the first data point; * `b`: pointer to the second data point; * `bsize`: side length of the periodic box; * `pi`: the squared radial distance. Return: The squared Euclidean distance of the two points. ******************************************************************************/ static inline real squared_distance_with_pi(const DATA *restrict a, const DATA *restrict b, const real bsize, real *pi) { register real dx = a->x[0] - b->x[0]; if (dx * 2 > bsize) dx -= bsize; else if (dx * 2 < -bsize) dx += bsize; register real dy = a->x[1] - b->x[1]; if (dy * 2 > bsize) dy -= bsize; else if (dy * 2 < -bsize) dy += bsize; register real dz = a->x[2] - b->x[2]; if (dz * 2 > bsize) dz -= bsize; else if (dz * 2 < -bsize) dz += bsize; *pi = dz * dz; return dx * dx + dy * dy + *pi; } /****************************************************************************** Function `unsigned_distance_par`: Compute the unsigned radial Euclidean distance between two points in 3-D. Arguments: * `a`: pointer to the first data point; * `b`: pointer to the second data point; * `bsize`: side length of the periodic box. Return: The unsigned radial Euclidean distance of the two points. ******************************************************************************/ static inline real unsigned_distance_par(const DATA *restrict a, const DATA *restrict b, const real bsize) { register real dz = a->x[2] - b->x[2]; if (dz * 2 > bsize) dz -= bsize; else if (dz * 2 < -bsize) dz += bsize; if (dz < 0) return -dz; return dz; } /****************************************************************************** Function `squared_distance_perp`: Compute the squared Euclidean distance between two points in 3-D space perpendicular to the line of sight. Arguments: * `a`: pointer to the first data point; * `b`: pointer to the second data point; * `bsize`: side length of the periodic box. Return: The squared perpendicular Euclidean distance of the two points. ******************************************************************************/ static inline real squared_distance_perp(const DATA *restrict a, const DATA *restrict b, const real bsize) { register real dx = a->x[0] - b->x[0]; if (dx * 2 > bsize) dx -= bsize; else if (dx * 2 < -bsize) dx += bsize; register real dy = a->x[1] - b->x[1]; if (dy * 2 > bsize) dy -= bsize; else if (dy * 2 < -bsize) dy += bsize; return dx * dx + dy * dy; } /****************************************************************************** Function `min_squared_dist_between_box`: Compute the minimum squared distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The minimum squared distance between the two boxes. ******************************************************************************/ static inline real min_squared_dist_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real sum = 0; for (int i = 0; i < 3; i++) { real d; if (min1->x[i] < min2->x[i]) { real d1 = min2->x[i] - max1->x[i]; real d2 = min1->x[i] - max2->x[i] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) continue; } else { real d1 = min1->x[i] - max2->x[i]; real d2 = min2->x[i] - max1->x[i] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) continue; } sum += d * d; } return sum; } /****************************************************************************** Function `min_unsigned_dist_par_between_box`: Compute the minimum unsigned radial distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The minimum unsigned radial distance between the two boxes. ******************************************************************************/ static inline real min_unsigned_dist_par_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real d; if (min1->x[2] < min2->x[2]) { real d1 = min2->x[2] - max1->x[2]; real d2 = min1->x[2] - max2->x[2] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) return 0; } else { real d1 = min1->x[2] - max2->x[2]; real d2 = min2->x[2] - max1->x[2] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) return 0; } return d; } /****************************************************************************** Function `min_squared_dist_perp_between_box`: Compute the minimum squared perpendicular distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The minimum squared perpendicular distance between the two boxes. ******************************************************************************/ static inline real min_squared_dist_perp_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real sum = 0; for (int i = 0; i < 2; i++) { real d; if (min1->x[i] < min2->x[i]) { real d1 = min2->x[i] - max1->x[i]; real d2 = min1->x[i] - max2->x[i] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) continue; } else { real d1 = min1->x[i] - max2->x[i]; real d2 = min2->x[i] - max1->x[i] + bsize; d = (d1 < d2) ? d1 : d2; if (d <= 0) continue; } sum += d * d; } return sum; } /****************************************************************************** Function `max_squared_dist_between_box`: Compute the maximum squared distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The maximum squared distance between the two boxes. ******************************************************************************/ static inline real max_squared_dist_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real sum = 0; for (int i = 0; i < 3; i++) { real d1, d2; if (min1->x[i] + max1->x[i] < min2->x[i] + max2->x[i]) { d1 = max2->x[i] - min1->x[i]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max1->x[i] - min2->x[i]; if (d2 < 0) d2 += bsize; } else { d1 = max1->x[i] - min2->x[i]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max2->x[i] - min1->x[i]; if (d2 < 0) d2 += bsize; } real d = (d1 > d2) ? d1 : d2; sum += d * d; } return sum; } /****************************************************************************** Function `max_unsigned_dist_par_between_box`: Compute the maximum unsigned radial distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The maximum unsigned radial distance between the two boxes. ******************************************************************************/ static inline real max_unsigned_dist_par_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real d1, d2; if (min1->x[2] + max1->x[2] < min2->x[2] + max2->x[2]) { d1 = max2->x[2] - min1->x[2]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max1->x[2] - min2->x[2]; if (d2 < 0) d2 += bsize; } else { d1 = max1->x[2] - min2->x[2]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max2->x[2] - min1->x[2]; if (d2 < 0) d2 += bsize; } real d = (d1 > d2) ? d1 : d2; return d; } /****************************************************************************** Function `max_squared_dist_perp_between_box`: Compute the maximum squared perpendicular distance between two boxes. Arguments: * `min1`: the lower corner of the first box; * `max1`: the upper corner of the first box; * `min2`: the lower corner of the second box; * `max2`: the upper corner of the second box; * `bsize`: side length of the periodic box. Return: The maximum squared perpendicular distance between the two boxes. ******************************************************************************/ static inline real max_squared_dist_perp_between_box(const DATA *restrict min1, const DATA *restrict max1, const DATA *restrict min2, const DATA *restrict max2, const real bsize) { real sum = 0; for (int i = 0; i < 2; i++) { real d1, d2; if (min1->x[i] + max1->x[i] < min2->x[i] + max2->x[i]) { d1 = max2->x[i] - min1->x[i]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max1->x[i] - min2->x[i]; if (d2 < 0) d2 += bsize; } else { d1 = max1->x[i] - min2->x[i]; if (d1 * 2 > bsize) d1 -= bsize; d2 = max2->x[i] - min1->x[i]; if (d2 < 0) d2 += bsize; } real d = (d1 > d2) ? d1 : d2; sum += d * d; } return sum; } /****************************************************************************** Function `find_dist_bin`: Find the index of a squared distance in the bins, using binary search. Arguments: * `dist`: the given distance; * `rbin`: the array for distance bins; * `n`: the number of distance bins. Output: Index of the bin on success; SIZE_MAX if the bin is not found. ******************************************************************************/ static inline size_t find_dist_bin(const real dist, const real *restrict dbin, const int n) { size_t l, u; l = 0; u = n - 1; while (l <= u) { size_t i = (l + u) >> 1; if (dbin[i + 1] <= dist) l = i + 1; else if (dbin[i] > dist) u = i - 1; else return i; } return SIZE_MAX; } /*============================================================================*\ Pair counting functions from templates \*============================================================================*/ /* Clean all the relevant macros first */ #ifdef FCFC_TREE_TYPE #undef FCFC_TREE_TYPE #endif #ifdef FCFC_CNT_TYPE #undef FCFC_CNT_TYPE #endif #ifdef FCFC_BIN_TYPE #undef FCFC_BIN_TYPE #endif #ifdef FCFC_BIN_PREC #undef FCFC_BIN_PREC #endif #ifdef FCFC_BIN_SMIN #undef FCFC_BIN_SMIN #endif #ifdef FCFC_BIN_PMIN #undef FCFC_BIN_PMIN #endif /******************************************************************************* k-D tree *******************************************************************************/ #define FCFC_TREE_TYPE FCFC_TREE_TYPE_KDTREE /* kdtree_auto_iso_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_iso_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_iso_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_iso_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_iso_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_iso_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_smu_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_exact_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_auto_spi_exact_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_auto_spi_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_intbin_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_auto_spi_intbin_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_auto_spi_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_auto_spi_trunc_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_auto_spi_trunc_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_AUTO #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_iso_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_iso_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_iso_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_iso_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_iso_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_iso_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_ISO #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_smu_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SMU #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_exact */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_exact_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_exact_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_spi_exact_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_EXACT #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_spi_intbin */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_intbin_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_intbin_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_spi_intbin_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_INTEG #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_spi_trunc */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_trunc_smin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_NONZERO #include "dual_tree.c" /* kdtree_cross_spi_trunc_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_NONZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /* kdtree_cross_spi_trunc_smin0_pmin0 */ #define FCFC_CNT_TYPE FCFC_PAIR_COUNT_CROSS #define FCFC_BIN_TYPE FCFC_BIN_SPI #define FCFC_BIN_PREC FCFC_BIN_TRUNC #define FCFC_BIN_SMIN FCFC_BIN_MIN_ZERO #define FCFC_BIN_PMIN FCFC_BIN_MIN_ZERO #include "dual_tree.c" /*============================================================================*\ Interface for pair counting \*============================================================================*/ /****************************************************************************** Function `count_pairs`: Count cross pairs based on the k-D tree data structure. Arguments: * `tree1`: pointer to the root of the first k-D tree; * `tree2`: pointer to the root of the second k-D tree; * `cf`: structure for congifurations of correlation functions; * `cnt`: array for storing pair counts; * `isauto`: true for counting auto pairs. ******************************************************************************/ void count_pairs(const void *tree1, const void *tree2, CF *cf, size_t *cnt, bool isauto) { /* Choose the optimal pair counting function. */ void (*pair_count_func) (STACK_DUAL_NODE *, const CF *, size_t *) = NULL; bool smin0 = (cf->sbin[0] < REAL_TOL && cf->sbin[0] > -REAL_TOL); if (isauto) { if (cf->bintype == FCFC_BIN_ISO) { if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) pair_count_func = kdtree_auto_iso_exact_smin0; else pair_count_func = kdtree_auto_iso_exact; } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) pair_count_func = kdtree_auto_iso_intbin_smin0; else pair_count_func = kdtree_auto_iso_intbin; } else { /* FCFC_BIN_TRUNC */ if (smin0) pair_count_func = kdtree_auto_iso_trunc_smin0; else pair_count_func = kdtree_auto_iso_trunc; } } else if (cf->bintype == FCFC_BIN_SMU) { if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) pair_count_func = kdtree_auto_smu_exact_smin0; else pair_count_func = kdtree_auto_smu_exact; } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) pair_count_func = kdtree_auto_smu_intbin_smin0; else pair_count_func = kdtree_auto_smu_intbin; } else { /* FCFC_BIN_TRUNC */ if (smin0) pair_count_func = kdtree_auto_smu_trunc_smin0; else pair_count_func = kdtree_auto_smu_trunc; } } else { /* FCFC_BIN_SPI */ bool pmin0 = (cf->pbin[0] < REAL_TOL && cf->pbin[0] > -REAL_TOL); if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) { if (pmin0) pair_count_func = kdtree_auto_spi_exact_smin0_pmin0; else pair_count_func = kdtree_auto_spi_exact_smin0; } else { if (pmin0) pair_count_func = kdtree_auto_spi_exact_pmin0; else pair_count_func = kdtree_auto_spi_exact; } } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) { if (pmin0) pair_count_func = kdtree_auto_spi_intbin_smin0_pmin0; else pair_count_func = kdtree_auto_spi_intbin_smin0; } else { if (pmin0) pair_count_func = kdtree_auto_spi_intbin_pmin0; else pair_count_func = kdtree_auto_spi_intbin; } } else { /* FCFC_BIN_TRUNC */ if (smin0) { if (pmin0) pair_count_func = kdtree_auto_spi_trunc_smin0_pmin0; else pair_count_func = kdtree_auto_spi_trunc_smin0; } else { if (pmin0) pair_count_func = kdtree_auto_spi_trunc_pmin0; else pair_count_func = kdtree_auto_spi_trunc; } } } } else { if (cf->bintype == FCFC_BIN_ISO) { if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) pair_count_func = kdtree_cross_iso_exact_smin0; else pair_count_func = kdtree_cross_iso_exact; } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) pair_count_func = kdtree_cross_iso_intbin_smin0; else pair_count_func = kdtree_cross_iso_intbin; } else { /* FCFC_BIN_TRUNC */ if (smin0) pair_count_func = kdtree_cross_iso_trunc_smin0; else pair_count_func = kdtree_cross_iso_trunc; } } else if (cf->bintype == FCFC_BIN_SMU) { if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) pair_count_func = kdtree_cross_smu_exact_smin0; else pair_count_func = kdtree_cross_smu_exact; } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) pair_count_func = kdtree_cross_smu_intbin_smin0; else pair_count_func = kdtree_cross_smu_intbin; } else { /* FCFC_BIN_TRUNC */ if (smin0) pair_count_func = kdtree_cross_smu_trunc_smin0; else pair_count_func = kdtree_cross_smu_trunc; } } else { /* FCFC_BIN_SPI */ bool pmin0 = (cf->pbin[0] < REAL_TOL && cf->pbin[0] > -REAL_TOL); if (cf->prec == REAL_NAN) { /* FCFC_BIN_EXACT */ if (smin0) { if (pmin0) pair_count_func = kdtree_cross_spi_exact_smin0_pmin0; else pair_count_func = kdtree_cross_spi_exact_smin0; } else { if (pmin0) pair_count_func = kdtree_cross_spi_exact_pmin0; else pair_count_func = kdtree_cross_spi_exact; } } else if (cf->prec == 1) { /* FCFC_BIN_INTEG */ if (smin0) { if (pmin0) pair_count_func = kdtree_cross_spi_intbin_smin0_pmin0; else pair_count_func = kdtree_cross_spi_intbin_smin0; } else { if (pmin0) pair_count_func = kdtree_cross_spi_intbin_pmin0; else pair_count_func = kdtree_cross_spi_intbin; } } else { /* FCFC_BIN_TRUNC */ if (smin0) { if (pmin0) pair_count_func = kdtree_cross_spi_trunc_smin0_pmin0; else pair_count_func = kdtree_cross_spi_trunc_smin0; } else { if (pmin0) pair_count_func = kdtree_cross_spi_trunc_pmin0; else pair_count_func = kdtree_cross_spi_trunc; } } } } /* Initialise the stack for dual nodes. */ STACK_DUAL_NODE stack; stack.size = stack.capacity = 0; stack_push(&stack, tree1, tree2); #ifdef OMP /* Assign tasks to different OpenMP threads. */ size_t size = stack.size; /* for visiting all nodes at the same level */ while (stack.size != size || stack.size < (size_t) cf->nthread * FCFC_STACK_SIZE_PER_THREAD) { pair_count_func(&stack, cf, cnt); if (!stack.size) return; /* all pairs have been recorded */ if (size > 1) { size -= 1; /* reorder dual nodes, to ensure nodes at the same level are visited */ DUAL_NODE tmp = stack.nodes[stack.size - 1]; stack.nodes[stack.size - 1] = stack.nodes[size - 1]; stack.nodes[size - 1] = tmp; } else size = stack.size; } /* Clean the array for storing thread-private pair counts. */ memset(cf->pcnt, 0, sizeof(size_t) * cf->ntot * cf->nthread); #pragma omp parallel { STACK_DUAL_NODE ps; /* thread-private stack */ ps.size = ps.capacity = 0; const int tid = omp_get_thread_num(); #pragma omp for schedule(dynamic) for (size_t i = 0; i < stack.size; i++) { stack_push(&ps, stack.nodes[i].a, stack.nodes[i].b); while (ps.size) pair_count_func(&ps, cf, cf->pcnt + tid * cf->ntot); } stack_destroy(&ps); } /* Gather pair counts from threads. */ #pragma omp parallel for for (size_t i = 0; i < cf->ntot; i++) { for (int j = 0; j < cf->nthread; j++) cnt[i] += cf->pcnt[i + j * cf->ntot]; } #else while (stack.size) pair_count_func(&stack, cf, cnt); #endif stack_destroy(&stack); }
hessian.c
/* Author: Sebastian Wouters <sebastianwouters@gmail.com> Date: August 3, 2015 Augmented Hessian Newton-Raphson optimization of 1. either the Edmiston-Ruedenberg localization cost function 2. or the Boys localization cost function in both cases with an analytic gradient and hessian Reference: C. Edmiston and K. Ruedenberg, Reviews of Modern Physics 35, 457-464 (1963). http://dx.doi.org/10.1103/RevModPhys.35.457 http://sebwouters.github.io/CheMPS2/doxygen/classCheMPS2_1_1EdmistonRuedenberg.html */ #include <stdlib.h> void hessian_boys(const int Norbs, double * x_symm, double * y_symm, double * z_symm, double * vector_in, double * vector_out){ int rowindex,p,q,r,s; const int num_vars = (Norbs*(Norbs-1))/2; // for (p=0; p<Norbs; p++){ // for (q=p+1; q<Norbs; q++){ // const int rowindex == q + p * Norbs - ((p+1)*(p+2))/2 #pragma omp parallel for schedule(static) for (rowindex=0; rowindex<num_vars; rowindex++){ s = num_vars - 1 - rowindex; r = 2; while ( (r*(r-1))/2 <= s ){ r++; } p = Norbs - r; q = rowindex - p*Norbs + ((p+1)*(p+2))/2; double value = 0.0; // Part 1: p == r for (s=p+1; s<Norbs; s++){ const int arg_pq = p + Norbs * q; const int arg_ps = p + Norbs * s; const int arg_qs = q + Norbs * s; const int arg_pp = p + Norbs * p; const int arg_qq = q + Norbs * q; const int arg_ss = s + Norbs * s; const double prefactor = ( 2 * x_symm[arg_pq] * x_symm[arg_ps] + x_symm[arg_qs] * ( x_symm[arg_pp] - 0.5 * x_symm[arg_qq] - 0.5 * x_symm[arg_ss] ) ) + ( 2 * y_symm[arg_pq] * y_symm[arg_ps] + y_symm[arg_qs] * ( y_symm[arg_pp] - 0.5 * y_symm[arg_qq] - 0.5 * y_symm[arg_ss] ) ) + ( 2 * z_symm[arg_pq] * z_symm[arg_ps] + z_symm[arg_qs] * ( z_symm[arg_pp] - 0.5 * z_symm[arg_qq] - 0.5 * z_symm[arg_ss] ) ); const int colindex = rowindex + s - q; // s + p * Norbs - ((p+1)*(p+2))/2 value += prefactor * vector_in[ colindex ]; } // Part 2: q == s for (r=0; r<q; r++){ const int arg_pq = p + Norbs * q; const int arg_rq = r + Norbs * q; const int arg_pr = p + Norbs * r; const int arg_qq = q + Norbs * q; const int arg_pp = p + Norbs * p; const int arg_rr = r + Norbs * r; const double prefactor = ( 2 * x_symm[arg_pq] * x_symm[arg_rq] + x_symm[arg_pr] * ( x_symm[arg_qq] - 0.5 * x_symm[arg_pp] - 0.5 * x_symm[arg_rr] ) ) + ( 2 * y_symm[arg_pq] * y_symm[arg_rq] + y_symm[arg_pr] * ( y_symm[arg_qq] - 0.5 * y_symm[arg_pp] - 0.5 * y_symm[arg_rr] ) ) + ( 2 * z_symm[arg_pq] * z_symm[arg_rq] + z_symm[arg_pr] * ( z_symm[arg_qq] - 0.5 * z_symm[arg_pp] - 0.5 * z_symm[arg_rr] ) ); const int colindex = q + r * Norbs - ((r+1)*(r+2))/2; value += prefactor * vector_in[ colindex ]; } // Part 3: q == r for (s=q+1; s<Norbs; s++){ const int arg_pq = p + Norbs * q; const int arg_qs = q + Norbs * s; const int arg_ps = p + Norbs * s; const int arg_qq = q + Norbs * q; const int arg_pp = p + Norbs * p; const int arg_ss = s + Norbs * s; const double prefactor = ( 2 * x_symm[arg_pq] * x_symm[arg_qs] + x_symm[arg_ps] * ( x_symm[arg_qq] - 0.5 * x_symm[arg_pp] - 0.5 * x_symm[arg_ss] ) ) + ( 2 * y_symm[arg_pq] * y_symm[arg_qs] + y_symm[arg_ps] * ( y_symm[arg_qq] - 0.5 * y_symm[arg_pp] - 0.5 * y_symm[arg_ss] ) ) + ( 2 * z_symm[arg_pq] * z_symm[arg_qs] + z_symm[arg_ps] * ( z_symm[arg_qq] - 0.5 * z_symm[arg_pp] - 0.5 * z_symm[arg_ss] ) ); const int colindex = s + q * Norbs - ((q+1)*(q+2))/2; value -= prefactor * vector_in[ colindex ]; } // Part 4: p == s for (r=0; r<p; r++){ const int arg_pq = p + Norbs * q; const int arg_rp = r + Norbs * p; const int arg_qr = q + Norbs * r; const int arg_pp = p + Norbs * p; const int arg_qq = q + Norbs * q; const int arg_rr = r + Norbs * r; const double prefactor = ( 2 * x_symm[arg_pq] * x_symm[arg_rp] + x_symm[arg_qr] * ( x_symm[arg_pp] - 0.5 * x_symm[arg_qq] - 0.5 * x_symm[arg_rr] ) ) + ( 2 * y_symm[arg_pq] * y_symm[arg_rp] + y_symm[arg_qr] * ( y_symm[arg_pp] - 0.5 * y_symm[arg_qq] - 0.5 * y_symm[arg_rr] ) ) + ( 2 * z_symm[arg_pq] * z_symm[arg_rp] + z_symm[arg_qr] * ( z_symm[arg_pp] - 0.5 * z_symm[arg_qq] - 0.5 * z_symm[arg_rr] ) ); const int colindex = p + r * Norbs - ((r+1)*(r+2))/2; value -= prefactor * vector_in[ colindex ]; } vector_out[ rowindex ] = -Norbs*value; } } void hessian_edmiston(const int Norbs, double * eri, double * vector_in, double * vector_out){ int rowindex,p,q,r,s; const int num_vars = (Norbs*(Norbs-1))/2; // for (p=0; p<Norbs; p++){ // for (q=p+1; q<Norbs; q++){ // const int rowindex == q + p * Norbs - ((p+1)*(p+2))/2 #pragma omp parallel for schedule(static) for (rowindex=0; rowindex<num_vars; rowindex++){ s = num_vars - 1 - rowindex; r = 2; while ( (r*(r-1))/2 <= s ){ r++; } p = Norbs - r; q = rowindex - p*Norbs + ((p+1)*(p+2))/2; double value = 0.0; // Part 1: p == r for (s=p+1; s<Norbs; s++){ const int pqps = p + Norbs * ( q + Norbs * ( p + Norbs * s )); const int ppqs = p + Norbs * ( p + Norbs * ( q + Norbs * s )); const int qqqs = q + Norbs * ( q + Norbs * ( q + Norbs * s )); const int sssq = s + Norbs * ( s + Norbs * ( s + Norbs * q )); const double prefactor = 2*(4*eri[pqps] + 2*eri[ppqs] - eri[qqqs] - eri[sssq]); const int colindex = rowindex + s - q; // s + p * Norbs - ((p+1)*(p+2))/2 value += prefactor * vector_in[ colindex ]; } // Part 2: q == s for (r=0; r<q; r++){ const int qpqr = q + Norbs * ( p + Norbs * ( q + Norbs * r )); const int qqpr = q + Norbs * ( q + Norbs * ( p + Norbs * r )); const int pppr = p + Norbs * ( p + Norbs * ( p + Norbs * r )); const int rrrp = r + Norbs * ( r + Norbs * ( r + Norbs * p )); const double prefactor = 2*(4*eri[qpqr] + 2*eri[qqpr] - eri[pppr] - eri[rrrp]); const int colindex = q + r * Norbs - ((r+1)*(r+2))/2; value += prefactor * vector_in[ colindex ]; } // Part 3: q == r for (s=q+1; s<Norbs; s++){ const int qpqs = q + Norbs * ( p + Norbs * ( q + Norbs * s )); const int qqps = q + Norbs * ( q + Norbs * ( p + Norbs * s )); const int ppps = p + Norbs * ( p + Norbs * ( p + Norbs * s )); const int sssp = s + Norbs * ( s + Norbs * ( s + Norbs * p )); const double prefactor = 2*(4*eri[qpqs] + 2*eri[qqps] - eri[ppps] - eri[sssp]); const int colindex = s + q * Norbs - ((q+1)*(q+2))/2; value -= prefactor * vector_in[ colindex ]; } // Part 4: p == s for (r=0; r<p; r++){ const int pqpr = p + Norbs * ( q + Norbs * ( p + Norbs * r )); const int ppqr = p + Norbs * ( p + Norbs * ( q + Norbs * r )); const int qqqr = q + Norbs * ( q + Norbs * ( q + Norbs * r )); const int rrrq = r + Norbs * ( r + Norbs * ( r + Norbs * q )); const double prefactor = 2*(4*eri[pqpr] + 2*eri[ppqr] - eri[qqqr] - eri[rrrq]); const int colindex = p + r * Norbs - ((r+1)*(r+2))/2; value -= prefactor * vector_in[ colindex ]; } vector_out[ rowindex ] = -value; } }
omp_builtin.c
/* * BUILT IN BARRIER: OPENMP * To show correct functionality of barrier: Uncomment printf in main * To compile: gcc -o omp_builtin omp_builtin.c -lm -fopenmp * To run: ./omp_builtin [num_threads num_barriers] */ #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <sys/time.h> #include <stdbool.h> int P, N; int main(int argc, char* argv[]) { if (argc == 3){ if (sscanf (argv[1], "%d", &P)!=1) printf ("P - not an integer\n"); if (sscanf (argv[2], "%d", &N)!=1) printf ("N - not an integer\n"); } else{ //Number of processors P = 4; //Number of loops N = 5; } struct timeval tv1, tv2; double total_time; int pid_sense = 1; omp_set_num_threads(P); gettimeofday(&tv1, NULL); #pragma omp parallel shared (N) firstprivate(pid_sense) { int i; for(i=0;i<N;i++) { // printf("==============BARRIER %d=================\n", i); #pragma omp barrier #pragma omp barrier #pragma omp barrier #pragma omp barrier #pragma omp barrier } } gettimeofday(&tv2, NULL); total_time = (double) (tv2.tv_usec - tv1.tv_usec) + (double) (tv2.tv_sec - tv1.tv_sec)*1000000; printf("\nSUMMARY:\nTotal run-time for %d " "loops with 5 barriers per loop: %fs\n" "The average time per barrier: %fus\n", N, total_time/1000000, (double)(total_time/(N*5))); return 0; }
fft.ref.c
#include <sys/time.h> #include <time.h> #include <stdio.h> static unsigned long long current_time_ns() { #ifdef __MACH__ clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); unsigned long long s = 1000000000ULL * (unsigned long long)mts.tv_sec; return (unsigned long long)mts.tv_nsec + s; #else struct timespec t ={0,0}; clock_gettime(CLOCK_MONOTONIC, &t); unsigned long long s = 1000000000ULL * (unsigned long long)t.tv_sec; return (((unsigned long long)t.tv_nsec)) + s; #endif } /**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ /* * Original code from the Cilk project * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include "bots.h" #include "app-desc.h" /* Definitions and operations for complex numbers */ /* * compute the W coefficients (that is, powers of the root of 1) * and store them into an array. */ void compute_w_coefficients(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; #pragma omp task untied compute_w_coefficients(n, a, ab, W); #pragma omp task untied compute_w_coefficients(n, ab + 1, b, W); #pragma omp taskwait ; } } void compute_w_coefficients_seq(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; compute_w_coefficients_seq(n, a, ab, W); compute_w_coefficients_seq(n, ab + 1, b, W); } } /* * Determine (in a stupid way) if n is divisible by eight, then by four, else * find the smallest prime factor of n. */ int factor(int n) { int r; if (n < 2) return 1; if (n == 64 || n == 128 || n == 256 || n == 1024 || n == 2048 || n == 4096) return 8; if ((n & 15) == 0) return 16; if ((n & 7) == 0) return 8; if ((n & 3) == 0) return 4; if ((n & 1) == 0) return 2; /* try odd numbers up to n (computing the sqrt may be slower) */ for (r = 3; r < n; r += 2) if (n % r == 0) return r; /* n is prime */ return n; } void unshuffle(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; #pragma omp task untied unshuffle(a, ab, in, out, r, m); #pragma omp task untied unshuffle(ab, b, in, out, r, m); #pragma omp taskwait ; } } void unshuffle_seq(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; unshuffle_seq(a, ab, in, out, r, m); unshuffle_seq(ab, b, in, out, r, m); } } void fft_twiddle_gen1(COMPLEX * in, COMPLEX * out, COMPLEX * W, int r, int m, int nW, int nWdnti, int nWdntm) { int j, k; COMPLEX *jp, *kp; for (k = 0, kp = out; k < r; ++k, kp += m) { REAL r0, i0, rt, it, rw, iw; int l1 = nWdnti + nWdntm * k; int l0; r0 = i0 = 0.0; for (j = 0, jp = in, l0 = 0; j < r; ++j, jp += m) { rw = c_re(W[l0]); iw = c_im(W[l0]); rt = c_re(*jp); it = c_im(*jp); r0 += rt * rw - it * iw; i0 += rt * iw + it * rw; l0 += l1; if (l0 > nW) l0 -= nW; } c_re(*kp) = r0; c_im(*kp) = i0; } } void fft_twiddle_gen(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { #pragma omp task untied fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; #pragma omp task untied fft_twiddle_gen(i, i2, in, out, W, nW, nWdn, r, m); #pragma omp task untied fft_twiddle_gen(i2, i1, in, out, W, nW, nWdn, r, m); } #pragma omp taskwait ; } void fft_twiddle_gen_seq(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; fft_twiddle_gen_seq(i, i2, in, out, W, nW, nWdn, r, m); fft_twiddle_gen_seq(i2, i1, in, out, W, nW, nWdn, r, m); } } /* machine-generated code begins here */ void fft_base_2(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(in[0]); i1_0 = c_im(in[0]); r1_1 = c_re(in[1]); i1_1 = c_im(in[1]); c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[1]) = (r1_0 - r1_1); c_im(out[1]) = (i1_0 - i1_1); } void fft_twiddle_2(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_2(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_2(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; fft_twiddle_2_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_2_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_2(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_2(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_2(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_2_seq(a, ab, in, out, m); fft_unshuffle_2_seq(ab, b, in, out, m); } } void fft_base_4(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(in[0]); i2_0 = c_im(in[0]); r2_2 = c_re(in[2]); i2_2 = c_im(in[2]); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; r2_1 = c_re(in[1]); i2_1 = c_im(in[1]); r2_3 = c_re(in[3]); i2_3 = c_im(in[3]); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[2]) = (r1_0 - r1_1); c_im(out[2]) = (i1_0 - i1_1); c_re(out[1]) = (r1_2 + i1_3); c_im(out[1]) = (i1_2 - r1_3); c_re(out[3]) = (r1_2 - i1_3); c_im(out[3]) = (i1_2 + r1_3); } void fft_twiddle_4(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_4(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_4(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; fft_twiddle_4_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_4_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_4(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_4(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_4(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_4_seq(a, ab, in, out, m); fft_unshuffle_4_seq(ab, b, in, out, m); } } void fft_base_8(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(in[0]); i3_0 = c_im(in[0]); r3_4 = c_re(in[4]); i3_4 = c_im(in[4]); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; r3_2 = c_re(in[2]); i3_2 = c_im(in[2]); r3_6 = c_re(in[6]); i3_6 = c_im(in[6]); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; r3_1 = c_re(in[1]); i3_1 = c_im(in[1]); r3_5 = c_re(in[5]); i3_5 = c_im(in[5]); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; r3_3 = c_re(in[3]); i3_3 = c_im(in[3]); r3_7 = c_re(in[7]); i3_7 = c_im(in[7]); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[4]) = (r1_0 - r1_1); c_im(out[4]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[5]) = (r1_2 - tmpr); c_im(out[5]) = (i1_2 - tmpi); c_re(out[2]) = (r1_4 + i1_5); c_im(out[2]) = (i1_4 - r1_5); c_re(out[6]) = (r1_4 - i1_5); c_im(out[6]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 - tmpi); c_re(out[7]) = (r1_6 - tmpr); c_im(out[7]) = (i1_6 + tmpi); } } void fft_twiddle_8(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_8(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_8(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_8_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_8_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_8(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_8(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_8(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_8_seq(a, ab, in, out, m); fft_unshuffle_8_seq(ab, b, in, out, m); } } void fft_base_16(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(in[0]); i4_0 = c_im(in[0]); r4_8 = c_re(in[8]); i4_8 = c_im(in[8]); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; r4_4 = c_re(in[4]); i4_4 = c_im(in[4]); r4_12 = c_re(in[12]); i4_12 = c_im(in[12]); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; r4_2 = c_re(in[2]); i4_2 = c_im(in[2]); r4_10 = c_re(in[10]); i4_10 = c_im(in[10]); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; r4_6 = c_re(in[6]); i4_6 = c_im(in[6]); r4_14 = c_re(in[14]); i4_14 = c_im(in[14]); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; r4_1 = c_re(in[1]); i4_1 = c_im(in[1]); r4_9 = c_re(in[9]); i4_9 = c_im(in[9]); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; r4_5 = c_re(in[5]); i4_5 = c_im(in[5]); r4_13 = c_re(in[13]); i4_13 = c_im(in[13]); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; r4_3 = c_re(in[3]); i4_3 = c_im(in[3]); r4_11 = c_re(in[11]); i4_11 = c_im(in[11]); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; r4_7 = c_re(in[7]); i4_7 = c_im(in[7]); r4_15 = c_re(in[15]); i4_15 = c_im(in[15]); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[8]) = (r1_0 - r1_1); c_im(out[8]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[9]) = (r1_2 - tmpr); c_im(out[9]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[10]) = (r1_4 - tmpr); c_im(out[10]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[11]) = (r1_6 - tmpr); c_im(out[11]) = (i1_6 - tmpi); c_re(out[4]) = (r1_8 + i1_9); c_im(out[4]) = (i1_8 - r1_9); c_re(out[12]) = (r1_8 - i1_9); c_im(out[12]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 - tmpi); c_re(out[13]) = (r1_10 - tmpr); c_im(out[13]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 - tmpi); c_re(out[14]) = (r1_12 - tmpr); c_im(out[14]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 - tmpi); c_re(out[15]) = (r1_14 - tmpr); c_im(out[15]) = (i1_14 + tmpi); } } void fft_twiddle_16(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_16(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_16(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_16_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_16_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_16(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_16(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_16(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_16_seq(a, ab, in, out, m); fft_unshuffle_16_seq(ab, b, in, out, m); } } void fft_base_32(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(in[0]); i5_0 = c_im(in[0]); r5_16 = c_re(in[16]); i5_16 = c_im(in[16]); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; r5_8 = c_re(in[8]); i5_8 = c_im(in[8]); r5_24 = c_re(in[24]); i5_24 = c_im(in[24]); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; r5_4 = c_re(in[4]); i5_4 = c_im(in[4]); r5_20 = c_re(in[20]); i5_20 = c_im(in[20]); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; r5_12 = c_re(in[12]); i5_12 = c_im(in[12]); r5_28 = c_re(in[28]); i5_28 = c_im(in[28]); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; r5_2 = c_re(in[2]); i5_2 = c_im(in[2]); r5_18 = c_re(in[18]); i5_18 = c_im(in[18]); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; r5_10 = c_re(in[10]); i5_10 = c_im(in[10]); r5_26 = c_re(in[26]); i5_26 = c_im(in[26]); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; r5_6 = c_re(in[6]); i5_6 = c_im(in[6]); r5_22 = c_re(in[22]); i5_22 = c_im(in[22]); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; r5_14 = c_re(in[14]); i5_14 = c_im(in[14]); r5_30 = c_re(in[30]); i5_30 = c_im(in[30]); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; r5_1 = c_re(in[1]); i5_1 = c_im(in[1]); r5_17 = c_re(in[17]); i5_17 = c_im(in[17]); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; r5_9 = c_re(in[9]); i5_9 = c_im(in[9]); r5_25 = c_re(in[25]); i5_25 = c_im(in[25]); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; r5_5 = c_re(in[5]); i5_5 = c_im(in[5]); r5_21 = c_re(in[21]); i5_21 = c_im(in[21]); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; r5_13 = c_re(in[13]); i5_13 = c_im(in[13]); r5_29 = c_re(in[29]); i5_29 = c_im(in[29]); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; r5_3 = c_re(in[3]); i5_3 = c_im(in[3]); r5_19 = c_re(in[19]); i5_19 = c_im(in[19]); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; r5_11 = c_re(in[11]); i5_11 = c_im(in[11]); r5_27 = c_re(in[27]); i5_27 = c_im(in[27]); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; r5_7 = c_re(in[7]); i5_7 = c_im(in[7]); r5_23 = c_re(in[23]); i5_23 = c_im(in[23]); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; r5_15 = c_re(in[15]); i5_15 = c_im(in[15]); r5_31 = c_re(in[31]); i5_31 = c_im(in[31]); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[16]) = (r1_0 - r1_1); c_im(out[16]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[17]) = (r1_2 - tmpr); c_im(out[17]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[18]) = (r1_4 - tmpr); c_im(out[18]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[19]) = (r1_6 - tmpr); c_im(out[19]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(out[4]) = (r1_8 + tmpr); c_im(out[4]) = (i1_8 + tmpi); c_re(out[20]) = (r1_8 - tmpr); c_im(out[20]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 + tmpi); c_re(out[21]) = (r1_10 - tmpr); c_im(out[21]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 + tmpi); c_re(out[22]) = (r1_12 - tmpr); c_im(out[22]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 + tmpi); c_re(out[23]) = (r1_14 - tmpr); c_im(out[23]) = (i1_14 - tmpi); c_re(out[8]) = (r1_16 + i1_17); c_im(out[8]) = (i1_16 - r1_17); c_re(out[24]) = (r1_16 - i1_17); c_im(out[24]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(out[9]) = (r1_18 + tmpr); c_im(out[9]) = (i1_18 - tmpi); c_re(out[25]) = (r1_18 - tmpr); c_im(out[25]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(out[10]) = (r1_20 + tmpr); c_im(out[10]) = (i1_20 - tmpi); c_re(out[26]) = (r1_20 - tmpr); c_im(out[26]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(out[11]) = (r1_22 + tmpr); c_im(out[11]) = (i1_22 - tmpi); c_re(out[27]) = (r1_22 - tmpr); c_im(out[27]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(out[12]) = (r1_24 + tmpr); c_im(out[12]) = (i1_24 - tmpi); c_re(out[28]) = (r1_24 - tmpr); c_im(out[28]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(out[13]) = (r1_26 + tmpr); c_im(out[13]) = (i1_26 - tmpi); c_re(out[29]) = (r1_26 - tmpr); c_im(out[29]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(out[14]) = (r1_28 + tmpr); c_im(out[14]) = (i1_28 - tmpi); c_re(out[30]) = (r1_28 - tmpr); c_im(out[30]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(out[15]) = (r1_30 + tmpr); c_im(out[15]) = (i1_30 - tmpi); c_re(out[31]) = (r1_30 - tmpr); c_im(out[31]) = (i1_30 + tmpi); } } void fft_twiddle_32(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_32(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_32(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait ; } } void fft_twiddle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_32_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_32_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_32(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_32(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_32(ab, b, in, out, m); #pragma omp taskwait ; } } void fft_unshuffle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_32_seq(a, ab, in, out, m); fft_unshuffle_32_seq(ab, b, in, out, m); } } /* end of machine-generated code */ /* * Recursive complex FFT on the n complex components of the array in: * basic Cooley-Tukey algorithm, with some improvements for * n power of two. The result is placed in the array out. n is arbitrary. * The algorithm runs in time O(n*(r1 + ... + rk)) where r1, ..., rk * are prime numbers, and r1 * r2 * ... * rk = n. * * n: size of the input * in: pointer to input * out: pointer to output * factors: list of factors of n, precomputed * W: twiddle factors * nW: size of W, that is, size of the original transform * */ void fft_aux(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) { #pragma omp task untied fft_unshuffle_32(0, m, in, out, m); } else if (r == 16) { #pragma omp task untied fft_unshuffle_16(0, m, in, out, m); } else if (r == 8) { #pragma omp task untied fft_unshuffle_8(0, m, in, out, m); } else if (r == 4) { #pragma omp task untied fft_unshuffle_4(0, m, in, out, m); } else if (r == 2) { #pragma omp task untied fft_unshuffle_2(0, m, in, out, m); } else unshuffle(0, m, in, out, r, m); #pragma omp taskwait ; for (k = 0; k < n; k += m) { #pragma omp task untied firstprivate(k) fft_aux(m, out + k, in + k, factors + 1, W, nW); } #pragma omp taskwait ; } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) { #pragma omp task untied fft_twiddle_2(0, m, in, out, W, nW, nW / n, m); } else if (r == 4) { #pragma omp task untied fft_twiddle_4(0, m, in, out, W, nW, nW / n, m); } else if (r == 8) { #pragma omp task untied fft_twiddle_8(0, m, in, out, W, nW, nW / n, m); } else if (r == 16) { #pragma omp task untied fft_twiddle_16(0, m, in, out, W, nW, nW / n, m); } else if (r == 32) { #pragma omp task untied fft_twiddle_32(0, m, in, out, W, nW, nW / n, m); } else { #pragma omp task untied fft_twiddle_gen(0, m, in, out, W, nW, nW / n, r, m); } #pragma omp taskwait ; return; } void fft_aux_seq(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) fft_unshuffle_32_seq(0, m, in, out, m); else if (r == 16) fft_unshuffle_16_seq(0, m, in, out, m); else if (r == 8) fft_unshuffle_8_seq(0, m, in, out, m); else if (r == 4) fft_unshuffle_4_seq(0, m, in, out, m); else if (r == 2) fft_unshuffle_2_seq(0, m, in, out, m); else unshuffle_seq(0, m, in, out, r, m); for (k = 0; k < n; k += m) { fft_aux_seq(m, out + k, in + k, factors + 1, W, nW); } } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) fft_twiddle_2_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 4) fft_twiddle_4_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 8) fft_twiddle_8_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 16) fft_twiddle_16_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 32) fft_twiddle_32_seq(0, m, in, out, W, nW, nW / n, m); else fft_twiddle_gen_seq(0, m, in, out, W, nW, nW / n, r, m); return; } /* * user interface for fft_aux */ void fft(int n, COMPLEX * in, COMPLEX * out) { int *factors = (int *)malloc(40 * sizeof(int)); // int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; bots_message("Computing coefficients "); const unsigned long long full_program_start = current_time_ns(); { W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); #pragma omp parallel { #pragma omp single { #pragma omp task untied { compute_w_coefficients(n, 0, n / 2, W); } } } bots_message(" completed!\n"); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); bots_message("Computing FFT "); #pragma omp parallel { #pragma omp single { #pragma omp task untied { fft_aux(n, in, out, factors, W, n); } } } free(W); } ; const unsigned long long full_program_end = current_time_ns(); printf("full_program %llu ns\n", full_program_end - full_program_start); bots_message(" completed!\n"); return; } void fft_seq(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); compute_w_coefficients_seq(n, 0, n / 2, W); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fft_aux_seq(n, in, out, factors, W, n); free(W); return; } int test_correctness(int n, COMPLEX *out1, COMPLEX *out2) { int i; double a,d,error = 0.0; for (i = 0; i < n; ++i) { a = sqrt((c_re(out1[i]) - c_re(out2[i])) * (c_re(out1[i]) - c_re(out2[i])) + (c_im(out1[i]) - c_im(out2[i])) * (c_im(out1[i]) - c_im(out2[i]))); d = sqrt(c_re(out2[i]) * c_re(out2[i]) + c_im(out2[i]) * c_im(out2[i])); if (d < -1.0e-10 || d > 1.0e-10) a /= d; if (a > error) error = a; } bots_message("relative error=%e\n", error); if (error > 1e-3) return BOTS_RESULT_UNSUCCESSFUL; else return BOTS_RESULT_SUCCESSFUL; }
BKTree.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SPTAG_COMMON_BKTREE_H_ #define _SPTAG_COMMON_BKTREE_H_ #include <iostream> #include <stack> #include <string> #include <vector> #include "../VectorIndex.h" #include "CommonUtils.h" #include "QueryResultSet.h" #include "WorkSpace.h" #pragma warning(disable:4996) // 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. namespace SPTAG { namespace COMMON { // node type for storing BKT struct BKTNode { int centerid; int childStart; int childEnd; BKTNode(int cid = -1) : centerid(cid), childStart(-1), childEnd(-1) {} }; template <typename T> struct KmeansArgs { int _K; int _D; int _T; T* centers; int* counts; float* newCenters; int* newCounts; char* label; int* clusterIdx; float* clusterDist; T* newTCenters; KmeansArgs(int k, int dim, int datasize, int threadnum) : _K(k), _D(dim), _T(threadnum) { centers = new T[k * dim]; counts = new int[k]; newCenters = new float[threadnum * k * dim]; newCounts = new int[threadnum * k]; label = new char[datasize]; clusterIdx = new int[threadnum * k]; clusterDist = new float[threadnum * k]; newTCenters = new T[k * dim]; } ~KmeansArgs() { delete[] centers; delete[] counts; delete[] newCenters; delete[] newCounts; delete[] label; delete[] clusterIdx; delete[] clusterDist; delete[] newTCenters; } inline void ClearCounts() { memset(newCounts, 0, sizeof(int) * _T * _K); } inline void ClearCenters() { memset(newCenters, 0, sizeof(float) * _T * _K * _D); } inline void ClearDists(float dist) { for (int i = 0; i < _T * _K; i++) { clusterIdx[i] = -1; clusterDist[i] = dist; } } void Shuffle(std::vector<int>& indices, int first, int last) { int* pos = new int[_K]; pos[0] = first; for (int k = 1; k < _K; k++) pos[k] = pos[k - 1] + newCounts[k - 1]; for (int k = 0; k < _K; k++) { if (newCounts[k] == 0) continue; int i = pos[k]; while (newCounts[k] > 0) { int swapid = pos[(int)(label[i])] + newCounts[(int)(label[i])] - 1; newCounts[(int)(label[i])]--; std::swap(indices[i], indices[swapid]); std::swap(label[i], label[swapid]); } while (indices[i] != clusterIdx[k]) i++; std::swap(indices[i], indices[pos[k] + counts[k] - 1]); } delete[] pos; } }; class BKTree { public: BKTree(): m_iTreeNumber(1), m_iBKTKmeansK(32), m_iBKTLeafSize(8), m_iSamples(1000) {} BKTree(BKTree& other): m_iTreeNumber(other.m_iTreeNumber), m_iBKTKmeansK(other.m_iBKTKmeansK), m_iBKTLeafSize(other.m_iBKTLeafSize), m_iSamples(other.m_iSamples) {} ~BKTree() {} inline const BKTNode& operator[](int index) const { return m_pTreeRoots[index]; } inline BKTNode& operator[](int index) { return m_pTreeRoots[index]; } inline int size() const { return (int)m_pTreeRoots.size(); } inline const std::unordered_map<int, int>& GetSampleMap() const { return m_pSampleCenterMap; } template <typename T> void BuildTrees(VectorIndex* index, std::vector<int>* indices = nullptr) { struct BKTStackItem { int index, first, last; BKTStackItem(int index_, int first_, int last_) : index(index_), first(first_), last(last_) {} }; std::stack<BKTStackItem> ss; std::vector<int> localindices; if (indices == nullptr) { localindices.resize(index->GetNumSamples()); for (int i = 0; i < index->GetNumSamples(); i++) localindices[i] = i; } else { localindices.assign(indices->begin(), indices->end()); } KmeansArgs<T> args(m_iBKTKmeansK, index->GetFeatureDim(), (int)localindices.size(), omp_get_num_threads()); m_pSampleCenterMap.clear(); for (char i = 0; i < m_iTreeNumber; i++) { std::random_shuffle(localindices.begin(), localindices.end()); m_pTreeStart.push_back((int)m_pTreeRoots.size()); m_pTreeRoots.push_back(BKTNode((int)localindices.size())); std::cout << "Start to build BKTree " << i + 1 << std::endl; ss.push(BKTStackItem(m_pTreeStart[i], 0, (int)localindices.size())); while (!ss.empty()) { BKTStackItem item = ss.top(); ss.pop(); int newBKTid = (int)m_pTreeRoots.size(); m_pTreeRoots[item.index].childStart = newBKTid; if (item.last - item.first <= m_iBKTLeafSize) { for (int j = item.first; j < item.last; j++) { m_pTreeRoots.push_back(BKTNode(localindices[j])); } } else { // clustering the data into BKTKmeansK clusters int numClusters = KmeansClustering(index, localindices, item.first, item.last, args); if (numClusters <= 1) { int end = min(item.last + 1, (int)localindices.size()); std::sort(localindices.begin() + item.first, localindices.begin() + end); m_pTreeRoots[item.index].centerid = localindices[item.first]; m_pTreeRoots[item.index].childStart = -m_pTreeRoots[item.index].childStart; for (int j = item.first + 1; j < end; j++) { m_pTreeRoots.push_back(BKTNode(localindices[j])); m_pSampleCenterMap[localindices[j]] = m_pTreeRoots[item.index].centerid; } m_pSampleCenterMap[-1 - m_pTreeRoots[item.index].centerid] = item.index; } else { for (int k = 0; k < m_iBKTKmeansK; k++) { if (args.counts[k] == 0) continue; m_pTreeRoots.push_back(BKTNode(localindices[item.first + args.counts[k] - 1])); if (args.counts[k] > 1) ss.push(BKTStackItem(newBKTid++, item.first, item.first + args.counts[k] - 1)); item.first += args.counts[k]; } } } m_pTreeRoots[item.index].childEnd = (int)m_pTreeRoots.size(); } std::cout << i + 1 << " BKTree built, " << m_pTreeRoots.size() - m_pTreeStart[i] << " " << localindices.size() << std::endl; } } bool SaveTrees(std::string sTreeFileName) const { std::cout << "Save BKT to " << sTreeFileName << std::endl; FILE *fp = fopen(sTreeFileName.c_str(), "wb"); if (fp == NULL) return false; fwrite(&m_iTreeNumber, sizeof(int), 1, fp); fwrite(m_pTreeStart.data(), sizeof(int), m_iTreeNumber, fp); int treeNodeSize = (int)m_pTreeRoots.size(); fwrite(&treeNodeSize, sizeof(int), 1, fp); fwrite(m_pTreeRoots.data(), sizeof(BKTNode), treeNodeSize, fp); fclose(fp); std::cout << "Save BKT (" << m_iTreeNumber << "," << treeNodeSize << ") Finish!" << std::endl; return true; } bool LoadTrees(char* pBKTMemFile) { m_iTreeNumber = *((int*)pBKTMemFile); pBKTMemFile += sizeof(int); m_pTreeStart.resize(m_iTreeNumber); memcpy(m_pTreeStart.data(), pBKTMemFile, sizeof(int) * m_iTreeNumber); pBKTMemFile += sizeof(int)*m_iTreeNumber; int treeNodeSize = *((int*)pBKTMemFile); pBKTMemFile += sizeof(int); m_pTreeRoots.resize(treeNodeSize); memcpy(m_pTreeRoots.data(), pBKTMemFile, sizeof(BKTNode) * treeNodeSize); return true; } bool LoadTrees(std::string sTreeFileName) { std::cout << "Load BKT From " << sTreeFileName << std::endl; FILE *fp = fopen(sTreeFileName.c_str(), "rb"); if (fp == NULL) return false; fread(&m_iTreeNumber, sizeof(int), 1, fp); m_pTreeStart.resize(m_iTreeNumber); fread(m_pTreeStart.data(), sizeof(int), m_iTreeNumber, fp); int treeNodeSize; fread(&treeNodeSize, sizeof(int), 1, fp); m_pTreeRoots.resize(treeNodeSize); fread(m_pTreeRoots.data(), sizeof(BKTNode), treeNodeSize, fp); fclose(fp); std::cout << "Load BKT (" << m_iTreeNumber << "," << treeNodeSize << ") Finish!" << std::endl; return true; } template <typename T> void InitSearchTrees(const VectorIndex* p_index, const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const { for (char i = 0; i < m_iTreeNumber; i++) { const BKTNode& node = m_pTreeRoots[m_pTreeStart[i]]; if (node.childStart < 0) { p_space.m_SPTQueue.insert(COMMON::HeapCell(m_pTreeStart[i], p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(node.centerid)))); } else { for (int begin = node.childStart; begin < node.childEnd; begin++) { int index = m_pTreeRoots[begin].centerid; p_space.m_SPTQueue.insert(COMMON::HeapCell(begin, p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(index)))); } } } } template <typename T> void SearchTrees(const VectorIndex* p_index, const COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space, const int p_limits) const { do { COMMON::HeapCell bcell = p_space.m_SPTQueue.pop(); const BKTNode& tnode = m_pTreeRoots[bcell.node]; if (tnode.childStart < 0) { if (!p_space.CheckAndSet(tnode.centerid)) { p_space.m_iNumberOfCheckedLeaves++; p_space.m_NGQueue.insert(COMMON::HeapCell(tnode.centerid, bcell.distance)); } if (p_space.m_iNumberOfCheckedLeaves >= p_limits) break; } else { if (!p_space.CheckAndSet(tnode.centerid)) { p_space.m_NGQueue.insert(COMMON::HeapCell(tnode.centerid, bcell.distance)); } for (int begin = tnode.childStart; begin < tnode.childEnd; begin++) { int index = m_pTreeRoots[begin].centerid; p_space.m_SPTQueue.insert(COMMON::HeapCell(begin, p_index->ComputeDistance((const void*)p_query.GetTarget(), p_index->GetSample(index)))); } } } while (!p_space.m_SPTQueue.empty()); } private: template <typename T> float KmeansAssign(VectorIndex* p_index, std::vector<int>& indices, const int first, const int last, KmeansArgs<T>& args, const bool updateCenters) const { float currDist = 0; int threads = omp_get_num_threads(); float lambda = (updateCenters) ? COMMON::Utils::GetBase<T>() * COMMON::Utils::GetBase<T>() / (100.0f * (last - first)) : 0.0f; int subsize = (last - first - 1) / threads + 1; #pragma omp parallel for for (int tid = 0; tid < threads; tid++) { int istart = first + tid * subsize; int iend = min(first + (tid + 1) * subsize, last); int *inewCounts = args.newCounts + tid * m_iBKTKmeansK; float *inewCenters = args.newCenters + tid * m_iBKTKmeansK * p_index->GetFeatureDim(); int * iclusterIdx = args.clusterIdx + tid * m_iBKTKmeansK; float * iclusterDist = args.clusterDist + tid * m_iBKTKmeansK; float idist = 0; for (int i = istart; i < iend; i++) { int clusterid = 0; float smallestDist = MaxDist; for (int k = 0; k < m_iBKTKmeansK; k++) { float dist = p_index->ComputeDistance(p_index->GetSample(indices[i]), (const void*)(args.centers + k*p_index->GetFeatureDim())) + lambda*args.counts[k]; if (dist > -MaxDist && dist < smallestDist) { clusterid = k; smallestDist = dist; } } args.label[i] = clusterid; inewCounts[clusterid]++; idist += smallestDist; if (updateCenters) { const T* v = (const T*)p_index->GetSample(indices[i]); float* center = inewCenters + clusterid*p_index->GetFeatureDim(); for (int j = 0; j < p_index->GetFeatureDim(); j++) center[j] += v[j]; if (smallestDist > iclusterDist[clusterid]) { iclusterDist[clusterid] = smallestDist; iclusterIdx[clusterid] = indices[i]; } } else { if (smallestDist <= iclusterDist[clusterid]) { iclusterDist[clusterid] = smallestDist; iclusterIdx[clusterid] = indices[i]; } } } COMMON::Utils::atomic_float_add(&currDist, idist); } for (int i = 1; i < threads; i++) { for (int k = 0; k < m_iBKTKmeansK; k++) args.newCounts[k] += args.newCounts[i*m_iBKTKmeansK + k]; } if (updateCenters) { for (int i = 1; i < threads; i++) { float* currCenter = args.newCenters + i*m_iBKTKmeansK*p_index->GetFeatureDim(); for (int j = 0; j < m_iBKTKmeansK * p_index->GetFeatureDim(); j++) args.newCenters[j] += currCenter[j]; } int maxcluster = 0; for (int k = 1; k < m_iBKTKmeansK; k++) if (args.newCounts[maxcluster] < args.newCounts[k]) maxcluster = k; int maxid = maxcluster; for (int tid = 1; tid < threads; tid++) { if (args.clusterDist[maxid] < args.clusterDist[tid * m_iBKTKmeansK + maxcluster]) maxid = tid * m_iBKTKmeansK + maxcluster; } if (args.clusterIdx[maxid] < 0 || args.clusterIdx[maxid] >= p_index->GetNumSamples()) std::cout << "first:" << first << " last:" << last << " maxcluster:" << maxcluster << "(" << args.newCounts[maxcluster] << ") Error maxid:" << maxid << " dist:" << args.clusterDist[maxid] << std::endl; maxid = args.clusterIdx[maxid]; for (int k = 0; k < m_iBKTKmeansK; k++) { T* TCenter = args.newTCenters + k * p_index->GetFeatureDim(); if (args.newCounts[k] == 0) { //int nextid = Utils::rand_int(last, first); //while (args.label[nextid] != maxcluster) nextid = Utils::rand_int(last, first); int nextid = maxid; std::memcpy(TCenter, p_index->GetSample(nextid), sizeof(T)*p_index->GetFeatureDim()); } else { float* currCenters = args.newCenters + k * p_index->GetFeatureDim(); for (int j = 0; j < p_index->GetFeatureDim(); j++) currCenters[j] /= args.newCounts[k]; if (p_index->GetDistCalcMethod() == DistCalcMethod::Cosine) { COMMON::Utils::Normalize(currCenters, p_index->GetFeatureDim(), COMMON::Utils::GetBase<T>()); } for (int j = 0; j < p_index->GetFeatureDim(); j++) TCenter[j] = (T)(currCenters[j]); } } } else { for (int i = 1; i < threads; i++) { for (int k = 0; k < m_iBKTKmeansK; k++) { if (args.clusterIdx[i*m_iBKTKmeansK + k] != -1 && args.clusterDist[i*m_iBKTKmeansK + k] <= args.clusterDist[k]) { args.clusterDist[k] = args.clusterDist[i*m_iBKTKmeansK + k]; args.clusterIdx[k] = args.clusterIdx[i*m_iBKTKmeansK + k]; } } } } return currDist; } template <typename T> int KmeansClustering(VectorIndex* p_index, std::vector<int>& indices, const int first, const int last, KmeansArgs<T>& args) const { int iterLimit = 100; int batchEnd = min(first + m_iSamples, last); float currDiff, currDist, minClusterDist = MaxDist; for (int numKmeans = 0; numKmeans < 3; numKmeans++) { for (int k = 0; k < m_iBKTKmeansK; k++) { int randid = COMMON::Utils::rand_int(last, first); std::memcpy(args.centers + k*p_index->GetFeatureDim(), p_index->GetSample(indices[randid]), sizeof(T)*p_index->GetFeatureDim()); } args.ClearCounts(); currDist = KmeansAssign(p_index, indices, first, batchEnd, args, false); if (currDist < minClusterDist) { minClusterDist = currDist; memcpy(args.newTCenters, args.centers, sizeof(T)*m_iBKTKmeansK*p_index->GetFeatureDim()); memcpy(args.counts, args.newCounts, sizeof(int) * m_iBKTKmeansK); } } minClusterDist = MaxDist; int noImprovement = 0; for (int iter = 0; iter < iterLimit; iter++) { std::memcpy(args.centers, args.newTCenters, sizeof(T)*m_iBKTKmeansK*p_index->GetFeatureDim()); std::random_shuffle(indices.begin() + first, indices.begin() + last); args.ClearCenters(); args.ClearCounts(); args.ClearDists(-MaxDist); currDist = KmeansAssign(p_index, indices, first, batchEnd, args, true); memcpy(args.counts, args.newCounts, sizeof(int)*m_iBKTKmeansK); currDiff = 0; for (int k = 0; k < m_iBKTKmeansK; k++) { currDiff += p_index->ComputeDistance((const void*)(args.centers + k*p_index->GetFeatureDim()), (const void*)(args.newTCenters + k*p_index->GetFeatureDim())); } if (currDist < minClusterDist) { noImprovement = 0; minClusterDist = currDist; } else { noImprovement++; } if (currDiff < 1e-3 || noImprovement >= 5) break; } args.ClearCounts(); args.ClearDists(MaxDist); currDist = KmeansAssign(p_index, indices, first, last, args, false); memcpy(args.counts, args.newCounts, sizeof(int)*m_iBKTKmeansK); int numClusters = 0; for (int i = 0; i < m_iBKTKmeansK; i++) if (args.counts[i] > 0) numClusters++; if (numClusters <= 1) { //if (last - first > 1) std::cout << "large cluster:" << last - first << " dist:" << currDist << std::endl; return numClusters; } args.Shuffle(indices, first, last); return numClusters; } private: std::vector<int> m_pTreeStart; std::vector<BKTNode> m_pTreeRoots; std::unordered_map<int, int> m_pSampleCenterMap; public: int m_iTreeNumber, m_iBKTKmeansK, m_iBKTLeafSize, m_iSamples; }; } } #endif
utils.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include <fcntl.h> #include <algorithm> #include <cassert> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <string> #include <memory> #include <random> #include <set> #include <xmmintrin.h> #ifdef __APPLE__ #else #include <malloc.h> #endif #ifdef _WINDOWS #include <Windows.h> typedef HANDLE FileHandle; #else #include <unistd.h> typedef int FileHandle; #endif #include "logger.h" #include "cached_io.h" #include "common_includes.h" #include "windows_customizations.h" #ifdef EXEC_ENV_OLS #include "content_buf.h" #include "memory_mapped_files.h" #endif // taken from // https://github.com/Microsoft/BLAS-on-flash/blob/master/include/utils.h // round up X to the nearest multiple of Y #define ROUND_UP(X, Y) \ ((((uint64_t)(X) / (Y)) + ((uint64_t)(X) % (Y) != 0)) * (Y)) #define DIV_ROUND_UP(X, Y) (((uint64_t)(X) / (Y)) + ((uint64_t)(X) % (Y) != 0)) // round down X to the nearest multiple of Y #define ROUND_DOWN(X, Y) (((uint64_t)(X) / (Y)) * (Y)) // alignment tests #define IS_ALIGNED(X, Y) ((uint64_t)(X) % (uint64_t)(Y) == 0) #define IS_512_ALIGNED(X) IS_ALIGNED(X, 512) #define IS_4096_ALIGNED(X) IS_ALIGNED(X, 4096) typedef uint64_t _u64; typedef int64_t _s64; typedef uint32_t _u32; typedef int32_t _s32; typedef uint16_t _u16; typedef int16_t _s16; typedef uint8_t _u8; typedef int8_t _s8; namespace diskann { static const size_t MAX_SIZE_OF_STREAMBUF = 2LL * 1024 * 1024 * 1024; enum Metric { L2 = 0, INNER_PRODUCT = 1, FAST_L2 = 2, PQ = 3 }; inline void alloc_aligned(void** ptr, size_t size, size_t align) { *ptr = nullptr; assert(IS_ALIGNED(size, align)); #ifndef _WINDOWS *ptr = ::aligned_alloc(align, size); #else *ptr = ::_aligned_malloc(size, align); // note the swapped arguments! #endif assert(*ptr != nullptr); } inline void aligned_free(void* ptr) { // Gopal. Must have a check here if the pointer was actually allocated by // _alloc_aligned if (ptr == nullptr) { return; } #ifndef _WINDOWS free(ptr); #else ::_aligned_free(ptr); #endif } inline void GenRandom(std::mt19937& rng, unsigned* addr, unsigned size, unsigned N) { for (unsigned i = 0; i < size; ++i) { addr[i] = rng() % (N - size); } std::sort(addr, addr + size); for (unsigned i = 1; i < size; ++i) { if (addr[i] <= addr[i - 1]) { addr[i] = addr[i - 1] + 1; } } unsigned off = rng() % N; for (unsigned i = 0; i < size; ++i) { addr[i] = (addr[i] + off) % N; } } // get_bin_metadata functions START inline void get_bin_metadata_impl(std::basic_istream<char>& reader, size_t& nrows, size_t& ncols) { int nrows_32, ncols_32; reader.read((char*) &nrows_32, sizeof(int)); reader.read((char*) &ncols_32, sizeof(int)); nrows = nrows_32; ncols = ncols_32; } #ifdef EXEC_ENV_OLS inline void get_bin_metadata(MemoryMappedFiles& files, const std::string& bin_file, size_t& nrows, size_t& ncols) { diskann::cout << "Getting metadata for file: " << bin_file << std::endl; auto fc = files.getContent(bin_file); auto cb = ContentBuf((char*) fc._content, fc._size); std::basic_istream<char> reader(&cb); get_bin_metadata_impl(reader, nrows, ncols); } #endif inline void get_bin_metadata(const std::string& bin_file, size_t& nrows, size_t& ncols) { std::ifstream reader(bin_file.c_str(), std::ios::binary); get_bin_metadata_impl(reader, nrows, ncols); } // get_bin_metadata functions END template<typename T> inline std::string getValues(T* data, size_t num) { std::stringstream stream; stream << "["; for (size_t i = 0; i < num; i++) { stream << std::to_string(data[i]) << ","; } stream << "]" << std::endl; return stream.str(); } // load_bin functions START template<typename T> inline void load_bin_impl(std::basic_istream<char>& reader, size_t actual_file_size, T*& data, size_t& npts, size_t& dim) { int npts_i32, dim_i32; reader.read((char*) &npts_i32, sizeof(int)); reader.read((char*) &dim_i32, sizeof(int)); npts = (unsigned) npts_i32; dim = (unsigned) dim_i32; diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "..." << std::endl; size_t expected_actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t); if (actual_file_size != expected_actual_file_size) { std::stringstream stream; stream << "Error. File size mismatch. Actual size is " << actual_file_size << " while expected size is " << expected_actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T) << std::endl; diskann::cout << stream.str(); throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } data = new T[npts * dim]; reader.read((char*) data, npts * dim * sizeof(T)); // diskann::cout << "Last bytes: " // << getValues<T>(data + (npts - 2) * dim, dim); // diskann::cout << "Finished reading bin file." << std::endl; } #ifdef EXEC_ENV_OLS template<typename T> inline void load_bin(MemoryMappedFiles& files, const std::string& bin_file, T*& data, size_t& npts, size_t& dim) { diskann::cout << "Reading bin file " << bin_file.c_str() << " ..." << std::endl; auto fc = files.getContent(bin_file); uint32_t t_npts, t_dim; uint32_t* contentAsIntPtr = (uint32_t*) (fc._content); t_npts = *(contentAsIntPtr); t_dim = *(contentAsIntPtr + 1); npts = t_npts; dim = t_dim; auto actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t); if (actual_file_size != fc._size) { std::stringstream stream; stream << "Error. File size mismatch. Actual size is " << fc._size << " while expected size is " << actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T) << std::endl; diskann::cout << stream.str(); throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } data = (T*) ((char*) fc._content + 2 * sizeof(uint32_t)); // No need to copy! } #endif inline void wait_for_keystroke() { int a; std::cout << "Press any number to continue.." << std::endl; std::cin >> a; } template<typename T> inline void load_bin(const std::string& bin_file, T*& data, size_t& npts, size_t& dim) { // OLS //_u64 read_blk_size = 64 * 1024 * 1024; // cached_ifstream reader(bin_file, read_blk_size); // size_t actual_file_size = reader.get_file_size(); // END OLS diskann::cout << "Reading bin file " << bin_file.c_str() << " ..." << std::endl; std::ifstream reader(bin_file, std::ios::binary | std::ios::ate); uint64_t fsize = reader.tellg(); reader.seekg(0); load_bin_impl<T>(reader, fsize, data, npts, dim); } // load_bin functions END inline void load_truthset(const std::string& bin_file, uint32_t*& ids, float*& dists, size_t& npts, size_t& dim) { _u64 read_blk_size = 64 * 1024 * 1024; cached_ifstream reader(bin_file, read_blk_size); diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl; size_t actual_file_size = reader.get_file_size(); int npts_i32, dim_i32; reader.read((char*) &npts_i32, sizeof(int)); reader.read((char*) &dim_i32, sizeof(int)); npts = (unsigned) npts_i32; dim = (unsigned) dim_i32; diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "..." << std::endl; int truthset_type = -1; // 1 means truthset has ids and distances, 2 means // only ids, -1 is error size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t); if (actual_file_size == expected_file_size_with_dists) truthset_type = 1; size_t expected_file_size_just_ids = npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t); if (actual_file_size == expected_file_size_just_ids) truthset_type = 2; if (truthset_type == -1) { std::stringstream stream; stream << "Error. File size mismatch. File should have bin format, with " "npts followed by ngt followed by npts*ngt ids and optionally " "followed by npts*ngt distance values; actual size: " << actual_file_size << ", expected: " << expected_file_size_with_dists << " or " << expected_file_size_just_ids; diskann::cout << stream.str(); throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } ids = new uint32_t[npts * dim]; reader.read((char*) ids, npts * dim * sizeof(uint32_t)); if (truthset_type == 1) { dists = new float[npts * dim]; reader.read((char*) dists, npts * dim * sizeof(float)); } } inline void prune_truthset_for_range(const std::string& bin_file, float range, std::vector<std::vector<_u32>> &groundtruth, size_t& npts) { _u64 read_blk_size = 64 * 1024 * 1024; cached_ifstream reader(bin_file, read_blk_size); diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl; size_t actual_file_size = reader.get_file_size(); int npts_i32, dim_i32; reader.read((char*) &npts_i32, sizeof(int)); reader.read((char*) &dim_i32, sizeof(int)); npts = (unsigned) npts_i32; _u64 dim = (unsigned) dim_i32; _u32* ids; float* dists; diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << "..." << std::endl; int truthset_type = -1; // 1 means truthset has ids and distances, 2 means // only ids, -1 is error size_t expected_file_size_with_dists = 2 * npts * dim * sizeof(uint32_t) + 2 * sizeof(uint32_t); if (actual_file_size == expected_file_size_with_dists) truthset_type = 1; if (truthset_type == -1) { std::stringstream stream; stream << "Error. File size mismatch. File should have bin format, with " "npts followed by ngt followed by npts*ngt ids and optionally " "followed by npts*ngt distance values; actual size: " << actual_file_size << ", expected: " << expected_file_size_with_dists; diskann::cout << stream.str(); throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } ids = new uint32_t[npts * dim]; reader.read((char*) ids, npts * dim * sizeof(uint32_t)); if (truthset_type == 1) { dists = new float[npts * dim]; reader.read((char*) dists, npts * dim * sizeof(float)); } float min_dist = std::numeric_limits<float>::max(); float max_dist = 0; groundtruth.resize(npts); for (_u32 i = 0; i < npts; i++) { groundtruth[i].clear(); for (_u32 j = 0; j < dim; j++) { if (dists[i*dim + j] <= range) { groundtruth[i].emplace_back(ids[i*dim+j]); } min_dist = min_dist > dists[i*dim+j] ? dists[i*dim + j] : min_dist; max_dist = max_dist < dists[i*dim+j] ? dists[i*dim + j] : max_dist; } //std::cout<<groundtruth[i].size() << " " ; } std::cout<<"Min dist: " << min_dist <<", Max dist: "<< max_dist << std::endl; delete[] ids; delete[] dists; } inline void load_range_truthset(const std::string& bin_file, std::vector<std::vector<_u32>> &groundtruth, _u64 & gt_num) { _u64 read_blk_size = 64 * 1024 * 1024; cached_ifstream reader(bin_file, read_blk_size); diskann::cout << "Reading truthset file " << bin_file.c_str() << " ..." << std::endl; size_t actual_file_size = reader.get_file_size(); int npts_u32, total_u32; reader.read((char*) &npts_u32, sizeof(int)); reader.read((char*) &total_u32, sizeof(int)); gt_num = (_u64) npts_u32; _u64 total_res = (_u64) total_u32; diskann::cout << "Metadata: #pts = " << gt_num << ", #total_results = " << total_res << "..." << std::endl; size_t expected_file_size = 2*sizeof(_u32) + gt_num*sizeof(_u32) + total_res*sizeof(_u32); if (actual_file_size != expected_file_size) { std::stringstream stream; stream << "Error. File size mismatch in range truthset. actual size: " << actual_file_size << ", expected: " << expected_file_size; diskann::cout << stream.str(); throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } groundtruth.clear(); groundtruth.resize(gt_num); std::vector<_u32> gt_count(gt_num); reader.read((char*) gt_count.data(), sizeof(_u32)*gt_num); std::vector<_u32> gt_stats(gt_count); std::sort(gt_stats.begin(), gt_stats.end()); std::cout<<"GT count percentiles:" << std::endl; for (_u32 p = 0; p < 100; p += 5) std::cout << "percentile " << p << ": " << gt_stats[std::floor((p / 100.0) * gt_num)] << std::endl; std::cout << "percentile 100" << ": " << gt_stats[gt_num - 1] << std::endl; for (_u32 i = 0; i < gt_num; i++) { groundtruth[i].clear(); groundtruth[i].resize(gt_count[i]); if (gt_count[i]!=0) reader.read((char*) groundtruth[i].data(), sizeof(_u32)*gt_count[i]); // debugging code /* if (i < 10) { std::cout<<gt_count[i] <<" nbrs, ids: "; for (auto &x : groundtruth[i]) std::cout<<x <<" "; std::cout<<std::endl; } */ } } #ifdef EXEC_ENV_OLS template<typename T> inline void load_bin(MemoryMappedFiles& files, const std::string& bin_file, std::unique_ptr<T[]>& data, size_t& npts, size_t& dim) { T* ptr; load_bin<T>(files, bin_file, ptr, npts, dim); data.reset(ptr); } #endif template<typename T> inline void load_bin(const std::string& bin_file, std::unique_ptr<T[]>& data, size_t& npts, size_t& dim) { T* ptr; load_bin<T>(bin_file, ptr, npts, dim); data.reset(ptr); } template<typename T> inline void save_bin(const std::string& filename, T* data, size_t npts, size_t ndims) { std::ofstream writer(filename, std::ios::binary | std::ios::out); diskann::cout << "Writing bin: " << filename.c_str() << std::endl; int npts_i32 = (int) npts, ndims_i32 = (int) ndims; writer.write((char*) &npts_i32, sizeof(int)); writer.write((char*) &ndims_i32, sizeof(int)); diskann::cout << "bin: #pts = " << npts << ", #dims = " << ndims << ", size = " << npts * ndims * sizeof(T) + 2 * sizeof(int) << "B" << std::endl; // data = new T[npts_u64 * ndims_u64]; writer.write((char*) data, npts * ndims * sizeof(T)); writer.close(); diskann::cout << "Finished writing bin." << std::endl; } // load_aligned_bin functions START template<typename T> inline void load_aligned_bin_impl(std::basic_istream<char>& reader, size_t actual_file_size, T*& data, size_t& npts, size_t& dim, size_t& rounded_dim) { int npts_i32, dim_i32; reader.read((char*) &npts_i32, sizeof(int)); reader.read((char*) &dim_i32, sizeof(int)); npts = (unsigned) npts_i32; dim = (unsigned) dim_i32; //check file size size_t expected_actual_file_size = npts * dim * sizeof(T) + 2 * sizeof(uint32_t); if (actual_file_size != expected_actual_file_size) { std::stringstream stream; stream << "Error. File size mismatch. Actual size is " << actual_file_size << " while expected size is " << expected_actual_file_size << " npts = " << npts << " dim = " << dim << " size of <T>= " << sizeof(T) << std::endl; diskann::cout << stream.str() << std::endl; throw diskann::ANNException(stream.str(), -1, __FUNCSIG__, __FILE__, __LINE__); } rounded_dim = ROUND_UP(dim, 8); diskann::cout << "Metadata: #pts = " << npts << ", #dims = " << dim << ", aligned_dim = " << rounded_dim << "..." << std::flush; size_t allocSize = npts * rounded_dim * sizeof(T); diskann::cout << "allocating aligned memory, " << allocSize << " bytes..." << std::flush; alloc_aligned(((void**) &data), allocSize, 8 * sizeof(T)); diskann::cout << "done. Copying data..." << std::flush; for (size_t i = 0; i < npts; i++) { reader.read((char*) (data + i * rounded_dim), dim * sizeof(T)); memset(data + i * rounded_dim + dim, 0, (rounded_dim - dim) * sizeof(T));// eliminate the holes } diskann::cout << " done." << std::endl; } #ifdef EXEC_ENV_OLS template<typename T> inline void load_aligned_bin(MemoryMappedFiles& files, const std::string& bin_file, T*& data, size_t& npts, size_t& dim, size_t& rounded_dim) { diskann::cout << "Reading bin file " << bin_file << " ..." << std::flush; FileContent fc = files.getContent(bin_file); ContentBuf buf((char*) fc._content, fc._size); std::basic_istream<char> reader(&buf); size_t actual_file_size = fc._size; load_aligned_bin_impl(reader, actual_file_size, data, npts, dim, rounded_dim); } #endif template<typename T> inline void load_aligned_bin(const std::string& bin_file, T*& data, size_t& npts, size_t& dim, size_t& rounded_dim) { diskann::cout << "Reading bin file " << bin_file << " ..." << std::flush; // START OLS // _u64 read_blk_size = 64 * 1024 * 1024; // cached_ifstream reader(bin_file, read_blk_size); // size_t actual_file_size = reader.get_file_size(); // END OLS std::ifstream reader(bin_file, std::ios::binary | std::ios::ate); uint64_t fsize = reader.tellg(); reader.seekg(0); load_aligned_bin_impl(reader, fsize, data, npts, dim, rounded_dim); } template<typename InType, typename OutType> void convert_types(const InType* srcmat, OutType* destmat, size_t npts, size_t dim) { #pragma omp parallel for schedule(static, 65536) for (int64_t i = 0; i < (_s64) npts; i++) { for (uint64_t j = 0; j < dim; j++) { destmat[i * dim + j] = (OutType) srcmat[i * dim + j]; } } } // this function will take in_file of n*d dimensions and save the output as a // floating point matrix // with n*(d+1) dimensions. All vectors are scaled by a large value M so that // the norms are <=1 and the final coordinate is set so that the resulting // norm (in d+1 coordinates) is equal to 1 this is a classical transformation // from MIPS to L2 search from "On Symmetric and Asymmetric LSHs for Inner // Product Search" by Neyshabur and Srebro template<typename T> float prepare_base_for_inner_products(const std::string in_file, const std::string out_file) { std::cout << "Pre-processing base file by adding extra coordinate" << std::endl; std::ifstream in_reader(in_file.c_str(), std::ios::binary); std::ofstream out_writer(out_file.c_str(), std::ios::binary); _u64 npts, in_dims, out_dims; float max_norm = 0; _u32 npts32, dims32; in_reader.read((char*) &npts32, sizeof(uint32_t)); in_reader.read((char*) &dims32, sizeof(uint32_t)); npts = npts32; in_dims = dims32; out_dims = in_dims + 1; _u32 outdims32 = (_u32) out_dims; out_writer.write((char*) &npts32, sizeof(uint32_t)); out_writer.write((char*) &outdims32, sizeof(uint32_t)); size_t BLOCK_SIZE = 100000; size_t block_size = npts <= BLOCK_SIZE ? npts : BLOCK_SIZE; std::unique_ptr<T[]> in_block_data = std::make_unique<T[]>(block_size * in_dims); std::unique_ptr<float[]> out_block_data = std::make_unique<float[]>(block_size * out_dims); std::memset(out_block_data.get(), 0, sizeof(float) * block_size * out_dims); _u64 num_blocks = DIV_ROUND_UP(npts, block_size); std::vector<float> norms(npts, 0); for (_u64 b = 0; b < num_blocks; b++) { _u64 start_id = b * block_size; _u64 end_id = (b + 1) * block_size < npts ? (b + 1) * block_size : npts; _u64 block_pts = end_id - start_id; in_reader.read((char*) in_block_data.get(), block_pts * in_dims * sizeof(T)); for (_u64 p = 0; p < block_pts; p++) { for (_u64 j = 0; j < in_dims; j++) { norms[start_id + p] += in_block_data[p * in_dims + j] * in_block_data[p * in_dims + j]; } max_norm = max_norm > norms[start_id + p] ? max_norm : norms[start_id + p]; } } max_norm = std::sqrt(max_norm); in_reader.seekg(2 * sizeof(_u32), std::ios::beg); for (_u64 b = 0; b < num_blocks; b++) { _u64 start_id = b * block_size; _u64 end_id = (b + 1) * block_size < npts ? (b + 1) * block_size : npts; _u64 block_pts = end_id - start_id; in_reader.read((char*) in_block_data.get(), block_pts * in_dims * sizeof(T)); for (_u64 p = 0; p < block_pts; p++) { for (_u64 j = 0; j < in_dims; j++) { out_block_data[p * out_dims + j] = in_block_data[p * in_dims + j] / max_norm; } float res = 1 - (norms[start_id + p] / (max_norm * max_norm)); res = res <= 0 ? 0 : std::sqrt(res); out_block_data[p * out_dims + out_dims - 1] = res; } out_writer.write((char*) out_block_data.get(), block_pts * out_dims * sizeof(float)); } out_writer.close(); return max_norm; } // plain saves data as npts X ndims array into filename template<typename T> void save_Tvecs(const char* filename, T* data, size_t npts, size_t ndims) { std::string fname(filename); // create cached ofstream with 64MB cache cached_ofstream writer(fname, 64 * 1048576); unsigned dims_u32 = (unsigned) ndims; // start writing for (uint64_t i = 0; i < npts; i++) { // write dims in u32 writer.write((char*) &dims_u32, sizeof(unsigned)); // get cur point in data T* cur_pt = data + i * ndims; writer.write((char*) cur_pt, ndims * sizeof(T)); } } // NOTE :: good efficiency when total_vec_size is integral multiple of 64 inline void prefetch_vector(const char* vec, size_t vecsize) { size_t max_prefetch_size = (vecsize / 64) * 64; for (size_t d = 0; d < max_prefetch_size; d += 64) _mm_prefetch((const char*) vec + d, _MM_HINT_T0); } // NOTE :: good efficiency when total_vec_size is integral multiple of 64 inline void prefetch_vector_l2(const char* vec, size_t vecsize) { size_t max_prefetch_size = (vecsize / 64) * 64; for (size_t d = 0; d < max_prefetch_size; d += 64) _mm_prefetch((const char*) vec + d, _MM_HINT_T1); } }; // namespace diskann struct PivotContainer { PivotContainer() = default; PivotContainer(size_t pivo_id, float pivo_dist) : piv_id{pivo_id}, piv_dist{pivo_dist} { } bool operator<(const PivotContainer& p) const { return p.piv_dist < piv_dist; } bool operator>(const PivotContainer& p) const { return p.piv_dist > piv_dist; } size_t piv_id; float piv_dist; }; inline bool file_exists(const std::string& name) { struct stat buffer; auto val = stat(name.c_str(), &buffer); diskann::cout << " Stat(" << name.c_str() << ") returned: " << val << std::endl; return (val == 0); } inline _u64 get_file_size(const std::string& fname) { std::ifstream reader(fname, std::ios::binary | std::ios::ate); if (!reader.fail() && reader.is_open()) { _u64 end_pos = reader.tellg(); diskann::cout << " Tellg: " << reader.tellg() << " as u64: " << end_pos << std::endl; reader.close(); return end_pos; } else { diskann::cout << "Could not open file: " << fname << std::endl; return 0; } } inline bool validate_file_size(const std::string& name) { std::ifstream in(std::string(name), std::ios::binary); in.seekg(0, in.end); size_t actual_file_size = in.tellg(); in.seekg(0, in.beg); size_t expected_file_size; in.read((char*) &expected_file_size, sizeof(uint64_t)); if (actual_file_size != expected_file_size) { diskann::cout << "Error loading" << name << ". Expected " "size (metadata): " << expected_file_size << ", actual file size : " << actual_file_size << ". Exitting." << std::endl; in.close(); return false; } in.close(); return true; } #ifdef _WINDOWS #include <intrin.h> #include <Psapi.h> inline void printProcessMemory(const char* message) { PROCESS_MEMORY_COUNTERS counters; HANDLE h = GetCurrentProcess(); GetProcessMemoryInfo(h, &counters, sizeof(counters)); diskann::cout << message << " [Peaking Working Set size: " << counters.PeakWorkingSetSize * 1.0 / (1024 * 1024 * 1024) << "GB Working set size: " << counters.WorkingSetSize * 1.0 / (1024 * 1024 * 1024) << "GB Private bytes " << counters.PagefileUsage * 1.0 / (1024 * 1024 * 1024) << "GB]" << std::endl; } #else // need to check and change this inline bool avx2Supported() { return true; } inline void printProcessMemory(const char* message) { diskann::cout << message << std::endl; } #endif extern bool AvxSupportedCPU; extern bool Avx2SupportedCPU;
ast-dump-openmp-begin-declare-variant_13.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify -ast-dump %s | FileCheck %s // RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -verify -ast-dump %s -x c++| FileCheck %s // expected-no-diagnostics int also_before(void) { return 1; } #pragma omp begin declare variant match(user = {condition(1)}) int also_after(void) { return 0; } int also_before(void) { return 0; } #pragma omp end declare variant int also_after(void) { return 2; } int test() { // Should return 0. return also_after() + also_before(); } // CHECK: |-FunctionDecl [[ADDR_0:0x[a-z0-9]*]] <{{.*}}, line:7:1> line:5:5 used also_before 'int ({{.*}})' // CHECK-NEXT: | |-CompoundStmt [[ADDR_1:0x[a-z0-9]*]] <col:23, line:7:1> // CHECK-NEXT: | | `-ReturnStmt [[ADDR_2:0x[a-z0-9]*]] <line:6:3, col:10> // CHECK-NEXT: | | `-IntegerLiteral [[ADDR_3:0x[a-z0-9]*]] <col:10> 'int' 1 // CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_4:0x[a-z0-9]*]] <<invalid sloc>> Implicit user={condition(1)} // CHECK-NEXT: | `-DeclRefExpr [[ADDR_5:0x[a-z0-9]*]] <line:13:1> 'int ({{.*}})' {{.*}}Function [[ADDR_6:0x[a-z0-9]*]] 'also_before[user={condition(...)}]' 'int ({{.*}})' // CHECK-NEXT: |-FunctionDecl [[ADDR_7:0x[a-z0-9]*]] <line:10:1, col:20> col:5 implicit used also_after 'int ({{.*}})' // CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_8:0x[a-z0-9]*]] <<invalid sloc>> Implicit user={condition(1)} // CHECK-NEXT: | `-DeclRefExpr [[ADDR_9:0x[a-z0-9]*]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_10:0x[a-z0-9]*]] 'also_after[user={condition(...)}]' 'int ({{.*}})' // CHECK-NEXT: |-FunctionDecl [[ADDR_10]] <col:1, line:12:1> line:10:1 also_after[user={condition(...)}] 'int ({{.*}})' // CHECK-NEXT: | `-CompoundStmt [[ADDR_11:0x[a-z0-9]*]] <col:22, line:12:1> // CHECK-NEXT: | `-ReturnStmt [[ADDR_12:0x[a-z0-9]*]] <line:11:3, col:10> // CHECK-NEXT: | `-IntegerLiteral [[ADDR_13:0x[a-z0-9]*]] <col:10> 'int' 0 // CHECK-NEXT: |-FunctionDecl [[ADDR_6]] <line:13:1, line:15:1> line:13:1 also_before[user={condition(...)}] 'int ({{.*}})' // CHECK-NEXT: | `-CompoundStmt [[ADDR_14:0x[a-z0-9]*]] <col:23, line:15:1> // CHECK-NEXT: | `-ReturnStmt [[ADDR_15:0x[a-z0-9]*]] <line:14:3, col:10> // CHECK-NEXT: | `-IntegerLiteral [[ADDR_16:0x[a-z0-9]*]] <col:10> 'int' 0 // CHECK-NEXT: |-FunctionDecl [[ADDR_17:0x[a-z0-9]*]] prev [[ADDR_7]] <line:18:1, line:20:1> line:18:5 used also_after 'int ({{.*}})' // CHECK-NEXT: | |-CompoundStmt [[ADDR_18:0x[a-z0-9]*]] <col:22, line:20:1> // CHECK-NEXT: | | `-ReturnStmt [[ADDR_19:0x[a-z0-9]*]] <line:19:3, col:10> // CHECK-NEXT: | | `-IntegerLiteral [[ADDR_20:0x[a-z0-9]*]] <col:10> 'int' 2 // CHECK-NEXT: | `-OMPDeclareVariantAttr [[ADDR_21:0x[a-z0-9]*]] <<invalid sloc>> Inherited Implicit user={condition(1)} // CHECK-NEXT: | `-DeclRefExpr [[ADDR_9]] <line:10:1> 'int ({{.*}})' {{.*}}Function [[ADDR_10]] 'also_after[user={condition(...)}]' 'int ({{.*}})' // CHECK-NEXT: `-FunctionDecl [[ADDR_22:0x[a-z0-9]*]] <line:22:1, line:25:1> line:22:5 test 'int ({{.*}})' // CHECK-NEXT: `-CompoundStmt [[ADDR_23:0x[a-z0-9]*]] <col:12, line:25:1> // CHECK-NEXT: `-ReturnStmt [[ADDR_24:0x[a-z0-9]*]] <line:24:3, col:37> // CHECK-NEXT: `-BinaryOperator [[ADDR_25:0x[a-z0-9]*]] <col:10, col:37> 'int' '+' // CHECK-NEXT: |-PseudoObjectExpr [[ADDR_26:0x[a-z0-9]*]] <col:10, col:21> 'int' // CHECK-NEXT: | |-CallExpr [[ADDR_27:0x[a-z0-9]*]] <col:10, col:21> 'int' // CHECK-NEXT: | | `-ImplicitCastExpr [[ADDR_28:0x[a-z0-9]*]] <col:10> 'int (*)({{.*}})' <FunctionToPointerDecay> // CHECK-NEXT: | | `-DeclRefExpr [[ADDR_29:0x[a-z0-9]*]] <col:10> 'int ({{.*}})' {{.*}}Function [[ADDR_17]] 'also_after' 'int ({{.*}})' // CHECK-NEXT: | `-CallExpr [[ADDR_30:0x[a-z0-9]*]] <line:10:1, line:24:21> 'int' // CHECK-NEXT: | `-ImplicitCastExpr [[ADDR_31:0x[a-z0-9]*]] <line:10:1> 'int (*)({{.*}})' <FunctionToPointerDecay> // CHECK-NEXT: | `-DeclRefExpr [[ADDR_9]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_10]] 'also_after[user={condition(...)}]' 'int ({{.*}})' // CHECK-NEXT: `-PseudoObjectExpr [[ADDR_32:0x[a-z0-9]*]] <line:24:25, col:37> 'int' // CHECK-NEXT: |-CallExpr [[ADDR_33:0x[a-z0-9]*]] <col:25, col:37> 'int' // CHECK-NEXT: | `-ImplicitCastExpr [[ADDR_34:0x[a-z0-9]*]] <col:25> 'int (*)({{.*}})' <FunctionToPointerDecay> // CHECK-NEXT: | `-DeclRefExpr [[ADDR_35:0x[a-z0-9]*]] <col:25> 'int ({{.*}})' {{.*}}Function [[ADDR_0]] 'also_before' 'int ({{.*}})' // CHECK-NEXT: `-CallExpr [[ADDR_36:0x[a-z0-9]*]] <line:13:1, line:24:37> 'int' // CHECK-NEXT: `-ImplicitCastExpr [[ADDR_37:0x[a-z0-9]*]] <line:13:1> 'int (*)({{.*}})' <FunctionToPointerDecay> // CHECK-NEXT: `-DeclRefExpr [[ADDR_5]] <col:1> 'int ({{.*}})' {{.*}}Function [[ADDR_6]] 'also_before[user={condition(...)}]' 'int ({{.*}})'
mdpush3.c
/* C Library for Skeleton 3D Darwin OpenMP PIC Code */ /* written by Viktor K. Decyk, UCLA */ #include <stdlib.h> #include <stdio.h> #include <complex.h> #include <math.h> #include "mdpush3.h" /*--------------------------------------------------------------------*/ double ranorm() { /* this program calculates a random number y from a gaussian distribution with zero mean and unit variance, according to the method of mueller and box: y(k) = (-2*ln(x(k)))**1/2*sin(2*pi*x(k+1)) y(k+1) = (-2*ln(x(k)))**1/2*cos(2*pi*x(k+1)), where x is a random number uniformly distributed on (0,1). written for the ibm by viktor k. decyk, ucla local data */ static int r1 = 885098780, r2 = 1824280461; static int r4 = 1396483093, r5 = 55318673; static int iflg = 0; static double h1l = 65531.0, h1u = 32767.0, h2l = 65525.0; static double r0 = 0.0; int isc, i1; double ranorm, r3, asc, bsc, temp; if (iflg==1) { ranorm = r0; r0 = 0.0; iflg = 0; return ranorm; } isc = 65536; asc = (double) isc; bsc = asc*asc; i1 = r1 - (r1/isc)*isc; r3 = h1l*(double) r1 + asc*h1u*(double) i1; i1 = r3/bsc; r3 -= ((double) i1)*bsc; bsc = 0.5*bsc; i1 = r2/isc; isc = r2 - i1*isc; r0 = h1l*(double) r2 + asc*h1u*(double) isc; asc = 1.0/bsc; isc = r0*asc; r2 = r0 - ((double) isc)*bsc; r3 += (double) isc + 2.0*h1u*(double) i1; isc = r3*asc; r1 = r3 - ((double) isc)*bsc; temp = sqrt(-2.0*log((((double) r1) + ((double) r2)*asc)*asc)); isc = 65536; asc = (double) isc; bsc = asc*asc; i1 = r4 - (r4/isc)*isc; r3 = h2l*(double) r4 + asc*h1u*(double) i1; i1 = r3/bsc; r3 -= ((double) i1)*bsc; bsc = 0.5*bsc; i1 = r5/isc; isc = r5 - i1*isc; r0 = h2l*(double) r5 + asc*h1u*(double) isc; asc = 1.0/bsc; isc = r0*asc; r5 = r0 - ((double) isc)*bsc; r3 += (double) isc + 2.0*h1u*(double) i1; isc = r3*asc; r4 = r3 - ((double) isc)*bsc; r0 = 6.28318530717959*((((double) r4) + ((double) r5)*asc)*asc); ranorm = temp*sin(r0); r0 = temp*cos(r0); iflg = 1; return ranorm; } /*--------------------------------------------------------------------*/ void cdistr3(float part[], float vtx, float vty, float vtz, float vdx, float vdy, float vdz, int npx, int npy, int npz, int idimp, int nop, int nx, int ny, int nz, int ipbc) { /* for 3d code, this subroutine calculates initial particle co-ordinates and velocities with uniform density and maxwellian velocity with drift part[n][0] = position x of particle n part[n][1] = position y of particle n part[n][2] = position z of particle n part[n][3] = velocity vx of particle n part[n][4] = velocity vy of particle n part[n][5] = velocity vz of particle n vtx/vty/vtz = thermal velocity of electrons in x/y/z direction vdx/vdy/vdz = drift velocity of beam electrons in x/y/z direction npx/npy/npz = initial number of particles distributed in x/y/z direction idimp = size of phase space = 6 nop = number of particles nx/ny/nz = system length in x/y/z direction ipbc = particle boundary condition = (0,1,2,3) = (none,3d periodic,3d reflecting,mixed 2d reflecting/1d periodic) ranorm = gaussian random number with zero mean and unit variance local data */ int j, k, l, k1, l1, npxy, npxyz; float edgelx, edgely, edgelz, at1, at2, at3, at4, at5; float sum1, sum2, sum3; double dsum1, dsum2, dsum3; npxy = npx*npy; npxyz = npxy*npz; /* set boundary values */ edgelx = 0.0; edgely = 0.0; edgelz = 0.0; at1 = (float) nx/(float) npx; at2 = (float) ny/(float) npy; at3 = (float) nz/(float) npz; if (ipbc==2) { edgelx = 1.0; edgely = 1.0; edgelz = 1.0; at1 = (float) (nx-2)/(float) npx; at2 = (float) (ny-2)/(float) npy; at3 = (float) (nz-2)/(float) npz; } else if (ipbc==3) { edgelx = 1.0; edgely = 1.0; edgelz = 0.0; at1 = (float) (nx-2)/(float) npx; at2 = (float) (ny-2)/(float) npy; } /* uniform density profile */ for (l = 0; l < npz; l++) { l1 = idimp*npxy*l; at5 = edgelz + at3*(((float) l) + 0.5); for (k = 0; k < npy; k++) { k1 = idimp*npx*k + l1; at4 = edgely + at2*(((float) k) + 0.5); for (j = 0; j < npx; j++) { part[idimp*j+k1] = edgelx + at1*(((float) j) + 0.5); part[1+idimp*j+k1] = at4; part[2+idimp*j+k1] = at5; } } } /* maxwellian velocity distribution */ for (j = 0; j < npxyz; j++) { part[3+idimp*j] = vtx*ranorm(); part[4+idimp*j] = vty*ranorm(); part[5+idimp*j] = vtz*ranorm(); } /* add correct drift */ dsum1 = 0.0; dsum2 = 0.0; dsum3 = 0.0; for (j = 0; j < npxyz; j++) { dsum1 += part[3+idimp*j]; dsum2 += part[4+idimp*j]; dsum3 += part[5+idimp*j]; } sum1 = dsum1; sum2 = dsum2; sum3 = dsum3; at1 = 1.0/(float) npxyz; sum1 = at1*sum1 - vdx; sum2 = at1*sum2 - vdy; sum3 = at1*sum3 - vdz; for (j = 0; j < npxyz; j++) { part[3+idimp*j] -= sum1; part[4+idimp*j] -= sum2; part[5+idimp*j] -= sum3; } return; } /*--------------------------------------------------------------------*/ void cdblkp3l(float part[], int kpic[], int *nppmx, int idimp, int nop, int mx, int my, int mz, int mx1, int my1, int mxyz1, int *irc) { /* this subroutine finds the maximum number of particles in each tile of mx, my, mz to calculate size of segmented particle array ppart linear interpolation input: all except kpic, nppmx, output: kpic, nppmx part = input particle array part[n][0] = position x of particle n part[n][1] = position y of particle n part[n][2] = position z of particle n kpic = output number of particles per tile nppmx = return maximum number of particles in tile idimp = size of phase space = 6 nop = number of particles mx/my/mz = number of grids in sorting cell in x, y and z mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int j, k, n, m, l, mxy1, isum, ist, npx, ierr; ierr = 0; mxy1 = mx1*my1; /* clear counter array */ for (k = 0; k < mxyz1; k++) { kpic[k] = 0; } /* find how many particles in each tile */ for (j = 0; j < nop; j++) { n = part[idimp*j]; n = n/mx; m = part[1+idimp*j]; m = m/my; l = part[2+idimp*j]; l = l/mz; m = n + mx1*m + mxy1*l; if (m < mxyz1) { kpic[m] += 1; } else { ierr = ierr > (m - mxyz1 + 1) ? ierr : (m - mxyz1 + 1); } } /* find maximum */ isum = 0; npx = 0; for (k = 0; k < mxyz1; k++) { ist = kpic[k]; npx = npx > ist ? npx : ist; isum += ist; } *nppmx = npx; /* check for errors */ if (ierr > 0) { *irc = ierr; } else if (isum != nop) { *irc = -1; } return; } /*--------------------------------------------------------------------*/ void cppmovin3l(float part[], float ppart[], int kpic[], int nppmx, int idimp, int nop, int mx, int my, int mz, int mx1, int my1, int mxyz1, int *irc) { /* this subroutine sorts particles by x,y,z grid in tiles of mx, my, mz and copies to segmented array ppart linear interpolation input: all except ppart, kpic, output: ppart, kpic part/ppart = input/output particle arrays part[n][0] = position x of particle n part[n][1] = position y of particle n part[n][2] = position z of particle n ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppart[m][n][3] = velocity vx of particle n in tile m ppart[m][n][4] = velocity vy of particle n in tile m ppart[m][n][5] = velocity vz of particle n in tile m kpic = output number of particles per tile nppmx = maximum number of particles in tile idimp = size of phase space = 6 nop = number of particles mx/my/mz = number of grids in sorting cell in x, y and z mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int i, j, k, n, m, l, mxy1, ip, ierr; ierr = 0; mxy1 = mx1*my1; /* clear counter array */ for (k = 0; k < mxyz1; k++) { kpic[k] = 0; } /* find addresses of particles at each tile and reorder particles */ for (j = 0; j < nop; j++) { n = part[idimp*j]; n = n/mx; m = part[1+idimp*j]; m = m/my; l = part[2+idimp*j]; l = l/mz; m = n + mx1*m + mxy1*l; ip = kpic[m]; if (ip < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(ip+nppmx*m)] = part[i+idimp*j]; } } else { ierr = ierr > ip-nppmx+1 ? ierr : ip-nppmx+1; } kpic[m] = ip + 1; } if (ierr > 0) *irc = ierr; return; } /*--------------------------------------------------------------------*/ void cppcheck3l(float ppart[], int kpic[], int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int mx1, int my1, int mz1, int *irc) { /* this subroutine performs a sanity check to make sure particles sorted by x,y,z grid in tiles of mx, my, mz, are all within bounds. tiles are assumed to be arranged in 3D linear memory input: all except irc output: irc ppart[l][n][0] = position x of particle n in tile l ppart[l][n][1] = position y of particle n in tile l ppart[l][n][2] = position a of particle n in tile l kpic(l) = number of reordered output particles in tile l idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = number of grids in sorting cell in x/y/z mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mz1 = (system length in z direction - 1)/mz + 1 irc = particle error, returned only if error occurs, when irc > 0 local data */ int mxy1, mxyz1, noff, moff, loff, npp, j, k, l, nn, mm, ll, ist; float edgelx, edgely, edgelz, edgerx, edgery, edgerz, dx, dy, dz; mxy1 = mx1*my1; mxyz1 = mxy1*mz1; /* loop over tiles */ #pragma omp parallel for \ private(j,k,l,noff,moff,loff,npp,nn,mm,ll,ist,edgelx,edgely,edgelz, \ edgerx,edgery,edgerz,dx,dy,dz) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; ll = nz - loff; ll = mz < ll ? mz : ll; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; edgelz = loff; edgerz = loff + ll; /* loop over particles in tile */ for (j = 0; j < npp; j++) { dx = ppart[idimp*(j+nppmx*l)]; dy = ppart[1+idimp*(j+nppmx*l)]; dz = ppart[2+idimp*(j+nppmx*l)]; /* find particles going out of bounds */ ist = 0; if (dx < edgelx) ist = 1; if (dx >= edgerx) ist = 2; if (dy < edgely) ist += 3; if (dy >= edgery) ist += 6; if (dz < edgelz) ist += 9; if (dz >= edgerz) ist += 18; if (ist > 0) *irc = l + 1; } } return; } /*--------------------------------------------------------------------*/ void cgbppush3l(float ppart[], float fxyz[], float bxyz[], int kpic[], float qbm, float dt, float dtc, float *ek, int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1, int ipbc) { /* for 3d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with magnetic field. Using the Boris Mover. OpenMP version using guard cells data read in tiles particles stored segmented array 190 flops/particle, 1 divide, 54 loads, 6 stores input: all, output: ppart, ek velocity equations used are: vx(t+dt/2) = rot(1)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(2)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(3)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) vy(t+dt/2) = rot(4)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(5)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(6)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) vz(t+dt/2) = rot(7)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(8)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(9)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) where q/m is charge/mass, and the rotation matrix is given by: rot(1) = (1 - (om*dt/2)**2 + 2*(omx*dt/2)**2)/(1 + (om*dt/2)**2) rot(2) = 2*(omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(3) = 2*(-omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(4) = 2*(-omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(5) = (1 - (om*dt/2)**2 + 2*(omy*dt/2)**2)/(1 + (om*dt/2)**2) rot(6) = 2*(omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(7) = 2*(omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(8) = 2*(-omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(9) = (1 - (om*dt/2)**2 + 2*(omz*dt/2)**2)/(1 + (om*dt/2)**2) and om**2 = omx**2 + omy**2 + omz**2 the rotation matrix is determined by: omx = (q/m)*bx(x(t),y(t),z(t)), omy = (q/m)*by(x(t),y(t),z(t)), and omz = (q/m)*bz(x(t),y(t),z(t)). position equations used are: x(t+dt)=x(t) + vx(t+dt/2)*dt y(t+dt)=y(t) + vy(t+dt/2)*dt z(t+dt)=z(t) + vz(t+dt/2)*dt fx(x(t),y(t),z(t)), fy(x(t),y(t),z(t)), and fz(x(t),y(t),z(t)), bx(x(t),y(t),z(t)), by(x(t),y(t),z(t)), and bz(x(t),y(t),z(t)) are approximated by interpolation from the nearest grid points: fx(x,y,z) = (1-dz)*((1-dy)*((1-dx)*fx(n,m,l)+dx*fx(n+1,m,l)) + dy*((1-dx)*fx(n,m+1,l) + dx*fx(n+1,m+1,l))) + dz*((1-dy)*((1-dx)*fx(n,m,l+1)+dx*fx(n+1,m,l+1)) + dy*((1-dx)*fx(n,m+1,l+1) + dx*fx(n+1,m+1,l+1))) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l similarly for fy(x,y,z), fz(x,y,z), bx(x,y,z), by(x,y,z), bz(x,y,z) ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppart[m][n][3] = velocity vx of particle n in tile m ppart[m][n][4] = velocity vy of particle n in tile m ppart[m][n][5] = velocity vz of particle n in tile m fxyz[l][k][j][0] = x component of force/charge at grid (j,k,l) fxyz[l][k][j][1] = y component of force/charge at grid (j,k,l) fxyz[l][k][j][2] = z component of force/charge at grid (j,k,l) that is, convolution of electric field over particle shape bxyz[l][k][j][0] = x component of magnetic field at grid (j,k,l) bxyz[l][k][j][1] = y component of magnetic field at grid (j,k,l) bxyz[l][k][j][2] = z component of magnetic field at grid (j,k,l) that is, the convolution of magnetic field over particle shape kpic = number of particles per tile qbm = particle charge/mass ratio dt = time interval between successive force calculations dtc = time interval between successive co-ordinate calculations kinetic energy/mass at time t is also calculated, using ek = .5*sum((vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t))*dt)**2 + (vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t))*dt)**2 + .25*(vz(t+dt/2) + vz(t-dt/2))**2) idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 nzv = fourth dimension of field array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 ipbc = particle boundary condition = (0,1,2,3) = (none,3d periodic,3d reflecting,mixed 2d reflecting/1d periodic) local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, mxv, myv, mxyv, nxyv; float qtmh, edgelx, edgely, edgelz, edgerx, edgery, edgerz; float dxp, dyp, dzp, amx, amy, amz, dx, dy, dz, ox, oy, oz, dx1; float acx, acy, acz, omxt, omyt, omzt, omt, anorm; float rot1, rot2, rot3, rot4, rot5, rot6, rot7, rot8, rot9; float x, y, z; float sfxyz[3*MXV*MYV*MZV], sbxyz[3*MXV*MYV*MZV]; /* float sfxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sbxyz[3*(mx+1)*(my+1)*(mz+1)]; */ double sum1, sum2; /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; qtmh = 0.5f*qbm*dt; sum2 = 0.0; /* set boundary values */ edgelx = 0.0f; edgely = 0.0f; edgelz = 0.0f; edgerx = (float) nx; edgery = (float) ny; edgerz = (float) nz; if (ipbc==2) { edgelx = 1.0f; edgely = 1.0f; edgelz = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); edgerz = (float) (nz-1); } else if (ipbc==3) { edgelx = 1.0f; edgely = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); } /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,x,y,z,dxp,dyp,dzp, \ amx,amy,amz,dx1,dx,dy,dz,ox,oy,oz,acx,acy,acz,omxt,omyt,omzt,omt,anorm, \ rot1,rot2,rot3,rot4,rot5,rot6,rot7,rot8,rot9,sum1,sfxyz,sbxyz) \ reduction(+:sum2) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; ll = (mz < nz-loff ? mz : nz-loff) + 1; for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxyz[3*(i+mxv*j+mxyv*k)] = fxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[1+3*(i+mxv*j+mxyv*k)] = fxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[2+3*(i+mxv*j+mxyv*k)] = fxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sbxyz[3*(i+mxv*j+mxyv*k)] = bxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[1+3*(i+mxv*j+mxyv*k)] = bxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[2+3*(i+mxv*j+mxyv*k)] = bxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } sum1 = 0.0; /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = x - (float) nn; dyp = y - (float) mm; dzp = z - (float) ll; nm = 3*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = 1.0f - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* find electric field */ nn = nm; dx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; dy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; dz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = amz*(dx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = amz*(dy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = amz*(dz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; acy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; acz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = dx + dzp*(acx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = dy + dzp*(acy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = dz + dzp*(acz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); /* find magnetic field */ nn = nm; ox = amx*sbxyz[nn] + amy*sbxyz[nn+3]; oy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; oz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = amz*(ox + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = amz*(oy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = amz*(oz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sbxyz[nn] + amy*sbxyz[nn+3]; acy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; acz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = ox + dzp*(acx + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = oy + dzp*(acy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = oz + dzp*(acz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); /* calculate half impulse */ dx *= qtmh; dy *= qtmh; dz *= qtmh; /* half acceleration */ acx = ppart[3+idimp*(j+npoff)] + dx; acy = ppart[4+idimp*(j+npoff)] + dy; acz = ppart[5+idimp*(j+npoff)] + dz; /* time-centered kinetic energy */ sum1 += (acx*acx + acy*acy + acz*acz); /* calculate cyclotron frequency */ omxt = qtmh*ox; omyt = qtmh*oy; omzt = qtmh*oz; /* calculate rotation matrix */ omt = omxt*omxt + omyt*omyt + omzt*omzt; anorm = 2.0f/(1.0f + omt); omt = 0.5f*(1.0f - omt); rot4 = omxt*omyt; rot7 = omxt*omzt; rot8 = omyt*omzt; rot1 = omt + omxt*omxt; rot5 = omt + omyt*omyt; rot9 = omt + omzt*omzt; rot2 = omzt + rot4; rot4 -= omzt; rot3 = -omyt + rot7; rot7 += omyt; rot6 = omxt + rot8; rot8 -= omxt; /* new velocity */ dx += (rot1*acx + rot2*acy + rot3*acz)*anorm; dy += (rot4*acx + rot5*acy + rot6*acz)*anorm; dz += (rot7*acx + rot8*acy + rot9*acz)*anorm; ppart[3+idimp*(j+npoff)] = dx; ppart[4+idimp*(j+npoff)] = dy; ppart[5+idimp*(j+npoff)] = dz; /* new position */ dx = x + dx*dtc; dy = y + dy*dtc; dz = z + dz*dtc; /* reflecting boundary conditions */ if (ipbc==2) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; ppart[3+idimp*(j+npoff)] = -ppart[3+idimp*(j+npoff)]; } if ((dy < edgely) || (dy >= edgery)) { dy = y; ppart[4+idimp*(j+npoff)] = -ppart[4+idimp*(j+npoff)]; } if ((dz < edgelz) || (dz >= edgerz)) { dz = z; ppart[5+idimp*(j+npoff)] = -ppart[5+idimp*(j+npoff)]; } } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; ppart[3+idimp*(j+npoff)] = -ppart[3+idimp*(j+npoff)]; } if ((dy < edgely) || (dy >= edgery)) { dy = y; ppart[4+idimp*(j+npoff)] = -ppart[4+idimp*(j+npoff)]; } } /* set new position */ ppart[idimp*(j+npoff)] = dx; ppart[1+idimp*(j+npoff)] = dy; ppart[2+idimp*(j+npoff)] = dz; } sum2 += sum1; } /* normalize kinetic energy */ *ek += 0.5f*sum2; return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgbppushf3l(float ppart[], float fxyz[], float bxyz[], int kpic[], int ncl[], int ihole[], float qbm, float dt, float dtc, float *ek, int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1, int ntmax, int *irc) { /* for 3d code, this subroutine updates particle co-ordinates and velocities using leap-frog scheme in time and first-order linear interpolation in space, with magnetic field. Using the Boris Mover. also determines list of particles which are leaving this tile OpenMP version using guard cells data read in tiles particles stored segmented array 190 flops/particle, 1 divide, 54 loads, 6 stores input: all except ncl, ihole, irc, output: ppart, ncl, ihole, ek, irc velocity equations used are: vx(t+dt/2) = rot(1)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(2)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(3)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) vy(t+dt/2) = rot(4)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(5)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(6)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) vz(t+dt/2) = rot(7)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(8)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(9)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) where q/m is charge/mass, and the rotation matrix is given by: rot(1) = (1 - (om*dt/2)**2 + 2*(omx*dt/2)**2)/(1 + (om*dt/2)**2) rot(2) = 2*(omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(3) = 2*(-omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(4) = 2*(-omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(5) = (1 - (om*dt/2)**2 + 2*(omy*dt/2)**2)/(1 + (om*dt/2)**2) rot(6) = 2*(omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(7) = 2*(omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(8) = 2*(-omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(9) = (1 - (om*dt/2)**2 + 2*(omz*dt/2)**2)/(1 + (om*dt/2)**2) and om**2 = omx**2 + omy**2 + omz**2 the rotation matrix is determined by: omx = (q/m)*bx(x(t),y(t),z(t)), omy = (q/m)*by(x(t),y(t),z(t)), and omz = (q/m)*bz(x(t),y(t),z(t)). position equations used are: x(t+dt)=x(t) + vx(t+dt/2)*dt y(t+dt)=y(t) + vy(t+dt/2)*dt z(t+dt)=z(t) + vz(t+dt/2)*dt fx(x(t),y(t),z(t)), fy(x(t),y(t),z(t)), and fz(x(t),y(t),z(t)), bx(x(t),y(t),z(t)), by(x(t),y(t),z(t)), and bz(x(t),y(t),z(t)) are approximated by interpolation from the nearest grid points: fx(x,y,z) = (1-dz)*((1-dy)*((1-dx)*fx(n,m,l)+dx*fx(n+1,m,l)) + dy*((1-dx)*fx(n,m+1,l) + dx*fx(n+1,m+1,l))) + dz*((1-dy)*((1-dx)*fx(n,m,l+1)+dx*fx(n+1,m,l+1)) + dy*((1-dx)*fx(n,m+1,l+1) + dx*fx(n+1,m+1,l+1))) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l similarly for fy(x,y,z), fz(x,y,z), bx(x,y,z), by(x,y,z), bz(x,y,z) ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppart[m][n][3] = velocity vx of particle n in tile m ppart[m][n][4] = velocity vy of particle n in tile m ppart[m][n][5] = velocity vz of particle n in tile m fxyz[l][k][j][0] = x component of force/charge at grid (j,k,l) fxyz[l][k][j][1] = y component of force/charge at grid (j,k,l) fxyz[l][k][j][2] = z component of force/charge at grid (j,k,l) that is, convolution of electric field over particle shape bxyz[l][k][j][0] = x component of magnetic field at grid (j,k,l) bxyz[l][k][j][1] = y component of magnetic field at grid (j,k,l) bxyz[l][k][j][2] = z component of magnetic field at grid (j,k,l) that is, the convolution of magnetic field over particle shape kpic[l] = number of particles in tile l ncl[l][i] = number of particles going to destination i, tile l ihole[l][:][0] = location of hole in array left by departing particle ihole[l][:][1] = direction destination of particle leaving hole all for tile l ihole[l][0][0] = ih, number of holes left (error, if negative) qbm = particle charge/mass ratio dt = time interval between successive force calculations dtc = time interval between successive co-ordinate calculations kinetic energy/mass at time t is also calculated, using ek = .5*sum((vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t))*dt)**2 + (vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t))*dt)**2 + .25*(vz(t+dt/2) + vz(t-dt/2))**2) idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 nzv = fourth dimension of field array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 optimized version local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, ih, nh, nn, mm, ll, nm, mxv, myv, mxyv, nxyv; float anx, any, anz, edgelx, edgely, edgelz, edgerx, edgery, edgerz; float dxp, dyp, dzp, amx, amy, amz, dx, dy, dz, ox, oy, oz, dx1; float qtmh, acx, acy, acz, omxt, omyt, omzt, omt, anorm; float rot1, rot2, rot3, rot4, rot5, rot6, rot7, rot8, rot9; float x, y, z; float sfxyz[3*MXV*MYV*MZV], sbxyz[3*MXV*MYV*MZV]; /* float sfxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sbxyz[3*(mx+1)*(my+1)*(mz+1)]; */ double sum1, sum2; /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; qtmh = 0.5f*qbm*dt; anx = (float) nx; any = (float) ny; anz = (float) nz; sum2 = 0.0; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,ih,nh,x,y,z,dxp, \ dyp,dzp,amx,amy,amz,dx1,dx,dy,dz,ox,oy,oz,acx,acy,acz,omxt,omyt,omzt, \ omt,anorm,rot1,rot2,rot3,rot4,rot5,rot6,rot7,rot8,rot9,edgelx,edgely, \ edgelz,edgerx,edgery,edgerz,sum1,sfxyz,sbxyz) \ reduction(+:sum2) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; ll = nz - loff; ll = mz < ll ? mz : ll; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; edgelz = loff; edgerz = loff + ll; ih = 0; nh = 0; nn += 1; mm += 1; ll += 1; /* load local fields from global array */ for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxyz[3*(i+mxv*j+mxyv*k)] = fxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[1+3*(i+mxv*j+mxyv*k)] = fxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[2+3*(i+mxv*j+mxyv*k)] = fxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sbxyz[3*(i+mxv*j+mxyv*k)] = bxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[1+3*(i+mxv*j+mxyv*k)] = bxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[2+3*(i+mxv*j+mxyv*k)] = bxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } /* clear counters */ for (j = 0; j < 26; j++) { ncl[j+26*l] = 0; } sum1 = 0.0; /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = x - (float) nn; dyp = y - (float) mm; dzp = z - (float) ll; nm = 3*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = 1.0f - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* find electric field */ nn = nm; dx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; dy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; dz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = amz*(dx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = amz*(dy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = amz*(dz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; acy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; acz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = dx + dzp*(acx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = dy + dzp*(acy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = dz + dzp*(acz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); /* find magnetic field */ nn = nm; ox = amx*sbxyz[nn] + amy*sbxyz[nn+3]; oy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; oz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = amz*(ox + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = amz*(oy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = amz*(oz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sbxyz[nn] + amy*sbxyz[nn+3]; acy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; acz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = ox + dzp*(acx + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = oy + dzp*(acy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = oz + dzp*(acz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); /* calculate half impulse */ dx *= qtmh; dy *= qtmh; dz *= qtmh; /* half acceleration */ acx = ppart[3+idimp*(j+npoff)] + dx; acy = ppart[4+idimp*(j+npoff)] + dy; acz = ppart[5+idimp*(j+npoff)] + dz; /* time-centered kinetic energy */ sum1 += (acx*acx + acy*acy + acz*acz); /* calculate cyclotron frequency */ omxt = qtmh*ox; omyt = qtmh*oy; omzt = qtmh*oz; /* calculate rotation matrix */ omt = omxt*omxt + omyt*omyt + omzt*omzt; anorm = 2.0f/(1.0f + omt); omt = 0.5f*(1.0f - omt); rot4 = omxt*omyt; rot7 = omxt*omzt; rot8 = omyt*omzt; rot1 = omt + omxt*omxt; rot5 = omt + omyt*omyt; rot9 = omt + omzt*omzt; rot2 = omzt + rot4; rot4 -= omzt; rot3 = -omyt + rot7; rot7 += omyt; rot6 = omxt + rot8; rot8 -= omxt; /* new velocity */ dx += (rot1*acx + rot2*acy + rot3*acz)*anorm; dy += (rot4*acx + rot5*acy + rot6*acz)*anorm; dz += (rot7*acx + rot8*acy + rot9*acz)*anorm; ppart[3+idimp*(j+npoff)] = dx; ppart[4+idimp*(j+npoff)] = dy; ppart[5+idimp*(j+npoff)] = dz; /* new position */ dx = x + dx*dtc; dy = y + dy*dtc; dz = z + dz*dtc; /* find particles going out of bounds */ mm = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* mm = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) dx = dx - anx; mm = 2; } else if (dx < edgelx) { if (dx < 0.0f) { dx += anx; if (dx < anx) mm = 1; else dx = 0.0f; } else { mm = 1; } } if (dy >= edgery) { if (dy >= any) dy = dy - any; mm += 6; } else if (dy < edgely) { if (dy < 0.0f) { dy += any; if (dy < any) mm += 3; else dy = 0.0f; } else { mm += 3; } } if (dz >= edgerz) { if (dz >= anz) dz = dz - anz; mm += 18; } else if (dz < edgelz) { if (dz < 0.0f) { dz += anz; if (dz < anz) mm += 9; else dz = 0.0f; } else { mm += 9; } } /* set new position */ ppart[idimp*(j+npoff)] = dx; ppart[1+idimp*(j+npoff)] = dy; ppart[2+idimp*(j+npoff)] = dz; /* increment counters */ if (mm > 0) { ncl[mm+26*l-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*l)] = j + 1; ihole[1+2*(ih+(ntmax+1)*l)] = mm; } else { nh = 1; } } } sum2 += sum1; /* set error and end of file flag */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*l] = ih; } /* normalize kinetic energy */ *ek += 0.5f*sum2; return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgppost3l(float ppart[], float q[], int kpic[], float qm, int nppmx, int idimp, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1) { /* for 3d code, this subroutine calculates particle charge density using first-order linear interpolation, periodic boundaries OpenMP version using guard cells data deposited in tiles particles stored segmented array 33 flops/particle, 11 loads, 8 stores input: all, output: q charge density is approximated by values at the nearest grid points q(n,m,l)=qm*(1.-dx)*(1.-dy)*(1.-dz) q(n+1,m,l)=qm*dx*(1.-dy)*(1.-dz) q(n,m+1,l)=qm*(1.-dx)*dy*(1.-dz) q(n+1,m+1,l)=qm*dx*dy*(1.-dz) q(n,m,l+1)=qm*(1.-dx)*(1.-dy)*dz q(n+1,m,l+1)=qm*dx*(1.-dy)*dz q(n,m+1,l+1)=qm*(1.-dx)*dy*dz q(n+1,m+1,l+1)=qm*dx*dy*dz where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m q[l][k][j] = charge density at grid point j,k,l kpic = number of particles per tile qm = charge on particle, in units of e nppmx = maximum number of particles in tile idimp = size of phase space = 6 mx/my/mz = number of grids in sorting cell in x/y/z nxv = first dimension of charge array, must be >= nx+1 nyv = second dimension of charge array, must be >= ny+1 nzv = third dimension of charge array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, lm, mxv, myv, mxyv, nxyv; float x, y, z, dxp, dyp, dzp, amx, amy, amz, dx1; float sq[MXV*MYV*MZV]; /* float sq[(mx+1)*(my+1)*(mz+1)]; */ /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,lm,x,y,z,dxp,dyp, \ dzp,amx,amy,amz,dx1,sq) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* zero out local accumulator */ for (j = 0; j < mxyv*(mz+1); j++) { sq[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = qm*(x - (float) nn); dyp = y - (float) mm; dzp = z - (float) ll; nn = nn - noff + mxv*(mm - moff) + mxyv*(ll - loff); amx = qm - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* deposit charge within tile to local accumulator */ x = sq[nn] + amx*amz; y = sq[nn+1] + amy*amz; sq[nn] = x; sq[nn+1] = y; mm = nn + mxv; x = sq[mm] + dyp*amz; y = sq[mm+1] + dx1*amz; sq[mm] = x; sq[mm+1] = y; nn += mxyv; x = sq[nn] + amx*dzp; y = sq[nn+1] + amy*dzp; sq[nn] = x; sq[nn+1] = y; mm = nn + mxv; x = sq[mm] + dyp*dzp; y = sq[mm+1] + dx1*dzp; sq[mm] = x; sq[mm+1] = y; } /* deposit charge to interior points in global array */ nn = nxv - noff; nn = mx < nn ? mx : nn; mm = nyv - moff; mm = my < mm ? my : mm; ll = nzv - loff; ll = mz < ll ? mz : ll; for (k = 1; k < ll; k++) { for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { q[i+noff+nxv*(j+moff)+nxyv*(k+loff)] += sq[i+mxv*j+mxyv*k]; } } } /* deposit charge to edge points in global array */ lm = nzv - loff; lm = mz+1 < lm ? mz+1 : lm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { #pragma omp atomic q[i+noff+nxv*(j+moff)+nxyv*loff] += sq[i+mxv*j]; if (lm > mz) { #pragma omp atomic q[i+noff+nxv*(j+moff)+nxyv*(lm+loff-1)] += sq[i+mxv*j+mxyv*(lm-1)]; } } } nm = nxv - noff; nm = mx+1 < nm ? mx+1 : nm; mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (k = 0; k < ll; k++) { for (i = 1; i < nn; i++) { #pragma omp atomic q[i+noff+nxv*moff+nxyv*(k+loff)] += sq[i+mxyv*k]; if (mm > my) { #pragma omp atomic q[i+noff+nxv*(mm+moff-1)+nxyv*(k+loff)] += sq[i+mxv*(mm-1)+mxyv*k]; } } for (j = 0; j < mm; j++) { #pragma omp atomic q[noff+nxv*(j+moff)+nxyv*(k+loff)] += sq[mxv*j+mxyv*k]; if (nm > mx) { #pragma omp atomic q[nm+noff-1+nxv*(j+moff)+nxyv*(k+loff)] += sq[nm-1+mxv*j+mxyv*k]; } } } if (lm > mz) { for (i = 1; i < nn; i++) { #pragma omp atomic q[i+noff+nxv*moff+nxyv*(lm+loff-1)] += sq[i+mxyv*(lm-1)]; if (mm > my) { #pragma omp atomic q[i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1)] += sq[i+mxv*(mm-1)+mxyv*(lm-1)]; } } for (j = 0; j < mm; j++) { #pragma omp atomic q[noff+nxv*(j+moff)+nxyv*(lm+loff-1)] += sq[mxv*j+mxyv*(lm-1)]; if (nm > mx) { #pragma omp atomic q[nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1)] += sq[nm-1+mxv*j+mxyv*(lm-1)]; } } } } return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgjppost3l(float ppart[], float cu[], int kpic[], float qm, float dt, int nppmx, int idimp, int nx, int ny, int nz, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1, int ipbc) { /* for 3d code, this subroutine calculates particle current density using first-order linear interpolation in addition, particle positions are advanced a half time-step OpenMP version using guard cells data deposited in tiles particles stored segmented array 69 flops/particle, 30 loads, 27 stores input: all, output: ppart, cu current density is approximated by values at the nearest grid points cu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) cu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) cu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) cu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) cu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz cu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz cu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz cu(i,n+1,m+1,l+1)=qci*dx*dy*dz where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l and qci = qm*vi, where i = x,y,z ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppart[m][n][3] = velocity vx of particle n in tile m ppart[m][n][4] = velocity vy of particle n in tile m ppart[m][n][5] = velocity vz of particle n in tile m cu[l][k][j][i] = ith component of current density at grid point j,k,l kpic = number of particles per tile qm = charge on particle, in units of e dt = time interval between successive calculations nppmx = maximum number of particles in tile idimp = size of phase space = 6 nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of current array, must be >= nx+1 nyv = third dimension of current array, must be >= ny+1 nzv = fourth dimension of current array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 ipbc = particle boundary condition = (0,1,2,3) = (none,3d periodic,3d reflecting,mixed 2d reflecting/1d periodic) local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, lm, mxv, myv, mxyv, nxyv; float edgelx, edgely, edgelz, edgerx, edgery, edgerz; float dxp, dyp, dzp, amx, amy, amz, dx1, dx, dy, dz, vx, vy, vz; float x, y, z; float scu[3*MXV*MYV*MZV]; /* float scu[3*(mx+1)*(my+1)*(mz+1)]; */ /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; /* set boundary values */ edgelx = 0.0f; edgely = 0.0f; edgelz = 0.0f; edgerx = (float) nx; edgery = (float) ny; edgerz = (float) nz; if (ipbc==2) { edgelx = 1.0f; edgely = 1.0f; edgelz = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); edgerz = (float) (nz-1); } else if (ipbc==3) { edgelx = 1.0f; edgely = 1.0f; edgerx = (float) (nx-1); edgery = (float) (ny-1); } /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,lm,x,y,z,dxp,dyp, \ dzp,amx,amy,amz,dx1,dx,dy,dz,vx,vy,vz,scu) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* zero out local accumulator */ for (j = 0; j < 3*mxyv*(mz+1); j++) { scu[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = qm*(x - (float) nn); dyp = y - (float) mm; dzp = z - (float) ll; nn = 3*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = qm - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* deposit current within tile to local accumulator */ dx = amx*amz; dy = amy*amz; vx = ppart[3+idimp*(j+npoff)]; vy = ppart[4+idimp*(j+npoff)]; vz = ppart[5+idimp*(j+npoff)]; scu[nn] += vx*dx; scu[nn+1] += vy*dx; scu[nn+2] += vz*dx; dx = dyp*amz; scu[nn+3] += vx*dy; scu[nn+1+3] += vy*dy; scu[nn+2+3] += vz*dy; dy = dx1*amz; mm = nn + 3*mxv; scu[mm] += vx*dx; scu[mm+1] += vy*dx; scu[mm+2] += vz*dx; dx = amx*dzp; scu[mm+3] += vx*dy; scu[mm+1+3] += vy*dy; scu[mm+2+3] += vz*dy; dy = amy*dzp; nn += 3*mxyv; scu[nn] += vx*dx; scu[nn+1] += vy*dx; scu[nn+2] += vz*dx; dx = dyp*dzp; scu[nn+3] += vx*dy; scu[nn+1+3] += vy*dy; scu[nn+2+3] += vz*dy; dy = dx1*dzp; mm = nn + 3*mxv; scu[mm] += vx*dx; scu[mm+1] += vy*dx; scu[mm+2] += vz*dx; scu[mm+3] += vx*dy; scu[mm+1+3] += vy*dy; scu[mm+2+3] += vz*dy; /* advance position half a time-step */ dx = x + vx*dt; dy = y + vy*dt; dz = z + vz*dt; /* reflecting boundary conditions */ if (ipbc==2) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; ppart[3+idimp*(j+npoff)] = -vx; } if ((dy < edgely) || (dy >= edgery)) { dy = y; ppart[4+idimp*(j+npoff)] = -vy; } if ((dz < edgelz) || (dz >= edgerz)) { dz = z; ppart[5+idimp*(j+npoff)] = -vz; } } /* mixed reflecting/periodic boundary conditions */ else if (ipbc==3) { if ((dx < edgelx) || (dx >= edgerx)) { dx = x; ppart[3+idimp*(j+npoff)] = -vx; } if ((dy < edgely) || (dy >= edgery)) { dy = y; ppart[4+idimp*(j+npoff)] = -vy; } } /* set new position */ ppart[idimp*(j+npoff)] = dx; ppart[1+idimp*(j+npoff)] = dy; ppart[2+idimp*(j+npoff)] = dz; } /* deposit current to interior points in global array */ nn = nxv - noff; nn = mx < nn ? mx : nn; mm = nyv - moff; mm = my < mm ? my : mm; ll = nzv - loff; ll = mz < ll ? mz : ll; for (k = 1; k < ll; k++) { for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { cu[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(i+mxv*j+mxyv*k)]; cu[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(i+mxv*j+mxyv*k)]; cu[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(i+mxv*j+mxyv*k)]; } } } /* deposit current to edge points in global array */ lm = nzv - loff; lm = mz+1 < lm ? mz+1 : lm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { #pragma omp atomic cu[3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[3*(i+mxv*j)]; #pragma omp atomic cu[1+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[1+3*(i+mxv*j)]; #pragma omp atomic cu[2+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[2+3*(i+mxv*j)]; if (lm > mz) { #pragma omp atomic cu[3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(i+mxv*j+mxyv*(lm-1))]; } } } nm = nxv - noff; nm = mx+1 < nm ? mx+1 : nm; mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (k = 0; k < ll; k++) { for (i = 1; i < nn; i++) { #pragma omp atomic cu[3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[3*(i+mxyv*k)]; #pragma omp atomic cu[1+3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[1+3*(i+mxyv*k)]; #pragma omp atomic cu[2+3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[2+3*(i+mxyv*k)]; if (mm > my) { #pragma omp atomic cu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic cu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[1+3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic cu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[2+3*(i+mxv*(mm-1)+mxyv*k)]; } } for (j = 0; j < mm; j++) { #pragma omp atomic cu[3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(mxv*j+mxyv*k)]; #pragma omp atomic cu[1+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(mxv*j+mxyv*k)]; #pragma omp atomic cu[2+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(mxv*j+mxyv*k)]; if (nm > mx) { #pragma omp atomic cu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic cu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic cu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(nm-1+mxv*j+mxyv*k)]; } } } if (lm > mz) { for (i = 1; i < nn; i++) { #pragma omp atomic cu[3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[3*(i+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[1+3*(i+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[2+3*(i+mxyv*(lm-1))]; if (mm > my) { #pragma omp atomic cu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[1+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[2+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; } } for (j = 0; j < mm; j++) { #pragma omp atomic cu[3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(mxv*j+mxyv*(lm-1))]; if (nm > mx) { #pragma omp atomic cu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(nm-1+mxv*j+mxyv*(lm-1))]; } } } } return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgmjppost3l(float ppart[], float amu[], int kpic[], float qm, int nppmx, int idimp, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1) { /* for 3d code, this subroutine calculates particle momentum flux using first-order linear interpolation OpenMP version using guard cells data deposited in tiles particles stored segmented array 121 flops/particle, 52 loads, 48 stores input: all, output: ppart, amu momentum flux is approximated by values at the nearest grid points amu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) amu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) amu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) amu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) amu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz amu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz amu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz amu(i,n+1,m+1,l+1)=qci*dx*dy*dz where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l and qci = qm*vj*vk, where jk = xx,xy,xz,yy,yz,zz, for i = 1, 6 where vj = vj(t-dt/2) and vk = vk(t-dt/2) ppart[m][n][0] = position x of particle n in tile m at t ppart[m][n][1] = position y of particle n in tile m at t ppart[m][n][2] = position z of particle n in tile m at t ppart[m][n][3] = velocity vx of particle n in tile m at t - dt/2 ppart[m][n][4] = velocity vy of particle n in tile m at t - dt/2 ppart[m][n][5] = velocity vz of particle n in tile m at t - dt/2 amu[l][k][j][i] = ith component of momentum flux at grid point j,k,l kpic = number of particles per tile qm = charge on particle, in units of e nppmx = maximum number of particles in tile idimp = size of phase space = 6 mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of current array, must be >= nx+1 nyv = third dimension of current array, must be >= ny+1 nzv = fourth dimension of current array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, lm, mxv, myv, mxyv, nxyv; float dxp, dyp, dzp, amx, amy, amz, dx1, dx, dy, vx, vy, vz; float x, y, z, v1, v2, v3, v4, v5, v6; float samu[6*MXV*MYV*MZV]; /* float samu[6*(mx+1)*(my+1)*(mz+1)]; */ /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,lm,x,y,z,dxp,dyp, \ dzp,amx,amy,amz,dx1,dx,dy,vx,vy,vz,v1,v2,v3,v4,v5,v6,samu) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* zero out local accumulator */ for (j = 0; j < 6*mxyv*(mz+1); j++) { samu[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = qm*(x - (float) nn); dyp = y - (float) mm; dzp = z - (float) ll; nn = 6*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = qm - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* deposit momentum flux within tile to local accumulator */ dx = amx*amz; dy = amy*amz; vx = ppart[3+idimp*(j+npoff)]; vy = ppart[4+idimp*(j+npoff)]; vz = ppart[5+idimp*(j+npoff)]; v1 = vx*vx; v2 = vx*vy; v3 = vx*vz; v4 = vy*vy; v5 = vy*vz; v6 = vz*vz; samu[nn] += v1*dx; samu[nn+1] += v2*dx; samu[nn+2] += v3*dx; samu[nn+3] += v4*dx; samu[nn+4] += v5*dx; samu[nn+5] += v6*dx; dx = dyp*amz; samu[nn+6] += v1*dy; samu[nn+1+6] += v2*dy; samu[nn+2+6] += v3*dy; samu[nn+3+6] += v4*dy; samu[nn+4+6] += v5*dy; samu[nn+5+6] += v6*dy; dy = dx1*amz; mm = nn + 6*mxv; samu[mm] += v1*dx; samu[mm+1] += v2*dx; samu[mm+2] += v3*dx; samu[mm+3] += v4*dx; samu[mm+4] += v5*dx; samu[mm+5] += v6*dx; dx = amx*dzp; samu[mm+6] += v1*dy; samu[mm+1+6] += v2*dy; samu[mm+2+6] += v3*dy; samu[mm+3+6] += v4*dy; samu[mm+4+6] += v5*dy; samu[mm+5+6] += v6*dy; dy = amy*dzp; nn += 6*mxyv; samu[nn] += v1*dx; samu[nn+1] += v2*dx; samu[nn+2] += v3*dx; samu[nn+3] += v4*dx; samu[nn+4] += v5*dx; samu[nn+5] += v6*dx; dx = dyp*dzp; samu[nn+6] += v1*dy; samu[nn+1+6] += v2*dy; samu[nn+2+6] += v3*dy; samu[nn+3+6] += v4*dy; samu[nn+4+6] += v5*dy; samu[nn+5+6] += v6*dy; dy = dx1*dzp; mm = nn + 6*mxv; samu[mm] += v1*dx; samu[mm+1] += v2*dx; samu[mm+2] += v3*dx; samu[mm+3] += v4*dx; samu[mm+4] += v5*dx; samu[mm+5] += v6*dx; samu[mm+6] += v1*dy; samu[mm+1+6] += v2*dy; samu[mm+2+6] += v3*dy; samu[mm+3+6] += v4*dy; samu[mm+4+6] += v5*dy; samu[mm+5+6] += v6*dy; } /* deposit momentum flux to interior points in global array */ nn = nxv - noff; nn = mx < nn ? mx : nn; mm = nyv - moff; mm = my < mm ? my : mm; ll = nzv - loff; ll = mz < ll ? mz : ll; for (k = 1; k < ll; k++) { for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { amu[6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(i+mxv*j+mxyv*k)]; amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(i+mxv*j+mxyv*k)]; amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(i+mxv*j+mxyv*k)]; amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(i+mxv*j+mxyv*k)]; amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(i+mxv*j+mxyv*k)]; amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(i+mxv*j+mxyv*k)]; } } } /* deposit momentum flux to edge points in global array */ lm = nzv - loff; lm = mz+1 < lm ? mz+1 : lm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[6*(i+mxv*j)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[1+6*(i+mxv*j)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[2+6*(i+mxv*j)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[3+6*(i+mxv*j)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[4+6*(i+mxv*j)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[5+6*(i+mxv*j)]; if (lm > mz) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*j+mxyv*(lm-1))]; } } } nm = nxv - noff; nm = mx+1 < nm ? mx+1 : nm; mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (k = 0; k < ll; k++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[6*(i+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[1+6*(i+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[2+6*(i+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[3+6*(i+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[4+6*(i+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[5+6*(i+mxyv*k)]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[1+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[2+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[3+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[4+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[5+6*(i+mxv*(mm-1)+mxyv*k)]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(mxv*j+mxyv*k)]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(nm-1+mxv*j+mxyv*k)]; } } } if (lm > mz) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[1+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[2+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[3+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[4+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[5+6*(i+mxyv*(lm-1))]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(mxv*j+mxyv*(lm-1))]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(nm-1+mxv*j+mxyv*(lm-1))]; } } } } return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgdjppost3l(float ppart[], float fxyz[], float bxyz[], int kpic[], float dcu[], float amu[], float qm, float qbm, float dt, int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1) { /* for 3 code, this subroutine calculates particle momentum flux, and acceleration density using first-order spline interpolation. OpenMP version using guard cells data read/written in tiles particles stored segmented array 350 flops/particle, 1 divide, 126 loads, 72 stores acceleration density is approximated by values at the nearest grid points dcu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) dcu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) dcu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) dcu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) dcu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz dcu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz dcu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz dcu(i,n+1,m+1,l+1)=qci*dx*dy*dz and qci = qm*dvj/dt, where j = x,y,z, for i = 1, 3 where dvj = (vj(t+dt/2)-vj(t-dt/2))/dt momentum flux is approximated by values at the nearest grid points amu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) amu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) amu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) amu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) amu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz amu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz amu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz amu(i,n+1,m+1,l+1)=qci*dx*dy*dz and qci = qm*vj*vk, where jk = xx,xy,xz,yy,yz,zz, for i = 1, 6 where vj = 0.5*(vj(t+dt/2)+vj(t-dt/2), and vk = 0.5*(vk(t+dt/2)+vk(t-dt/2)) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l velocity equations at t=t+dt/2 are calculated from: vx(t+dt/2) = rot(1)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(2)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(3)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) vy(t+dt/2) = rot(4)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(5)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(6)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) vz(t+dt/2) = rot(7)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(8)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(9)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) where q/m is charge/mass, and the rotation matrix is given by: rot(1) = (1 - (om*dt/2)**2 + 2*(omx*dt/2)**2)/(1 + (om*dt/2)**2) rot(2) = 2*(omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(3) = 2*(-omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(4) = 2*(-omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(5) = (1 - (om*dt/2)**2 + 2*(omy*dt/2)**2)/(1 + (om*dt/2)**2) rot(6) = 2*(omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(7) = 2*(omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(8) = 2*(-omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(9) = (1 - (om*dt/2)**2 + 2*(omz*dt/2)**2)/(1 + (om*dt/2)**2) and om**2 = omx**2 + omy**2 + omz**2 the rotation matrix is determined by: omx = (q/m)*bx(x(t),y(t),z(t)), omy = (q/m)*by(x(t),y(t),z(t)), and omz = (q/m)*bz(x(t),y(t),z(t)). fx(x(t),y(t),z(t)), fy(x(t),y(t),z(t)), and fz(x(t),y(t),z(t)), bx(x(t),y(t),z(t)), by(x(t),y(t),z(t)), and bz(x(t),y(t),z(t)) are approximated by interpolation from the nearest grid points: fx(x,y,z) = (1-dz)*((1-dy)*((1-dx)*fx(n,m,l)+dx*fx(n+1,m,l)) + dy*((1-dx)*fx(n,m+1,l) + dx*fx(n+1,m+1,l))) + dz*((1-dy)*((1-dx)*fx(n,m,l+1)+dx*fx(n+1,m,l+1)) + dy*((1-dx)*fx(n,m+1,l+1) + dx*fx(n+1,m+1,l+1))) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l similarly for fy(x,y,z), fz(x,y,z), bx(x,y,z), by(x,y,z), bz(x,y,z) ppart[m][n][0] = position x of particle n in tile m at t ppart[m][n][1] = position y of particle n in tile m at t ppart[m][n][2] = position z of particle n in tile m at t ppart[m][n][3] = velocity vx of particle n in tile m at t - dt/2 ppart[m][n][4] = velocity vy of particle n in tile m at t - dt/2 ppart[m][n][5] = velocity vz of particle n in tile m at t - dt/2 fxyz[l][k][j][0] = x component of force/charge at grid (j,k,l) fxyz[l][k][j][1] = y component of force/charge at grid (j,k,l) fxyz[l][k][j][2] = z component of force/charge at grid (j,k,l) that is, convolution of electric field over particle shape bxyz[l][k][j][0] = x component of magnetic field at grid (j,k,l) bxyz[l][k][j][1] = y component of magnetic field at grid (j,k,l) bxyz[l][k][j][2] = z component of magnetic field at grid (j,k,l) that is, the convolution of magnetic field over particle shape dcu[l][k][j][i] = ith component of acceleration density at grid point j,k for i = 1, 3 amu[l][k][j][i] = ith component of momentum flux at grid point j,k,l for i = 1, 6 kpic = number of particles per tile qm = charge on particle, in units of e qbm = particle charge/mass ratio dt = time interval between successive force calculations idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 nzv = fourth dimension of field array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, lm, mxv, myv, mxyv, nxyv; float qtmh, dti, dxp, dyp, dzp, amx, amy, amz, dx, dy, dz; float ox, oy, oz, dx1, acx, acy, acz, omxt, omyt, omzt, omt, anorm; float rot1, rot2, rot3, rot4, rot5, rot6, rot7, rot8, rot9; float x, y, z, vx, vy, vz, v1, v2, v3, v4, v5, v6; float sfxyz[3*MXV*MYV*MZV], sbxyz[3*MXV*MYV*MZV]; float sdcu[3*MXV*MYV*MZV], samu[6*MXV*MYV*MZV]; /* float sfxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sbxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sdcu[3*(mx+1)*(my+1)*(mz+1)]; */ /* float samu[6*(mx+1)*(my+1)*(mz+1)]; */ /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; qtmh = 0.5f*qbm*dt; dti = 1.0f/dt; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,lm,x,y,z,vx,vy,vz, \ v1,v2,v3,v4,v5,v6,dxp,dyp,dzp,amx,amy,amz,dx1,dx,dy,dz,ox,oy,oz,acx, \ acy,acz,omxt,omyt,omzt,omt,anorm,rot1,rot2,rot3,rot4,rot5,rot6,rot7, \ rot8,rot9,sfxyz,sbxyz,sdcu,samu) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; ll = (mz < nz-loff ? mz : nz-loff) + 1; for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxyz[3*(i+mxv*j+mxyv*k)] = fxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[1+3*(i+mxv*j+mxyv*k)] = fxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[2+3*(i+mxv*j+mxyv*k)] = fxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sbxyz[3*(i+mxv*j+mxyv*k)] = bxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[1+3*(i+mxv*j+mxyv*k)] = bxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[2+3*(i+mxv*j+mxyv*k)] = bxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } /* zero out local accumulators */ for (j = 0; j < 3*mxyv*(mz+1); j++) { sdcu[j] = 0.0f; } for (j = 0; j < 6*mxyv*(mz+1); j++) { samu[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = x - (float) nn; dyp = y - (float) mm; dzp = z - (float) ll; nm = 3*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = 1.0f - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* find electric field */ nn = nm; dx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; dy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; dz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = amz*(dx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = amz*(dy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = amz*(dz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; acy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; acz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = dx + dzp*(acx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = dy + dzp*(acy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = dz + dzp*(acz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); /* find magnetic field */ nn = nm; ox = amx*sbxyz[nn] + amy*sbxyz[nn+3]; oy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; oz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = amz*(ox + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = amz*(oy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = amz*(oz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sbxyz[nn] + amy*sbxyz[nn+3]; acy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; acz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = ox + dzp*(acx + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = oy + dzp*(acy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = oz + dzp*(acz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); /* calculate half impulse */ dx *= qtmh; dy *= qtmh; dz *= qtmh; /* half acceleration */ vx = ppart[3+idimp*(j+npoff)]; vy = ppart[4+idimp*(j+npoff)]; vz = ppart[5+idimp*(j+npoff)]; acx = vx + dx; acy = vy + dy; acz = vz + dz; /* calculate cyclotron frequency */ omxt = qtmh*ox; omyt = qtmh*oy; omzt = qtmh*oz; /* calculate rotation matrix */ omt = omxt*omxt + omyt*omyt + omzt*omzt; anorm = 2.0f/(1.0f + omt); omt = 0.5f*(1.0f - omt); rot4 = omxt*omyt; rot7 = omxt*omzt; rot8 = omyt*omzt; rot1 = omt + omxt*omxt; rot5 = omt + omyt*omyt; rot9 = omt + omzt*omzt; rot2 = omzt + rot4; rot4 -= omzt; rot3 = -omyt + rot7; rot7 += omyt; rot6 = omxt + rot8; rot8 -= omxt; /* new velocity */ dx += (rot1*acx + rot2*acy + rot3*acz)*anorm; dy += (rot4*acx + rot5*acy + rot6*acz)*anorm; dz += (rot7*acx + rot8*acy + rot9*acz)*anorm; /* deposit momentum flux and acceleration density */ nn = nm; amz = qm*amz; dzp = qm*dzp; ox = 0.5*(dx + vx); oy = 0.5*(dy + vy); oz = 0.5*(dz + vz); vx = dti*(dx - vx); vy = dti*(dy - vy); vz = dti*(dz - vz); dx = amx*amz; dy = amy*amz; v1 = ox*ox; v2 = ox*oy; v3 = ox*oz; v4 = oy*oy; v5 = oy*oz; v6 = oz*oz; samu[2*nn] += v1*dx; samu[2*nn+1] += v2*dx; samu[2*nn+2] += v3*dx; samu[2*nn+3] += v4*dx; samu[2*nn+4] += v5*dx; samu[2*nn+5] += v6*dx; sdcu[nn] += vx*dx; sdcu[nn+1] += vy*dx; sdcu[nn+2] += vz*dx; dx = dyp*amz; samu[2*nn+6] += v1*dy; samu[2*nn+1+6] += v2*dy; samu[2*nn+2+6] += v3*dy; samu[2*nn+3+6] += v4*dy; samu[2*nn+4+6] += v5*dy; samu[2*nn+5+6] += v6*dy; sdcu[nn+3] += vx*dy; sdcu[nn+1+3] += vy*dy; sdcu[nn+2+3] += vz*dy; dy = dx1*amz; mm = nn + 3*mxv; samu[2*mm] += v1*dx; samu[2*mm+1] += v2*dx; samu[2*mm+2] += v3*dx; samu[2*mm+3] += v4*dx; samu[2*mm+4] += v5*dx; samu[2*mm+5] += v6*dx; sdcu[mm] += vx*dx; sdcu[mm+1] += vy*dx; sdcu[mm+2] += vz*dx; dx = amx*dzp; samu[2*mm+6] += v1*dy; samu[2*mm+1+6] += v2*dy; samu[2*mm+2+6] += v3*dy; samu[2*mm+3+6] += v4*dy; samu[2*mm+4+6] += v5*dy; samu[2*mm+5+6] += v6*dy; sdcu[mm+3] += vx*dy; sdcu[mm+1+3] += vy*dy; sdcu[mm+2+3] += vz*dy; dy = amy*dzp; nn += 3*mxyv; samu[2*nn] += v1*dx; samu[2*nn+1] += v2*dx; samu[2*nn+2] += v3*dx; samu[2*nn+3] += v4*dx; samu[2*nn+4] += v5*dx; samu[2*nn+5] += v6*dx; sdcu[nn] += vx*dx; sdcu[nn+1] += vy*dx; sdcu[nn+2] += vz*dx; dx = dyp*dzp; samu[2*nn+6] += v1*dy; samu[2*nn+1+6] += v2*dy; samu[2*nn+2+6] += v3*dy; samu[2*nn+3+6] += v4*dy; samu[2*nn+4+6] += v5*dy; samu[2*nn+5+6] += v6*dy; sdcu[nn+3] += vx*dy; sdcu[nn+1+3] += vy*dy; sdcu[nn+2+3] += vz*dy; dy = dx1*dzp; mm = nn + 3*mxv; samu[2*mm] += v1*dx; samu[2*mm+1] += v2*dx; samu[2*mm+2] += v3*dx; samu[2*mm+3] += v4*dx; samu[2*mm+4] += v5*dx; samu[2*mm+5] += v6*dx; sdcu[mm] += vx*dx; sdcu[mm+1] += vy*dx; sdcu[mm+2] += vz*dx; samu[2*mm+6] += v1*dy; samu[2*mm+1+6] += v2*dy; samu[2*mm+2+6] += v3*dy; samu[2*mm+3+6] += v4*dy; samu[2*mm+4+6] += v5*dy; samu[2*mm+5+6] += v6*dy; sdcu[mm+3] += vx*dy; sdcu[mm+1+3] += vy*dy; sdcu[mm+2+3] += vz*dy; } /* deposit current to interior points in global array */ nn = nxv - noff; nn = mx < nn ? mx : nn; mm = nyv - moff; mm = my < mm ? my : mm; ll = nzv - loff; ll = mz < ll ? mz : ll; for (k = 1; k < ll; k++) { for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { amu[6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(i+mxv*j+mxyv*k)]; amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(i+mxv*j+mxyv*k)]; amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(i+mxv*j+mxyv*k)]; amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(i+mxv*j+mxyv*k)]; amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(i+mxv*j+mxyv*k)]; amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(i+mxv*j+mxyv*k)]; dcu[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(i+mxv*j+mxyv*k)]; dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(i+mxv*j+mxyv*k)]; dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(i+mxv*j+mxyv*k)]; } } } /* deposit current to edge points in global array */ lm = nzv - loff; lm = mz+1 < lm ? mz+1 : lm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[6*(i+mxv*j)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[1+6*(i+mxv*j)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[2+6*(i+mxv*j)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[3+6*(i+mxv*j)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[4+6*(i+mxv*j)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[5+6*(i+mxv*j)]; #pragma omp atomic dcu[3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[3*(i+mxv*j)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[1+3*(i+mxv*j)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[2+3*(i+mxv*j)]; if (lm > mz) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxv*j+mxyv*(lm-1))]; } } } nm = nxv - noff; nm = mx+1 < nm ? mx+1 : nm; mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (k = 0; k < ll; k++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[6*(i+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[1+6*(i+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[2+6*(i+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[3+6*(i+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[4+6*(i+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[5+6*(i+mxyv*k)]; #pragma omp atomic dcu[3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[3*(i+mxyv*k)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[1+3*(i+mxyv*k)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[2+3*(i+mxyv*k)]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[1+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[2+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[3+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[4+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[5+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[1+3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[2+3*(i+mxv*(mm-1)+mxyv*k)]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[1+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[2+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(mxv*j+mxyv*k)]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(nm-1+mxv*j+mxyv*k)]; } } } if (lm > mz) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[1+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[2+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[3+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[4+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[5+6*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[3*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxyv*(lm-1))]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(mxv*j+mxyv*(lm-1))]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(nm-1+mxv*j+mxyv*(lm-1))]; } } } } return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cgdcjppost3l(float ppart[], float fxyz[], float bxyz[], int kpic[], float cu[], float dcu[], float amu[], float qm, float qbm, float dt, int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int nxv, int nyv, int nzv, int mx1, int my1, int mxyz1) { /* for 3 code, this subroutine calculates particle momentum flux, acceleration density and current density using first-order spline interpolation. OpenMP version using guard cells data read/written in tiles particles stored segmented array 398 flops/particle, 1 divide, 150 loads, 96 stores input: all, output: cu, dcu, amu current density is approximated by values at the nearest grid points cu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) cu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) cu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) cu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) cu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz cu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz cu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz cu(i,n+1,m+1,l+1)=qci*dx*dy*dz and qci = qm*vj, where j = x,y,z, for i = 1, 3 where vj = .5*(vj(t+dt/2)+vj(t-dt/2)) acceleration density is approximated by values at the nearest grid points dcu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) dcu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) dcu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) dcu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) dcu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz dcu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz dcu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz dcu(i,n+1,m+1,l+1)=qci*dx*dy*dz and qci = qm*dvj/dt, where j = x,y,z, for i = 1, 3 where dvj = (vj(t+dt/2)-vj(t-dt/2))/dt momentum flux is approximated by values at the nearest grid points amu(i,n,m,l)=qci*(1.-dx)*(1.-dy)*(1.-dz) amu(i,n+1,m,l)=qci*dx*(1.-dy)*(1.-dz) amu(i,n,m+1,l)=qci*(1.-dx)*dy*(1.-dz) amu(i,n+1,m+1,l)=qci*dx*dy*(1.-dz) amu(i,n,m,l+1)=qci*(1.-dx)*(1.-dy)*dz amu(i,n+1,m,l+1)=qci*dx*(1.-dy)*dz amu(i,n,m+1,l+1)=qci*(1.-dx)*dy*dz amu(i,n+1,m+1,l+1)=qci*dx*dy*dz and qci = qm*vj*vk, where jk = xx,xy,xz,yy,yz,zz, for i = 1, 6 where vj = 0.5*(vj(t+dt/2)+vj(t-dt/2), and vk = 0.5*(vk(t+dt/2)+vk(t-dt/2)) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l velocity equations at t=t+dt/2 are calculated from: vx(t+dt/2) = rot(1)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(2)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(3)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) vy(t+dt/2) = rot(4)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(5)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(6)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) vz(t+dt/2) = rot(7)*(vx(t-dt/2) + .5*(q/m)*fx(x(t),y(t),z(t))*dt) + rot(8)*(vy(t-dt/2) + .5*(q/m)*fy(x(t),y(t),z(t))*dt) + rot(9)*(vz(t-dt/2) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) + .5*(q/m)*fz(x(t),y(t),z(t))*dt) where q/m is charge/mass, and the rotation matrix is given by: rot(1) = (1 - (om*dt/2)**2 + 2*(omx*dt/2)**2)/(1 + (om*dt/2)**2) rot(2) = 2*(omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(3) = 2*(-omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(4) = 2*(-omz*dt/2 + (omx*dt/2)*(omy*dt/2))/(1 + (om*dt/2)**2) rot(5) = (1 - (om*dt/2)**2 + 2*(omy*dt/2)**2)/(1 + (om*dt/2)**2) rot(6) = 2*(omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(7) = 2*(omy*dt/2 + (omx*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(8) = 2*(-omx*dt/2 + (omy*dt/2)*(omz*dt/2))/(1 + (om*dt/2)**2) rot(9) = (1 - (om*dt/2)**2 + 2*(omz*dt/2)**2)/(1 + (om*dt/2)**2) and om**2 = omx**2 + omy**2 + omz**2 the rotation matrix is determined by: omx = (q/m)*bx(x(t),y(t),z(t)), omy = (q/m)*by(x(t),y(t),z(t)), and omz = (q/m)*bz(x(t),y(t),z(t)). fx(x(t),y(t),z(t)), fy(x(t),y(t),z(t)), and fz(x(t),y(t),z(t)), bx(x(t),y(t),z(t)), by(x(t),y(t),z(t)), and bz(x(t),y(t),z(t)) are approximated by interpolation from the nearest grid points: fx(x,y,z) = (1-dz)*((1-dy)*((1-dx)*fx(n,m,l)+dx*fx(n+1,m,l)) + dy*((1-dx)*fx(n,m+1,l) + dx*fx(n+1,m+1,l))) + dz*((1-dy)*((1-dx)*fx(n,m,l+1)+dx*fx(n+1,m,l+1)) + dy*((1-dx)*fx(n,m+1,l+1) + dx*fx(n+1,m+1,l+1))) where n,m,l = leftmost grid points and dx = x-n, dy = y-m, dz = z-l similarly for fy(x,y,z), fz(x,y,z), bx(x,y,z), by(x,y,z), bz(x,y,z) ppart[m][n][0] = position x of particle n in tile m at t ppart[m][n][1] = position y of particle n in tile m at t ppart[m][n][2] = position z of particle n in tile m at t ppart[m][n][3] = velocity vx of particle n in tile m at t - dt/2 ppart[m][n][4] = velocity vy of particle n in tile m at t - dt/2 ppart[m][n][5] = velocity vz of particle n in tile m at t - dt/2 fxyz[l][k][j][0] = x component of force/charge at grid (j,k,l) fxyz[l][k][j][1] = y component of force/charge at grid (j,k,l) fxyz[l][k][j][2] = z component of force/charge at grid (j,k,l) that is, convolution of electric field over particle shape bxyz[l][k][j][0] = x component of magnetic field at grid (j,k,l) bxyz[l][k][j][1] = y component of magnetic field at grid (j,k,l) bxyz[l][k][j][2] = z component of magnetic field at grid (j,k,l) that is, the convolution of magnetic field over particle shape cu[l][k][j][i] = ith component of current density at grid point j,k for i = 1, 3 dcu[l][k][j][i] = ith component of acceleration density at grid point j,k for i = 1, 3 amu[l][k][j][i] = ith component of momentum flux at grid point j,k,l for i = 1, 6 kpic = number of particles per tile qm = charge on particle, in units of e qbm = particle charge/mass ratio dt = time interval between successive force calculations idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z nxv = second dimension of field arrays, must be >= nx+1 nyv = third dimension of field arrays, must be >= ny+1 nzv = fourth dimension of field array, must be >= nz+1 mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mxyz1 = mx1*my1*mz1, where mz1 = (system length in z direction - 1)/mz + 1 local data */ #define MXV 17 #define MYV 17 #define MZV 17 int mxy1, noff, moff, loff, npoff, npp; int i, j, k, l, nn, mm, ll, nm, lm, mxv, myv, mxyv, nxyv; float qtmh, dti, dxp, dyp, dzp, amx, amy, amz, dx, dy, dz; float ox, oy, oz, dx1, acx, acy, acz, omxt, omyt, omzt, omt, anorm; float rot1, rot2, rot3, rot4, rot5, rot6, rot7, rot8, rot9; float x, y, z, vx, vy, vz, v1, v2, v3, v4, v5, v6; float sfxyz[3*MXV*MYV*MZV], sbxyz[3*MXV*MYV*MZV]; float scu[3*MXV*MYV*MZV], sdcu[3*MXV*MYV*MZV]; float samu[6*MXV*MYV*MZV]; /* float sfxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sbxyz[3*(mx+1)*(my+1)*(mz+1)]; */ /* float scu[3*(mx+1)*(my+1)*(mz+1)]; */ /* float sdcu[3*(mx+1)*(my+1)*(mz+1)]; */ /* float samu[6*(mx+1)*(my+1)*(mz+1)]; */ /* mxv = MXV; */ /* myv = MYV; */ mxv = mx+1; myv = my+1; mxyv = mxv*myv; nxyv = nxv*nyv; mxy1 = mx1*my1; qtmh = 0.5f*qbm*dt; dti = 1.0f/dt; /* error if local array is too small */ /* if ((mx >= MXV) || (my >= MYV) || (mz >= MZV)) */ /* return; */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,noff,moff,loff,npp,npoff,nn,mm,ll,nm,lm,x,y,z,vx,vy,vz, \ v1,v2,v3,v4,v5,v6,dxp,dyp,dzp,amx,amy,amz,dx1,dx,dy,dz,ox,oy,oz,acx, \ acy,acz,omxt,omyt,omzt,omt,anorm,rot1,rot2,rot3,rot4,rot5,rot6,rot7, \ rot8,rot9,sfxyz,sbxyz,scu,sdcu,samu) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; npoff = nppmx*l; /* load local fields from global array */ nn = (mx < nx-noff ? mx : nx-noff) + 1; mm = (my < ny-moff ? my : ny-moff) + 1; ll = (mz < nz-loff ? mz : nz-loff) + 1; for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sfxyz[3*(i+mxv*j+mxyv*k)] = fxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[1+3*(i+mxv*j+mxyv*k)] = fxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sfxyz[2+3*(i+mxv*j+mxyv*k)] = fxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } for (k = 0; k < ll; k++) { for (j = 0; j < mm; j++) { for (i = 0; i < nn; i++) { sbxyz[3*(i+mxv*j+mxyv*k)] = bxyz[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[1+3*(i+mxv*j+mxyv*k)] = bxyz[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; sbxyz[2+3*(i+mxv*j+mxyv*k)] = bxyz[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))]; } } } /* zero out local accumulators */ for (j = 0; j < 3*mxyv*(mz+1); j++) { scu[j] = 0.0f; sdcu[j] = 0.0f; } for (j = 0; j < 6*mxyv*(mz+1); j++) { samu[j] = 0.0f; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { /* find interpolation weights */ x = ppart[idimp*(j+npoff)]; y = ppart[1+idimp*(j+npoff)]; z = ppart[2+idimp*(j+npoff)]; nn = x; mm = y; ll = z; dxp = x - (float) nn; dyp = y - (float) mm; dzp = z - (float) ll; nm = 3*(nn - noff + mxv*(mm - moff) + mxyv*(ll - loff)); amx = 1.0f - dxp; amy = 1.0f - dyp; dx1 = dxp*dyp; dyp = amx*dyp; amx = amx*amy; amz = 1.0f - dzp; amy = dxp*amy; /* find electric field */ nn = nm; dx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; dy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; dz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = amz*(dx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = amz*(dy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = amz*(dz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sfxyz[nn] + amy*sfxyz[nn+3]; acy = amx*sfxyz[nn+1] + amy*sfxyz[nn+1+3]; acz = amx*sfxyz[nn+2] + amy*sfxyz[nn+2+3]; mm = nn + 3*mxv; dx = dx + dzp*(acx + dyp*sfxyz[mm] + dx1*sfxyz[mm+3]); dy = dy + dzp*(acy + dyp*sfxyz[mm+1] + dx1*sfxyz[mm+1+3]); dz = dz + dzp*(acz + dyp*sfxyz[mm+2] + dx1*sfxyz[mm+2+3]); /* find magnetic field */ nn = nm; ox = amx*sbxyz[nn] + amy*sbxyz[nn+3]; oy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; oz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = amz*(ox + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = amz*(oy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = amz*(oz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); nn += 3*mxyv; acx = amx*sbxyz[nn] + amy*sbxyz[nn+3]; acy = amx*sbxyz[nn+1] + amy*sbxyz[nn+1+3]; acz = amx*sbxyz[nn+2] + amy*sbxyz[nn+2+3]; mm = nn + 3*mxv; ox = ox + dzp*(acx + dyp*sbxyz[mm] + dx1*sbxyz[mm+3]); oy = oy + dzp*(acy + dyp*sbxyz[mm+1] + dx1*sbxyz[mm+1+3]); oz = oz + dzp*(acz + dyp*sbxyz[mm+2] + dx1*sbxyz[mm+2+3]); /* calculate half impulse */ dx *= qtmh; dy *= qtmh; dz *= qtmh; /* half acceleration */ vx = ppart[3+idimp*(j+npoff)]; vy = ppart[4+idimp*(j+npoff)]; vz = ppart[5+idimp*(j+npoff)]; acx = vx + dx; acy = vy + dy; acz = vz + dz; /* calculate cyclotron frequency */ omxt = qtmh*ox; omyt = qtmh*oy; omzt = qtmh*oz; /* calculate rotation matrix */ omt = omxt*omxt + omyt*omyt + omzt*omzt; anorm = 2.0f/(1.0f + omt); omt = 0.5f*(1.0f - omt); rot4 = omxt*omyt; rot7 = omxt*omzt; rot8 = omyt*omzt; rot1 = omt + omxt*omxt; rot5 = omt + omyt*omyt; rot9 = omt + omzt*omzt; rot2 = omzt + rot4; rot4 -= omzt; rot3 = -omyt + rot7; rot7 += omyt; rot6 = omxt + rot8; rot8 -= omxt; /* new velocity */ dx += (rot1*acx + rot2*acy + rot3*acz)*anorm; dy += (rot4*acx + rot5*acy + rot6*acz)*anorm; dz += (rot7*acx + rot8*acy + rot9*acz)*anorm; /* deposit momentum flux, acceleration density, and current density */ nn = nm; amz = qm*amz; dzp = qm*dzp; ox = 0.5*(dx + vx); oy = 0.5*(dy + vy); oz = 0.5*(dz + vz); vx = dti*(dx - vx); vy = dti*(dy - vy); vz = dti*(dz - vz); dx = amx*amz; dy = amy*amz; v1 = ox*ox; v2 = ox*oy; v3 = ox*oz; v4 = oy*oy; v5 = oy*oz; v6 = oz*oz; samu[2*nn] += v1*dx; samu[2*nn+1] += v2*dx; samu[2*nn+2] += v3*dx; samu[2*nn+3] += v4*dx; samu[2*nn+4] += v5*dx; samu[2*nn+5] += v6*dx; sdcu[nn] += vx*dx; sdcu[nn+1] += vy*dx; sdcu[nn+2] += vz*dx; scu[nn] += ox*dx; scu[nn+1] += oy*dx; scu[nn+2] += oz*dx; dx = dyp*amz; samu[2*nn+6] += v1*dy; samu[2*nn+1+6] += v2*dy; samu[2*nn+2+6] += v3*dy; samu[2*nn+3+6] += v4*dy; samu[2*nn+4+6] += v5*dy; samu[2*nn+5+6] += v6*dy; sdcu[nn+3] += vx*dy; sdcu[nn+1+3] += vy*dy; sdcu[nn+2+3] += vz*dy; scu[nn+3] += ox*dy; scu[nn+1+3] += oy*dy; scu[nn+2+3] += oz*dy; dy = dx1*amz; mm = nn + 3*mxv; samu[2*mm] += v1*dx; samu[2*mm+1] += v2*dx; samu[2*mm+2] += v3*dx; samu[2*mm+3] += v4*dx; samu[2*mm+4] += v5*dx; samu[2*mm+5] += v6*dx; sdcu[mm] += vx*dx; sdcu[mm+1] += vy*dx; sdcu[mm+2] += vz*dx; scu[mm] += ox*dx; scu[mm+1] += oy*dx; scu[mm+2] += oz*dx; dx = amx*dzp; samu[2*mm+6] += v1*dy; samu[2*mm+1+6] += v2*dy; samu[2*mm+2+6] += v3*dy; samu[2*mm+3+6] += v4*dy; samu[2*mm+4+6] += v5*dy; samu[2*mm+5+6] += v6*dy; sdcu[mm+3] += vx*dy; sdcu[mm+1+3] += vy*dy; sdcu[mm+2+3] += vz*dy; scu[mm+3] += ox*dy; scu[mm+1+3] += oy*dy; scu[mm+2+3] += oz*dy; dy = amy*dzp; nn += 3*mxyv; samu[2*nn] += v1*dx; samu[2*nn+1] += v2*dx; samu[2*nn+2] += v3*dx; samu[2*nn+3] += v4*dx; samu[2*nn+4] += v5*dx; samu[2*nn+5] += v6*dx; sdcu[nn] += vx*dx; sdcu[nn+1] += vy*dx; sdcu[nn+2] += vz*dx; scu[nn] += ox*dx; scu[nn+1] += oy*dx; scu[nn+2] += oz*dx; dx = dyp*dzp; samu[2*nn+6] += v1*dy; samu[2*nn+1+6] += v2*dy; samu[2*nn+2+6] += v3*dy; samu[2*nn+3+6] += v4*dy; samu[2*nn+4+6] += v5*dy; samu[2*nn+5+6] += v6*dy; sdcu[nn+3] += vx*dy; sdcu[nn+1+3] += vy*dy; sdcu[nn+2+3] += vz*dy; scu[nn+3] += ox*dy; scu[nn+1+3] += oy*dy; scu[nn+2+3] += oz*dy; dy = dx1*dzp; mm = nn + 3*mxv; samu[2*mm] += v1*dx; samu[2*mm+1] += v2*dx; samu[2*mm+2] += v3*dx; samu[2*mm+3] += v4*dx; samu[2*mm+4] += v5*dx; samu[2*mm+5] += v6*dx; sdcu[mm] += vx*dx; sdcu[mm+1] += vy*dx; sdcu[mm+2] += vz*dx; scu[mm] += ox*dx; scu[mm+1] += oy*dx; scu[mm+2] += oz*dx; samu[2*mm+6] += v1*dy; samu[2*mm+1+6] += v2*dy; samu[2*mm+2+6] += v3*dy; samu[2*mm+3+6] += v4*dy; samu[2*mm+4+6] += v5*dy; samu[2*mm+5+6] += v6*dy; sdcu[mm+3] += vx*dy; sdcu[mm+1+3] += vy*dy; sdcu[mm+2+3] += vz*dy; scu[mm+3] += ox*dy; scu[mm+1+3] += oy*dy; scu[mm+2+3] += oz*dy; } /* deposit current to interior points in global array */ nn = nxv - noff; nn = mx < nn ? mx : nn; mm = nyv - moff; mm = my < mm ? my : mm; ll = nzv - loff; ll = mz < ll ? mz : ll; for (k = 1; k < ll; k++) { for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { amu[6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(i+mxv*j+mxyv*k)]; amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(i+mxv*j+mxyv*k)]; amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(i+mxv*j+mxyv*k)]; amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(i+mxv*j+mxyv*k)]; amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(i+mxv*j+mxyv*k)]; amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(i+mxv*j+mxyv*k)]; dcu[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(i+mxv*j+mxyv*k)]; dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(i+mxv*j+mxyv*k)]; dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(i+mxv*j+mxyv*k)]; cu[3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(i+mxv*j+mxyv*k)]; cu[1+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(i+mxv*j+mxyv*k)]; cu[2+3*(i+noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(i+mxv*j+mxyv*k)]; } } } /* deposit current to edge points in global array */ lm = nzv - loff; lm = mz+1 < lm ? mz+1 : lm; for (j = 1; j < mm; j++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[6*(i+mxv*j)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[1+6*(i+mxv*j)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[2+6*(i+mxv*j)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[3+6*(i+mxv*j)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[4+6*(i+mxv*j)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*loff)] += samu[5+6*(i+mxv*j)]; #pragma omp atomic dcu[3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[3*(i+mxv*j)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[1+3*(i+mxv*j)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += sdcu[2+3*(i+mxv*j)]; #pragma omp atomic cu[3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[3*(i+mxv*j)]; #pragma omp atomic cu[1+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[1+3*(i+mxv*j)]; #pragma omp atomic cu[2+3*(i+noff+nxv*(j+moff)+nxyv*loff)] += scu[2+3*(i+mxv*j)]; if (lm > mz) { #pragma omp atomic amu[6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(i+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(i+mxv*j+mxyv*(lm-1))]; } } } nm = nxv - noff; nm = mx+1 < nm ? mx+1 : nm; mm = nyv - moff; mm = my+1 < mm ? my+1 : mm; for (k = 0; k < ll; k++) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[6*(i+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[1+6*(i+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[2+6*(i+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[3+6*(i+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[4+6*(i+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(k+loff))] += samu[5+6*(i+mxyv*k)]; #pragma omp atomic dcu[3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[3*(i+mxyv*k)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[1+3*(i+mxyv*k)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*moff+nxyv*(k+loff))] += sdcu[2+3*(i+mxyv*k)]; #pragma omp atomic cu[3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[3*(i+mxyv*k)]; #pragma omp atomic cu[1+3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[1+3*(i+mxyv*k)]; #pragma omp atomic cu[2+3*(i+noff+nxv*moff+nxyv*(k+loff))] += scu[2+3*(i+mxyv*k)]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[1+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[2+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[3+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[4+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += samu[5+6*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[1+3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += sdcu[2+3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic cu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic cu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[1+3*(i+mxv*(mm-1)+mxyv*k)]; #pragma omp atomic cu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(k+loff))] += scu[2+3*(i+mxv*(mm-1)+mxyv*k)]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[1+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(mxv*j+mxyv*k)]; #pragma omp atomic dcu[2+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(mxv*j+mxyv*k)]; #pragma omp atomic cu[3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(mxv*j+mxyv*k)]; #pragma omp atomic cu[1+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(mxv*j+mxyv*k)]; #pragma omp atomic cu[2+3*(noff+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(mxv*j+mxyv*k)]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[1+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[2+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[3+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[4+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += samu[5+6*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[1+3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic dcu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += sdcu[2+3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic cu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic cu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[1+3*(nm-1+mxv*j+mxyv*k)]; #pragma omp atomic cu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(k+loff))] += scu[2+3*(nm-1+mxv*j+mxyv*k)]; } } } if (lm > mz) { for (i = 1; i < nn; i++) { #pragma omp atomic amu[6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[1+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[2+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[3+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[4+6*(i+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += samu[5+6*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[3*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxyv*(lm-1))]; #pragma omp atomic cu[3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[3*(i+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[1+3*(i+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*moff+nxyv*(lm+loff-1))] += scu[2+3*(i+mxyv*(lm-1))]; if (mm > my) { #pragma omp atomic amu[6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[1+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[2+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[3+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[4+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += samu[5+6*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[1+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += sdcu[2+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic cu[3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[1+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(i+noff+nxv*(mm+moff-1)+nxyv*(lm+loff-1))] += scu[2+3*(i+mxv*(mm-1)+mxyv*(lm-1))]; } } for (j = 0; j < mm; j++) { #pragma omp atomic amu[6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(noff+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(mxv*j+mxyv*(lm-1))]; if (nm > mx) { #pragma omp atomic amu[6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[1+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[1+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[2+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[2+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[3+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[3+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[4+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[4+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic amu[5+6*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += samu[5+6*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[1+3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic dcu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += sdcu[2+3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[1+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[1+3*(nm-1+mxv*j+mxyv*(lm-1))]; #pragma omp atomic cu[2+3*(nm+noff-1+nxv*(j+moff)+nxyv*(lm+loff-1))] += scu[2+3*(nm-1+mxv*j+mxyv*(lm-1))]; } } } } return; #undef MXV #undef MYV #undef MZV } /*--------------------------------------------------------------------*/ void cpporder3l(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int nx, int ny, int nz, int mx, int my, int mz, int mx1, int my1, int mz1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y,z grid in tiles of mx, my, mz linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 3D linear memory algorithm has 3 steps. first, one finds particles leaving tile and stores their number in each directon, location, and destination in ncl and ihole. second, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. finally, we copy the incoming particles from other tiles into ppart. input: all except ppbuff, ncl, ihole, irc output: ppart, ppbuff, kpic, ncl, ihole, irc ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppbuff[l][n][i] = i co-ordinate of particle n in tile l kpic[l] = number of particles in tile l ncl[l][i] = number of particles going to destination i, tile l ihole[l][:][0] = location of hole in array left by departing particle ihole[l][:][1] = direction destination of particle leaving hole all for tile l ihole[l][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 6 nppmx = maximum number of particles in tile nx/ny/nz = system length in x/y/z direction mx/my/mz = number of grids in sorting cell in x/y/z mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mz1 = (system length in z direction - 1)/mz + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxy1, mxyz1, noff, moff, loff, npp, ncoff; int i, j, k, l, ii, kx, ky, kz, ih, nh, ist, nn, mm, ll, isum; int ip, j1, j2, kxl, kxr, kk, kl, kr, lk, lr; float anx, any, anz, edgelx, edgely, edgelz, edgerx, edgery, edgerz; float dx, dy, dz; int ks[26]; mxy1 = mx1*my1; mxyz1 = mxy1*mz1; anx = (float) nx; any = (float) ny; anz = (float) nz; /* find and count particles leaving tiles and determine destination */ /* update ppart, ihole, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(j,k,l,noff,moff,loff,npp,nn,mm,ll,ih,nh,ist,dx,dy,dz,edgelx, \ edgely,edgelz,edgerx,edgery,edgerz) for (l = 0; l < mxyz1; l++) { loff = l/mxy1; k = l - mxy1*loff; loff = mz*loff; noff = k/mx1; moff = my*noff; noff = mx*(k - mx1*noff); npp = kpic[l]; nn = nx - noff; nn = mx < nn ? mx : nn; mm = ny - moff; mm = my < mm ? my : mm; ll = nz - loff; ll = mz < ll ? mz : ll; ih = 0; nh = 0; edgelx = noff; edgerx = noff + nn; edgely = moff; edgery = moff + mm; edgelz = loff; edgerz = loff + ll; /* clear counters */ for (j = 0; j < 26; j++) { ncl[j+26*l] = 0; } /* loop over particles in tile */ for (j = 0; j < npp; j++) { dx = ppart[idimp*(j+nppmx*l)]; dy = ppart[1+idimp*(j+nppmx*l)]; dz = ppart[2+idimp*(j+nppmx*l)]; /* find particles going out of bounds */ ist = 0; /* count how many particles are going in each direction in ncl */ /* save their address and destination in ihole */ /* use periodic boundary conditions and check for roundoff error */ /* ist = direction particle is going */ if (dx >= edgerx) { if (dx >= anx) ppart[idimp*(j+nppmx*l)] = dx - anx; ist = 2; } else if (dx < edgelx) { if (dx < 0.0) { dx += anx; if (dx < anx) ist = 1; else dx = 0.0; ppart[idimp*(j+nppmx*l)] = dx; } else { ist = 1; } } if (dy >= edgery) { if (dy >= any) ppart[1+idimp*(j+nppmx*l)] = dy - any; ist += 6; } else if (dy < edgely) { if (dy < 0.0) { dy += any; if (dy < any) ist += 3; else dy = 0.0; ppart[1+idimp*(j+nppmx*l)] = dy; } else { ist += 3; } } if (dz >= edgerz) { if (dz >= anz) ppart[2+idimp*(j+nppmx*l)] = dz - anz; ist += 18; } else if (dz < edgelz) { if (dz < 0.0) { dz += anz; if (dz < anz) ist += 9; else dz = 0.0; ppart[2+idimp*(j+nppmx*l)] = dz; } else { ist += 9; } } if (ist > 0) { ncl[ist+26*l-1] += 1; ih += 1; if (ih <= ntmax) { ihole[2*(ih+(ntmax+1)*l)] = j + 1; ihole[1+2*(ih+(ntmax+1)*l)] = ist; } else { nh = 1; } } } /* set error and end of file flag */ if (nh > 0) { *irc = ih; ih = -ih; } ihole[2*(ntmax+1)*l] = ih; } /* ihole overflow */ if (*irc > 0) return; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,l,isum,ist,nh,ip,j1,ii) for (l = 0; l < mxyz1; l++) { /* find address offset for ordered ppbuff array */ isum = 0; for (j = 0; j < 26; j++) { ist = ncl[j+26*l]; ncl[j+26*l] = isum; isum += ist; } nh = ihole[2*(ntmax+1)*l]; ip = 0; /* loop over particles leaving tile */ for (j = 0; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+(ntmax+1)*l)] - 1; ist = ihole[1+2*(j+1+(ntmax+1)*l)]; ii = ncl[ist+26*l-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[i+idimp*(ii+npbmx*l)] = ppart[i+idimp*(j1+nppmx*l)]; } } else { ip = 1; } ncl[ist+26*l-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[25+26*l]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,ii,kk,npp,kx,ky,kz,kl,kr,kxl,kxr,lk,ll,lr,ih,nh,ncoff, \ ist,j1,j2,ip,ks) for (l = 0; l < mxyz1; l++) { npp = kpic[l]; kz = l/mxy1; k = l - mxy1*kz; /* loop over tiles in z, assume periodic boundary conditions */ lk = kz*mxy1; /* find tile behind */ ll = kz - 1; if (ll < 0) ll += mz1; ll = ll*mxy1; /* find tile in front */ lr = kz + 1; if (lr >= mz1) lr -= mz1; lr = lr*mxy1; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1 ; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk + lk; ks[1] = kxl + kk + lk; ks[2] = kx + kr + lk; ks[3] = kxr + kr + lk; ks[4] = kxl + kr + lk; ks[5] = kx + kl + lk; ks[6] = kxr + kl + lk; ks[7] = kxl + kl + lk; ks[8] = kx + kk + lr; ks[9] = kxr + kk + lr; ks[10] = kxl + kk + lr; ks[11] = kx + kr + lr; ks[12] = kxr + kr + lr; ks[13] = kxl + kr + lr; ks[14] = kx + kl + lr; ks[15] = kxr + kl + lr; ks[16] = kxl + kl + lr; ks[17] = kx + kk + ll; ks[18] = kxr + kk + ll; ks[19] = kxl + kk + ll; ks[20] = kx + kr + ll; ks[21] = kxr + kr + ll; ks[22] = kxl + kr + ll; ks[23] = kx + kl + ll; ks[24] = kxr + kl + ll; ks[25] = kxl + kl + ll; /* loop over directions */ nh = ihole[2*(ntmax+1)*l]; ncoff = 0; ih = 0; ist = 0; j1 = 0; for (ii = 0; ii < 26; ii++) { if (ii > 0) ncoff = ncl[ii-1+26*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+26*ks[ii]] - ncoff; for (j = 0; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+(ntmax+1)*l)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(j1+nppmx*l)] = ppbuff[i+idimp*(j+ncoff+npbmx*ks[ii])]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; for (j = 0; j < ip; j++) { j1 = npp - j - 1; j2 = ihole[2*(nh-j+(ntmax+1)*l)] - 1; if (j1 > j2) { /* move particle only if it is below current hole */ for (i = 0; i < idimp; i++) { ppart[i+idimp*(j2+nppmx*l)] = ppart[i+idimp*(j1+nppmx*l)]; } } } npp -= ip; } kpic[l] = npp; } return; } /*--------------------------------------------------------------------*/ void cpporderf3l(float ppart[], float ppbuff[], int kpic[], int ncl[], int ihole[], int idimp, int nppmx, int mx1, int my1, int mz1, int npbmx, int ntmax, int *irc) { /* this subroutine sorts particles by x,y,z grid in tiles of mx, my, mz linear interpolation, with periodic boundary conditions tiles are assumed to be arranged in 3D linear memory the algorithm has 2 steps. first, a prefix scan of ncl is performed and departing particles are buffered in ppbuff in direction order. then we copy the incoming particles from other tiles into ppart. it assumes that the number, location, and destination of particles leaving a tile have been previously stored in ncl and ihole by the cgppushf3l procedure. input: all except ppbuff, irc output: ppart, ppbuff, kpic, ncl, irc ppart[m][n][0] = position x of particle n in tile m ppart[m][n][1] = position y of particle n in tile m ppart[m][n][2] = position z of particle n in tile m ppbuff[l][n][i] = i co-ordinate of particle n in tile l kpic[l] = number of particles in tile l ncl[l][i] = number of particles going to destination i, tile l ihole[l][:][0] = location of hole in array left by departing particle ihole[l][:][1] = direction destination of particle leaving hole all for tile l ihole[l][0][0] = ih, number of holes left (error, if negative) idimp = size of phase space = 6 nppmx = maximum number of particles in tile mx1 = (system length in x direction - 1)/mx + 1 my1 = (system length in y direction - 1)/my + 1 mz1 = (system length in z direction - 1)/mz + 1 npbmx = size of buffer array ppbuff ntmax = size of hole array for particles leaving tiles irc = maximum overflow, returned only if error occurs, when irc > 0 local data */ int mxy1, mxyz1, npp, ncoff; int i, j, k, l, ii, kx, ky, kz, ih, nh, ist, ll, isum; int ip, j1, j2, kxl, kxr, kk, kl, kr, lk, lr; int ks[26]; mxy1 = mx1*my1; mxyz1 = mxy1*mz1; /* buffer particles that are leaving tile: update ppbuff, ncl */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,l,isum,ist,nh,ip,j1,ii) for (l = 0; l < mxyz1; l++) { /* find address offset for ordered ppbuff array */ isum = 0; for (j = 0; j < 26; j++) { ist = ncl[j+26*l]; ncl[j+26*l] = isum; isum += ist; } nh = ihole[2*(ntmax+1)*l]; ip = 0; /* loop over particles leaving tile */ for (j = 0; j < nh; j++) { /* buffer particles that are leaving tile, in direction order */ j1 = ihole[2*(j+1+(ntmax+1)*l)] - 1; ist = ihole[1+2*(j+1+(ntmax+1)*l)]; ii = ncl[ist+26*l-1]; if (ii < npbmx) { for (i = 0; i < idimp; i++) { ppbuff[i+idimp*(ii+npbmx*l)] = ppart[i+idimp*(j1+nppmx*l)]; } } else { ip = 1; } ncl[ist+26*l-1] = ii + 1; } /* set error */ if (ip > 0) *irc = ncl[25+26*l]; } /* ppbuff overflow */ if (*irc > 0) return; /* copy incoming particles from buffer into ppart: update ppart, kpic */ /* loop over tiles */ #pragma omp parallel for \ private(i,j,k,l,ii,kk,npp,kx,ky,kz,kl,kr,kxl,kxr,lk,ll,lr,ih,nh,ncoff, \ ist,j1,j2,ip,ks) for (l = 0; l < mxyz1; l++) { npp = kpic[l]; kz = l/mxy1; k = l - mxy1*kz; /* loop over tiles in z, assume periodic boundary conditions */ lk = kz*mxy1; /* find tile behind */ ll = kz - 1; if (ll < 0) ll += mz1; ll = ll*mxy1; /* find tile in front */ lr = kz + 1; if (lr >= mz1) lr -= mz1; lr = lr*mxy1; ky = k/mx1; /* loop over tiles in y, assume periodic boundary conditions */ kk = ky*mx1; /* find tile above */ kl = ky - 1; if (kl < 0) kl += my1; kl = kl*mx1; /* find tile below */ kr = ky + 1; if (kr >= my1) kr -= my1; kr = kr*mx1; /* loop over tiles in x, assume periodic boundary conditions */ kx = k - ky*mx1; kxl = kx - 1 ; if (kxl < 0) kxl += mx1; kxr = kx + 1; if (kxr >= mx1) kxr -= mx1; /* find tile number for different directions */ ks[0] = kxr + kk + lk; ks[1] = kxl + kk + lk; ks[2] = kx + kr + lk; ks[3] = kxr + kr + lk; ks[4] = kxl + kr + lk; ks[5] = kx + kl + lk; ks[6] = kxr + kl + lk; ks[7] = kxl + kl + lk; ks[8] = kx + kk + lr; ks[9] = kxr + kk + lr; ks[10] = kxl + kk + lr; ks[11] = kx + kr + lr; ks[12] = kxr + kr + lr; ks[13] = kxl + kr + lr; ks[14] = kx + kl + lr; ks[15] = kxr + kl + lr; ks[16] = kxl + kl + lr; ks[17] = kx + kk + ll; ks[18] = kxr + kk + ll; ks[19] = kxl + kk + ll; ks[20] = kx + kr + ll; ks[21] = kxr + kr + ll; ks[22] = kxl + kr + ll; ks[23] = kx + kl + ll; ks[24] = kxr + kl + ll; ks[25] = kxl + kl + ll; /* loop over directions */ nh = ihole[2*(ntmax+1)*l]; ncoff = 0; ih = 0; ist = 0; j1 = 0; for (ii = 0; ii < 26; ii++) { if (ii > 0) ncoff = ncl[ii-1+26*ks[ii]]; /* ip = number of particles coming from direction ii */ ip = ncl[ii+26*ks[ii]] - ncoff; for (j = 0; j < ip; j++) { ih += 1; /* insert incoming particles into holes */ if (ih <= nh) { j1 = ihole[2*(ih+(ntmax+1)*l)] - 1; } /* place overflow at end of array */ else { j1 = npp; npp += 1; } if (j1 < nppmx) { for (i = 0; i < idimp; i++) { ppart[i+idimp*(j1+nppmx*l)] = ppbuff[i+idimp*(j+ncoff+npbmx*ks[ii])]; } } else { ist = 1; } } } /* set error */ if (ist > 0) *irc = j1+1; /* fill up remaining holes in particle array with particles from bottom */ if (ih < nh) { ip = nh - ih; for (j = 0; j < ip; j++) { j1 = npp - j - 1; j2 = ihole[2*(nh-j+(ntmax+1)*l)] - 1; if (j1 > j2) { /* move particle only if it is below current hole */ for (i = 0; i < idimp; i++) { ppart[i+idimp*(j2+nppmx*l)] = ppart[i+idimp*(j1+nppmx*l)]; } } } npp -= ip; } kpic[l] = npp; } return; } /*--------------------------------------------------------------------*/ void ccguard3l(float fxyz[], int nx, int ny, int nz, int nxe, int nye, int nze) { /* replicate extended periodic vector field fxyz linear interpolation nx/ny/nz = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 nze = third dimension of field arrays, must be >= nz+1 local data */ int j, k, l, nxye3, ll; nxye3 = 3*nxe*nye; /* copy edges of extended field */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye3*l; for (k = 0; k < ny; k++) { fxyz[3*(nx+nxe*k)+ll] = fxyz[3*nxe*k+ll]; fxyz[1+3*(nx+nxe*k)+ll] = fxyz[1+3*nxe*k+ll]; fxyz[2+3*(nx+nxe*k)+ll] = fxyz[2+3*nxe*k+ll]; } for (j = 0; j < nx; j++) { fxyz[3*(j+nxe*ny)+ll] = fxyz[3*j+ll]; fxyz[1+3*(j+nxe*ny)+ll] = fxyz[1+3*j+ll]; fxyz[2+3*(j+nxe*ny)+ll] = fxyz[2+3*j+ll]; } fxyz[3*(nx+nxe*ny)+ll] = fxyz[ll]; fxyz[1+3*(nx+nxe*ny)+ll] = fxyz[1+ll]; fxyz[2+3*(nx+nxe*ny)+ll] = fxyz[2+ll]; } #pragma omp for private(j,k) for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { fxyz[3*(j+nxe*k)+nxye3*nz] = fxyz[3*(j+nxe*k)]; fxyz[1+3*(j+nxe*k)+nxye3*nz] = fxyz[1+3*(j+nxe*k)]; fxyz[2+3*(j+nxe*k)+nxye3*nz] = fxyz[2+3*(j+nxe*k)]; } fxyz[3*(nx+nxe*k)+nxye3*nz] = fxyz[3*nxe*k]; fxyz[1+3*(nx+nxe*k)+nxye3*nz] = fxyz[1+3*nxe*k]; fxyz[2+3*(nx+nxe*k)+nxye3*nz] = fxyz[2+3*nxe*k]; } } for (j = 0; j < nx; j++) { fxyz[3*(j+nxe*ny)+nxye3*nz] = fxyz[3*j]; fxyz[1+3*(j+nxe*ny)+nxye3*nz] = fxyz[1+3*j]; fxyz[2+3*(j+nxe*ny)+nxye3*nz] = fxyz[2+3*j]; } fxyz[3*(nx+nxe*ny)+nxye3*nz] = fxyz[0]; fxyz[1+3*(nx+nxe*ny)+nxye3*nz] = fxyz[1]; fxyz[2+3*(nx+nxe*ny)+nxye3*nz] = fxyz[2]; return; } /*--------------------------------------------------------------------*/ void cacguard3l(float cu[], int nx, int ny, int nz, int nxe, int nye, int nze) { /* accumulate extended periodic vector field cu linear interpolation nx/ny/nz = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 nze = third dimension of field arrays, must be >= nz+1 local data */ int j, k, l, nxye3, ll; nxye3 = 3*nxe*nye; /* accumulate edges of extended field */ #pragma omp parallel { #pragma omp for \ private(j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye3*l; for (k = 0; k < ny; k++) { cu[3*nxe*k+ll] += cu[3*(nx+nxe*k)+ll]; cu[1+3*nxe*k+ll] += cu[1+3*(nx+nxe*k)+ll]; cu[2+3*nxe*k+ll] += cu[2+3*(nx+nxe*k)+ll]; cu[3*(nx+nxe*k)+ll] = 0.0; cu[1+3*(nx+nxe*k)+ll] = 0.0; cu[2+3*(nx+nxe*k)+ll] = 0.0; } for (j = 0; j < nx; j++) { cu[3*j+ll] += cu[3*(j+nxe*ny)+ll]; cu[1+3*j+ll] += cu[1+3*(j+nxe*ny)+ll]; cu[2+3*j+ll] += cu[2+3*(j+nxe*ny)+ll]; cu[3*(j+nxe*ny)+ll] = 0.0; cu[1+3*(j+nxe*ny)+ll] = 0.0; cu[2+3*(j+nxe*ny)+ll] = 0.0; } cu[ll] += cu[3*(nx+nxe*ny)+ll]; cu[1+ll] += cu[1+3*(nx+nxe*ny)+ll]; cu[2+ll] += cu[2+3*(nx+nxe*ny)+ll]; cu[3*(nx+nxe*ny)+ll] = 0.0; cu[1+3*(nx+nxe*ny)+ll] = 0.0; cu[2+3*(nx+nxe*ny)+ll] = 0.0; } #pragma omp for private(j,k) for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { cu[3*(j+nxe*k)] += cu[3*(j+nxe*k)+nxye3*nz]; cu[1+3*(j+nxe*k)] += cu[1+3*(j+nxe*k)+nxye3*nz]; cu[2+3*(j+nxe*k)] += cu[2+3*(j+nxe*k)+nxye3*nz]; cu[3*(j+nxe*k)+nxye3*nz] = 0.0; cu[1+3*(j+nxe*k)+nxye3*nz] = 0.0; cu[2+3*(j+nxe*k)+nxye3*nz] = 0.0; } cu[3*nxe*k] += cu[3*(nx+nxe*k)+nxye3*nz]; cu[1+3*nxe*k] += cu[1+3*(nx+nxe*k)+nxye3*nz]; cu[2+3*nxe*k] += cu[2+3*(nx+nxe*k)+nxye3*nz]; cu[3*(nx+nxe*k)+nxye3*nz] = 0.0; cu[1+3*(nx+nxe*k)+nxye3*nz] = 0.0; cu[2+3*(nx+nxe*k)+nxye3*nz] = 0.0; } } for (j = 0; j < nx; j++) { cu[3*j] += cu[3*(j+nxe*ny)+nxye3*nz]; cu[1+3*j] += cu[1+3*(j+nxe*ny)+nxye3*nz]; cu[2+3*j] += cu[2+3*(j+nxe*ny)+nxye3*nz]; cu[3*(j+nxe*ny)+nxye3*nz] = 0.0; cu[1+3*(j+nxe*ny)+nxye3*nz] = 0.0; cu[2+3*(j+nxe*ny)+nxye3*nz] = 0.0; } cu[0] += cu[3*(nx+nxe*ny)+nxye3*nz]; cu[1] += cu[1+3*(nx+nxe*ny)+nxye3*nz]; cu[2] += cu[2+3*(nx+nxe*ny)+nxye3*nz]; cu[3*(nx+nxe*ny)+nxye3*nz] = 0.0; cu[1+3*(nx+nxe*ny)+nxye3*nz] = 0.0; cu[2+3*(nx+nxe*ny)+nxye3*nz] = 0.0; return; } /*--------------------------------------------------------------------*/ void caguard3l(float q[], int nx, int ny, int nz, int nxe, int nye, int nze) { /* accumulate extended periodic scalar field q linear interpolation nx/ny/nz = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 nze = third dimension of field arrays, must be >= nz+1 local data */ int j, k, l, nxye, ll; nxye = nxe*nye; /* accumulate edges of extended field */ #pragma omp parallel { #pragma omp for \ private(j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye*l; for (k = 0; k < ny; k++) { q[nxe*k+ll] += q[nx+nxe*k+ll]; q[nx+nxe*k+ll] = 0.0; } for (j = 0; j < nx; j++) { q[j+ll] += q[j+nxe*ny+ll]; q[j+nxe*ny+ll] = 0.0; } q[ll] += q[nx+nxe*ny+ll]; q[nx+nxe*ny+ll] = 0.0; } #pragma omp for private(j,k) for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { q[j+nxe*k] += q[j+nxe*k+nxye*nz]; q[j+nxe*k+nxye*nz] = 0.0; } q[nxe*k] += q[nx+nxe*k+nxye*nz]; q[nx+nxe*k+nxye*nz] = 0.0; } } for (j = 0; j < nx; j++) { q[j] += q[j+nxe*ny+nxye*nz]; q[j+nxe*ny+nxye*nz] = 0.0; } q[0] += q[nx+nxe*ny+nxye*nz]; q[nx+nxe*ny+nxye*nz] = 0.0; return; } /*--------------------------------------------------------------------*/ void camcguard3l(float amu[], int nx, int ny, int nz, int nxe, int nye, int nze, int ndim) { /* accumulate extended periodic tensor field amu linear interpolation nx/ny/nz = system length in x/y direction nxe = first dimension of field arrays, must be >= nx+1 nye = second dimension of field arrays, must be >= ny+1 nze = third dimension of field arrays, must be >= nz+1 ndim = number of elements in tensor local data */ int i, j, k, l, nnxye, ll; nnxye = ndim*nxe*nye; /* accumulate edges of extended field */ #pragma omp parallel { #pragma omp for \ private(i,j,k,l,ll) for (l = 0; l < nz; l++) { ll = nnxye*l; for (k = 0; k < ny; k++) { for (i = 0; i < ndim; i++) { amu[i+ndim*nxe*k+ll] += amu[i+ndim*(nx+nxe*k)+ll]; amu[i+ndim*(nx+nxe*k)+ll] = 0.0; } } for (j = 0; j < nx; j++) { for (i = 0; i < ndim; i++) { amu[i+ndim*j+ll] += amu[i+ndim*(j+nxe*ny)+ll]; amu[i+ndim*(j+nxe*ny)+ll] = 0.0; } } for (i = 0; i < ndim; i++) { amu[i+ll] += amu[i+ndim*(nx+nxe*ny)+ll]; amu[i+ndim*(nx+nxe*ny)+ll] = 0.0; } } #pragma omp for private(i,j,k) for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { for (i = 0; i < ndim; i++) { amu[i+ndim*(j+nxe*k)] += amu[i+ndim*(j+nxe*k)+nnxye*nz]; amu[i+ndim*(j+nxe*k)+nnxye*nz] = 0.0; } } for (i = 0; i < ndim; i++) { amu[i+ndim*nxe*k] += amu[i+ndim*(nx+nxe*k)+nnxye*nz]; amu[i+ndim*(nx+nxe*k)+nnxye*nz] = 0.0; } } } for (j = 0; j < nx; j++) { for (i = 0; i < ndim; i++) { amu[i+ndim*j] += amu[i+ndim*(j+nxe*ny)+nnxye*nz]; amu[i+ndim*(j+nxe*ny)+nnxye*nz] = 0.0; } } for (i = 0; i < ndim; i++) { amu[i] += amu[i+ndim*(nx+nxe*ny)+nnxye*nz]; amu[i+ndim*(nx+nxe*ny)+nnxye*nz] = 0.0; } return; } /*--------------------------------------------------------------------*/ void cascfguard3l(float dcu[], float cus[], float q2m0, int nx, int ny, int nz, int nxe, int nye, int nze) { /* add scaled field to extended periodic field */ /* local data */ int i, j, k, l, nxye3, ll; nxye3 = 3*nxe*nye; #pragma omp for private(i,j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye3*l; for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { for (i = 0; i < 3; i++) { dcu[i+3*(j+nxe*k)+ll] -= q2m0*cus[i+3*(j+nxe*k)+ll]; } } } } return; } /*--------------------------------------------------------------------*/ void cfwpminmx3(float qe[], float qbme, float *wpmax, float *wpmin, int nx, int ny, int nz, int nxe, int nye, int nze) { /* calculates maximum and minimum plasma frequency. assumes guard cells have already been added qe = charge density for electrons qbme = charge/mass ratio for electrons wpmax/wpmin = maximum/minimum plasma frequency nx/ny/nz = system length in x/y/z direction nxe = first dimension of charge arrays, nxe must be >= nx nye = second dimension of charge arrays, nye must be >= ny nze = third dimension of charge arrays, nze must be >= nz local data */ int j, k, l, nxye, ll; float tpmax, tpmin, at1; nxye = nxe*nye; tpmax = qbme*qe[0]; tpmin = tpmax; #pragma omp for private(j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye*l; for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { at1 = qbme*qe[j+nxe*k+ll]; #pragma omp critical tpmax = at1 > tpmax ? at1 : tpmax; #pragma omp critical tpmin = at1 < tpmin ? at1 : tpmin; } } } *wpmax = tpmax; *wpmin = tpmin; return; } /*--------------------------------------------------------------------*/ void cmpois33(float complex q[], float complex fxyz[], int isign, float complex ffc[], float ax, float ay, float az, float affp, float *we, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { /* this subroutine solves 3d poisson's equation in fourier space for force/charge (or convolution of electric field over particle shape) with periodic boundary conditions. for isign = 0, output: ffc input: isign,ax,ay,az,affp,nx,ny,nz,nxvh,nyv,nzv,nxhd,nyhd,nzhd for isign = -1, output: fxyz, we input: q,ffc,isign,nx,ny,nz,nxvh,nyv,nzv,nxhd,nyhd,nzhd approximate flop count is: 59*nxc*nyc*nzc + 26*(nxc*nyc + nxc*nzc + nyc*nzc) where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 if isign = 0, form factor array is prepared if isign is not equal to 0, force/charge is calculated equation used is: fx[kz][ky][kx] = -sqrt(-1)*kx*g[kz][ky][kx]*s[kz][ky][kx], fy[kz][ky][kx] = -sqrt(-1)*ky*g[kz][ky][kx]*s[kz][ky][kx], fz[kz][ky][kx] = -sqrt(-1)*kz*g[kz][ky][kx]*s[kz][ky][kx], where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, g[kz][ky][kx] = (affp/(kx**2+ky**2+kz**2))*s[kz][ky][kx], s[kz][ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2+(kz*az)**2)/2), except for fx(kx=pi) = fy(kx=pi) = fz(kx=pi) = 0, fx(ky=pi) = fy(ky=pi) = fx(ky=pi) = 0, fx(kz=pi) = fy(kz=pi) = fz(kz=pi) = 0, fx(kx=0,ky=0,kz=0) = fy(kx=0,ky=0,kz=0) = fz(kx=0,ky=0,kz=0) = 0. q[l][k][j] = complex charge density for fourier mode (j,k,l) fxyz[l][k][j][0] = x component of complex force/charge fxyz[l][k][j][1] = y component of complex force/charge fxyz[l][k][j][2] = z component of complex force/charge all for fourier mode (j,k,l) cimag(ffc[l][k][j]) = finite-size particle shape factor s for fourier mode (j,k,l) creal(ffc[l][k][j]) = potential green's function g for fourier mode (j,k,l) ax/ay/az = half-width of particle in x/y/z direction affp = normalization constant = nx*ny*nz/np, where np=number of particles electric field energy is also calculated, using we = nx*ny*nz*sum((affp/(kx**2+ky**2+kz**2))* |q[kz][ky][kx]*s[kz][ky][kx]|**2) nx/ny/nz = system length in x/y/z direction nxvh = first dimension of field arrays, must be >= nxh nyv = second dimension of field arrays, must be >= ny nzv = third dimension of field arrays, must be >= nz nxhd = first dimension of form factor array, must be >= nxh nyhd = second dimension of form factor array, must be >= nyh nzhd = third dimension of form factor array, must be >= nzh local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kk, kj, ll, lj, nxyhd, nxvyh; float dnx, dny, dnz, dkx, dky, dkz, at1, at2, at3, at4, at5, at6; float complex zero, zt1, zt2; double wp, sum1, sum2; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxyhd = nxhd*nyhd; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; if (isign != 0) goto L40; /* prepare form factor array */ for (l = 0; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; at1 = dkz*dkz; at2 = pow((dkz*az),2); for (k = 0; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; at3 = dky*dky + at1; at4 = pow((dky*ay),2) + at2; for (j = 0; j < nxh; j++) { dkx = dnx*(float) j; at5 = dkx*dkx + at3; at6 = exp(-0.5*(pow((dkx*ax),2) + at4)); if (at5==0.0) { ffc[j+kk+ll] = affp + 1.0*_Complex_I; } else { ffc[j+kk+ll] = (affp*at6/at5) + at6*_Complex_I; } } } } return; /* calculate force/charge and sum field energy */ L40: sum1 = 0.0; /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,ll,lj,kk,kj,dky,dkz,at1,at2,at3,at4,zt1,zt2,wp) \ reduction(+:sum1) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; lj = nxvyh*l; l1 = nxvyh*nz - lj; wp = 0.0; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j+kk+ll])*cimagf(ffc[j+kk+ll]); at2 = at1*dnx*(float) j; at3 = dky*at1; at4 = dkz*at1; zt1 = cimagf(q[j+kj+lj]) - crealf(q[j+kj+lj])*_Complex_I; zt2 = cimagf(q[j+k1+lj]) - crealf(q[j+k1+lj])*_Complex_I; fxyz[3*(j+kj+lj)] = at2*zt1; fxyz[1+3*(j+kj+lj)] = at3*zt1; fxyz[2+3*(j+kj+lj)] = at4*zt1; fxyz[3*(j+k1+lj)] = at2*zt2; fxyz[1+3*(j+k1+lj)] = -at3*zt2; fxyz[2+3*(j+k1+lj)] = at4*zt2; zt1 = cimagf(q[j+kj+l1]) - crealf(q[j+kj+l1])*_Complex_I; zt2 = cimagf(q[j+k1+l1]) - crealf(q[j+k1+l1])*_Complex_I; fxyz[3*(j+kj+l1)] = at2*zt1; fxyz[1+3*(j+kj+l1)] = at3*zt1; fxyz[2+3*(j+kj+l1)] = -at4*zt1; fxyz[3*(j+k1+l1)] = at2*zt2; fxyz[1+3*(j+k1+l1)] = -at3*zt2; fxyz[2+3*(j+k1+l1)] = -at4*zt2; wp += at1*(q[j+kj+lj]*conjf(q[j+kj+lj]) + q[j+k1+lj]*conjf(q[j+k1+lj]) + q[j+kj+l1]*conjf(q[j+kj+l1]) + q[j+k1+l1]*conjf(q[j+k1+l1])); } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; at1 = crealf(ffc[kk+ll])*cimagf(ffc[kk+ll]); at3 = at1*dny*(float) k; at4 = dkz*at1; zt1 = cimagf(q[kj+lj]) - crealf(q[kj+lj])*_Complex_I; zt2 = cimagf(q[kj+l1]) - crealf(q[kj+l1])*_Complex_I; fxyz[3*(kj+lj)] = zero; fxyz[1+3*(kj+lj)] = at3*zt1; fxyz[2+3*(kj+lj)] = at4*zt1; fxyz[3*(k1+lj)] = zero; fxyz[1+3*(k1+lj)] = zero; fxyz[2+3*(k1+lj)] = zero; fxyz[3*(kj+l1)] = zero; fxyz[1+3*(kj+l1)] = at3*zt2; fxyz[2+3*(kj+l1)] = -at4*zt2; fxyz[3*(k1+l1)] = zero; fxyz[1+3*(k1+l1)] = zero; fxyz[2+3*(k1+l1)] = zero; wp += at1*(q[kj+lj]*conjf(q[kj+lj]) + q[kj+l1]*conjf(q[kj+l1])); } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j+ll])*cimagf(ffc[j+ll]); at2 = at1*dnx*(float) j; at4 = dkz*at1; zt1 = cimagf(q[j+lj]) - crealf(q[j+lj])*_Complex_I; zt2 = cimagf(q[j+l1]) - crealf(q[j+l1])*_Complex_I; fxyz[3*(j+lj)] = at2*zt1; fxyz[1+3*(j+lj)] = zero; fxyz[2+3*(j+lj)] = at4*zt1; fxyz[3*(j+k1+lj)] = zero; fxyz[1+3*(j+k1+lj)] = zero; fxyz[2+3*(j+k1+lj)] = zero; fxyz[3*(j+l1)] = at2*zt2; fxyz[1+3*(j+l1)] = zero; fxyz[2+3*(j+l1)] = -at4*zt2; fxyz[3*(j+k1+l1)] = zero; fxyz[1+3*(j+k1+l1)] = zero; fxyz[2+3*(j+k1+l1)] = zero; wp += at1*(q[j+lj]*conjf(q[j+lj]) + q[j+l1]*conjf(q[j+l1])); } /* mode numbers kx = 0, nx/2 */ at1 = crealf(ffc[ll])*cimagf(ffc[ll]); at4 = dkz*at1; zt1 = cimagf(q[lj]) - crealf(q[lj])*_Complex_I; fxyz[3*lj] = zero; fxyz[1+3*lj] = zero; fxyz[2+3*lj] = at4*zt1; fxyz[3*(k1+lj)] = zero; fxyz[1+3*(k1+lj)] = zero; fxyz[2+3*(k1+lj)] = zero; fxyz[3*l1] = zero; fxyz[1+3*l1] = zero; fxyz[2+3*l1] = zero; fxyz[3*(k1+l1)] = zero; fxyz[1+3*(k1+l1)] = zero; fxyz[2+3*(k1+l1)] = zero; wp += at1*(q[lj]*conjf(q[lj])); sum1 += wp; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; sum2 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,dky,at1,at2,at3,zt1,zt2,wp) \ reduction(+:sum2) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j+kk])*cimagf(ffc[j+kk]); at2 = at1*dnx*(float) j; at3 = dky*at1; zt1 = cimagf(q[j+kj]) - crealf(q[j+kj])*_Complex_I; zt2 = cimagf(q[j+k1]) - crealf(q[j+k1])*_Complex_I; fxyz[3*(j+kj)] = at2*zt1; fxyz[1+3*(j+kj)] = at3*zt1; fxyz[2+3*(j+kj)] = zero; fxyz[3*(j+k1)] = at2*zt2; fxyz[1+3*(j+k1)] = -at3*zt2; fxyz[2+3*(j+k1)] = zero; fxyz[3*(j+kj+l1)] = zero; fxyz[1+3*(j+kj+l1)] = zero; fxyz[2+3*(j+kj+l1)] = zero; fxyz[3*(j+k1+l1)] = zero; fxyz[1+3*(j+k1+l1)] = zero; fxyz[2+3*(j+k1+l1)] = zero; wp += at1*(q[j+kj]*conjf(q[j+kj]) + q[j+k1]*conjf(q[j+k1])); } /* mode numbers kx = 0, nx/2 */ at1 = crealf(ffc[kk])*cimagf(ffc[kk]); at3 = at1*dny*(float) k; zt1 = cimagf(q[kj]) - crealf(q[kj])*_Complex_I; fxyz[3*kj] = zero; fxyz[1+3*kj] = at3*zt1; fxyz[2+3*kj] = zero; fxyz[3*k1] = zero; fxyz[1+3*k1] = zero; fxyz[2+3*k1] = zero; fxyz[3*(kj+l1)] = zero; fxyz[1+3*(kj+l1)] = zero; fxyz[2+3*(kj+l1)] = zero; fxyz[3*(k1+l1)] = zero; fxyz[1+3*(k1+l1)] = zero; fxyz[2+3*(k1+l1)] = zero; wp += at1*(q[kj]*conjf(q[kj])); sum2 += wp; } wp = 0.0; /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at1 = crealf(ffc[j])*cimagf(ffc[j]); at2 = at1*dnx*(float) j; zt1 = cimagf(q[j]) - crealf(q[j])*_Complex_I; fxyz[3*j] = at2*zt1; fxyz[1+3*j] = zero; fxyz[2+3*j] = zero; fxyz[3*(j+k1)] = zero; fxyz[1+3*(j+k1)] = zero; fxyz[2+3*(j+k1)] = zero; fxyz[3*(j+l1)] = zero; fxyz[1+3*(j+l1)] = zero; fxyz[2+3*(j+l1)] = zero; fxyz[3*(j+k1+l1)] = zero; fxyz[1+3*(j+k1+l1)] = zero; fxyz[2+3*(j+k1+l1)] = zero; wp += at1*(q[j]*conjf(q[j])); } fxyz[0] = zero; fxyz[1] = zero; fxyz[2] = zero; fxyz[3*k1] = zero; fxyz[1+3*k1] = zero; fxyz[2+3*k1] = zero; fxyz[3*l1] = zero; fxyz[1+3*l1] = zero; fxyz[2+3*l1] = zero; fxyz[3*(k1+l1)] = zero; fxyz[1+3*(k1+l1)] = zero; fxyz[2+3*(k1+l1)] = zero; *we = (sum1 + sum2 + wp)*((float) nx)*((float) ny)*((float) nz); return; } /*--------------------------------------------------------------------*/ void cmcuperp3(float complex cu[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { /* this subroutine calculates the transverse current in fourier space input: all, output: cu approximate flop count is: 100*nxc*nyc*nzc + 36*(nxc*nyc + nxc*nzc + nyc*nzc) and (nx/2)*nyc*nzc divides where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 the transverse current is calculated using the equation: cux[kz][ky][kx] = cux[kz][ky][kx] - kx*(kx*cux[kz][ky][kx]+ky*cuy[kz][ky][kx] + kz*cuz[kz][ky][kx])/(kx*kx+ky*ky+kz*kz) cuy[kz][ky][kx] = cuy[kz][ky][kx] - ky*(kx*cux([kz][ky][kx]+ky*cuy[kz][ky][kx] + kz*cuz[kz][ky][kx])/(kx*kx+ky*ky+kz*kz) cuz[kz][ky][kx] = cuz[kz][ky][kx] - kz*(kx*cux[kz][ky][kx]+ky*cuy[kz][ky][kx] + kz*cuz[kz][ky][kx])/(kx*kx+ky*ky+kz*kz) where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, except for cux(kx=pi) = cuy(kx=pi) = cuz(kx=pi) = 0, cux(ky=pi) = cuy(ky=pi) = cux(ky=pi) = 0, cux(kz=pi) = cuy(kz=pi) = cuz(kz=pi) = 0, cux(kx=0,ky=0,kz=0) = cuy(kx=0,ky=0,kz=0) = cuz(kx=0,ky=0,kz=0) = 0. cu[l][k][j][i] = complex current density for fourier mode (j,k,l) nx/ny/nz = system length in x/y/z direction nxvh = second dimension of field arrays, must be >= nxh nyv = third dimension of field arrays, must be >= ny nzv = fourth dimension of field arrays, must be >= nz local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kj, lj, nxvyh; float dnx, dny, dnz, dkx, dky, dkz, dky2, dkz2, dkyz2, at1; float complex zero, zt1; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; /* calculate transverse part of current */ /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,lj,kj,dkx,dky,dkz,dkz2,dkyz2,at1,zt1) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; lj = nxvyh*l; l1 = nxvyh*nz - lj; dkz2 = dkz*dkz; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dkyz2 = dky*dky + dkz2; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkyz2); zt1 = at1*(dkx*cu[3*(j+kj+lj)] + dky*cu[1+3*(j+kj+lj)] + dkz*cu[2+3*(j+kj+lj)]); cu[3*(j+kj+lj)] -= dkx*zt1; cu[1+3*(j+kj+lj)] -= dky*zt1; cu[2+3*(j+kj+lj)] -= dkz*zt1; zt1 = at1*(dkx*cu[3*(j+k1+lj)] - dky*cu[1+3*(j+k1+lj)] + dkz*cu[2+3*(j+k1+lj)]); cu[3*(j+k1+lj)] -= dkx*zt1; cu[1+3*(j+k1+lj)] += dky*zt1; cu[2+3*(j+k1+lj)] -= dkz*zt1; zt1 = at1*(dkx*cu[3*(j+kj+l1)] + dky*cu[1+3*(j+kj+l1)] - dkz*cu[2+3*(j+kj+l1)]); cu[3*(j+kj+l1)] -= dkx*zt1; cu[1+3*(j+kj+l1)] -= dky*zt1; cu[2+3*(j+kj+l1)] += dkz*zt1; zt1 = at1*(dkx*cu[3*(j+k1+l1)] - dky*cu[1+3*(j+k1+l1)] - dkz*cu[2+3*(j+k1+l1)]); cu[3*(j+k1+l1)] -= dkx*zt1; cu[1+3*(j+k1+l1)] += dky*zt1; cu[2+3*(j+k1+l1)] += dkz*zt1; } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kj = nxvh*k; k1 = nxvh*ny - kj; dky = dny*(float) k; at1 = 1.0/(dky*dky + dkz2); zt1 = at1*(dky*cu[1+3*(kj+lj)] + dkz*cu[2+3*(kj+lj)]); cu[1+3*(kj+lj)] -= dky*zt1; cu[2+3*(kj+lj)] -= dkz*zt1; cu[3*(k1+lj)] = zero; cu[1+3*(k1+lj)] = zero; cu[2+3*(k1+lj)] = zero; zt1 = at1*(dky*cu[1+3*(kj+l1)] - dkz*cu[2+3*(kj+l1)]); cu[1+3*(kj+l1)] -= dky*zt1; cu[2+3*(kj+l1)] += dkz*zt1; cu[3*(k1+l1)] = zero; cu[1+3*(k1+l1)] = zero; cu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkz2); zt1 = at1*(dkx*cu[3*(j+lj)] + dkz*cu[2+3*(j+lj)]); cu[3*(j+lj)] -= dkx*zt1; cu[2+3*(j+lj)] -= dkz*zt1; cu[3*(j+k1+lj)] = zero; cu[1+3*(j+k1+lj)] = zero; cu[2+3*(j+k1+lj)] = zero; zt1 = at1*(dkx*cu[3*(j+l1)] - dkz*cu[2+3*(j+l1)]); cu[3*(j+l1)] -= dkx*zt1; cu[2+3*(j+l1)] += dkz*zt1; cu[3*(j+k1+l1)] = zero; cu[1+3*(j+k1+l1)] = zero; cu[2+3*(j+k1+l1)] = zero; } /* mode numbers kx = 0, nx/2 */ cu[2+3*lj] = zero; cu[3*(k1+lj)] = zero; cu[1+3*(k1+lj)] = zero; cu[2+3*(k1+lj)] = zero; cu[3*l1] = zero; cu[1+3*l1] = zero; cu[2+3*l1] = zero; cu[3*(k1+l1)] = zero; cu[1+3*(k1+l1)] = zero; cu[2+3*(k1+l1)] = zero; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; #pragma omp parallel for \ private(j,k,k1,kj,dky,dky2,dkx,at1,zt1) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dky2 = dky*dky; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dky2); zt1 = at1*(dkx*cu[3*(j+kj)] + dky*cu[1+3*(j+kj)]); cu[3*(j+kj)] -= dkx*zt1; cu[1+3*(j+kj)] -= dky*zt1; zt1 = at1*(dkx*cu[3*(j+k1)]- dky*cu[1+3*(j+k1)]); cu[3*(j+k1)] -= dkx*zt1; cu[1+3*(j+k1)] += dky*zt1; cu[3*(j+kj+l1)] = zero; cu[1+3*(j+kj+l1)] = zero; cu[2+3*(j+kj+l1)] = zero; cu[3*(j+k1+l1)] = zero; cu[1+3*(j+k1+l1)] = zero; cu[2+3*(j+k1+l1)] = zero; } /* mode numbers kx = 0, nx/2 */ cu[1+3*kj] = zero; cu[3*k1] = zero; cu[1+3*k1] = zero; cu[2+3*k1] = zero; cu[3*(kj+l1)] = zero; cu[1+3*(kj+l1)] = zero; cu[2+3*(kj+l1)] = zero; cu[3*(k1+l1)] = zero; cu[1+3*(k1+l1)] = zero; cu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { cu[3*j] = zero; cu[3*(j+k1)] = zero; cu[1+3*(j+k1)] = zero; cu[2+3*(j+k1)] = zero; cu[3*(j+l1)] = zero; cu[1+3*(j+l1)] = zero; cu[2+3*(j+l1)] = zero; cu[3*(j+k1+l1)] = zero; cu[1+3*(j+k1+l1)] = zero; cu[2+3*(j+k1+l1)] = zero; } cu[0] = zero; cu[1] = zero; cu[2] = zero; cu[3*k1] = zero; cu[1+3*k1] = zero; cu[2+3*k1] = zero; cu[3*l1] = zero; cu[1+3*l1] = zero; cu[2+3*l1] = zero; cu[3*(k1+l1)] = zero; cu[1+3*(k1+l1)] = zero; cu[2+3*(k1+l1)] = zero; return; } /*--------------------------------------------------------------------*/ void cmbbpois33(float complex cu[], float complex bxyz[], float complex ffc[], float ci, float *wm, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { /* this subroutine solves 3d poisson's equation in fourier space for magnetic field (or convolution of magnetic field over particle shape) with periodic boundary conditions. input: cu,ffc,ci,nx,ny,nz,nxvh,nyv,nzv,nxhd,nyhd,nzhd output: bxyz, wm approximate flop count is: 193*nxc*nyc*nzc + 84*(nxc*nyc + nxc*nzc + nyc*nzc) where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 the magnetic field is calculated using the equations: bx[kz][ky][kx] = ci*ci*sqrt(-1)*g[kz][ky][kx]* (ky*cuz[kz][ky][kx]-kz*cuy[kz][ky][kx])*s[kz][ky][kx], by[kz][ky][kx] = ci*ci*sqrt(-1)*g[kz][ky][kx]* (kz*cux[kz][ky][kx]-kx*cuz[kz][ky][kx])*s[kz][ky][kx], bz[kz][ky][kx] = ci*ci*sqrt(-1)*g[kz][ky][kx]* (kx*cuy[kz][ky][kx]-ky*cux[kz][ky][kx])*s[kz][ky][kx], where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, g[kz][ky][kx] = (affp/(kx**2+ky**2+kz**2))*s[kz][ky][kx], s[kz][ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2+(kz*az)**2)/2), except for bx(kx=pi) = by(kx=pi) = bz(kx=pi) = 0, bx(ky=pi) = by(ky=pi) = bx(ky=pi) = 0, bx(kz=pi) = by(kz=pi) = bz(kz=pi) = 0, bx(kx=0,ky=0,kz=0) = by(kx=0,ky=0,kz=0) = bz(kx=0,ky=0,kz=0) = 0. cu[l][k][j][i] = complex current density for fourier mode (j,k,l) bxy[l][k][j][0] = x component of complex magnetic field bxy[l][k][j][1] = y component of complex magnetic field bxy[l][k][j][2] = z component of complex magnetic field all for fourier mode (j,k,l) aimag(ffc[l][k][j]) = finite-size particle shape factor s for fourier mode (j,k,l) real(ffc[l][k][j]) = potential green's function g for fourier mode (j,k,l) ci = reciprocal of velocity of light magnetic field energy is also calculated, using wm = nx*ny*nz*sum((affp/(kx**2+ky**2+kz**2))*ci*ci |cu[kz][ky][kx]*s[kz][ky][kx]|**2), where affp = normalization constant = nx*ny/np, where np=number of particles this expression is valid only if the current is divergence-free nx/ny/nz = system length in x/y/z direction nxvh = second dimension of field arrays, must be >= nxh nyv = third dimension of field arrays, must be >= ny nzv = fourth dimension of field arrays, must be >= nz nxhd = dimension of form factor array, must be >= nxh nyhd = second dimension of form factor array, must be >= nyh nzhd = third dimension of form factor array, must be >= nzh local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kk, kj, ll, lj, nxyhd, nxvyh; float dnx, dny, dnz, dky, dkz, ci2, at1, at2, at3, at4; float complex zero, zt1, zt2, zt3; double wp, sum1, sum2; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxyhd = nxhd*nyhd; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; ci2 = ci*ci; /* calculate smoothed magnetic field and sum field energy */ sum1 = 0.0; /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,ll,lj,kk,kj,dky,dkz,at1,at2,at3,at4,zt1,zt2,zt3,wp) \ reduction(+:sum1) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; lj = nxvyh*l; l1 = nxvyh*nz - lj; wp = 0.0; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; for (j = 1; j < nxh; j++) { at1 = ci2*crealf(ffc[j+kk+ll])*cimagf(ffc[j+kk+ll]); at2 = at1*dnx*(float) j; at3 = dky*at1; at4 = dkz*at1; zt1 = -cimagf(cu[2+3*(j+kj+lj)]) + crealf(cu[2+3*(j+kj+lj)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+kj+lj)]) + crealf(cu[1+3*(j+kj+lj)])*_Complex_I; zt3 = -cimagf(cu[3*(j+kj+lj)]) + crealf(cu[3*(j+kj+lj)])*_Complex_I; bxyz[3*(j+kj+lj)] = at3*zt1 - at4*zt2; bxyz[1+3*(j+kj+lj)] = at4*zt3 - at2*zt1; bxyz[2+3*(j+kj+lj)] = at2*zt2 - at3*zt3; zt1 = -cimagf(cu[2+3*(j+k1+lj)]) + crealf(cu[2+3*(j+k1+lj)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+k1+lj)]) + crealf(cu[1+3*(j+k1+lj)])*_Complex_I; zt3 = -cimagf(cu[3*(j+k1+lj)]) + crealf(cu[3*(j+k1+lj)])*_Complex_I; bxyz[3*(j+k1+lj)] = -at3*zt1 - at4*zt2; bxyz[1+3*(j+k1+lj)] = at4*zt3 - at2*zt1; bxyz[2+3*(j+k1+lj)] = at2*zt2 + at3*zt3; zt1 = -cimagf(cu[2+3*(j+kj+l1)]) + crealf(cu[2+3*(j+kj+l1)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+kj+l1)]) + crealf(cu[1+3*(j+kj+l1)])*_Complex_I; zt3 = -cimagf(cu[3*(j+kj+l1)]) + crealf(cu[3*(j+kj+l1)])*_Complex_I; bxyz[3*(j+kj+l1)] = at3*zt1 + at4*zt2; bxyz[1+3*(j+kj+l1)] = -at4*zt3 - at2*zt1; bxyz[2+3*(j+kj+l1)] = at2*zt2 - at3*zt3; zt1 = -cimagf(cu[2+3*(j+k1+l1)]) + crealf(cu[2+3*(j+k1+l1)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+k1+l1)]) + crealf(cu[1+3*(j+k1+l1)])*_Complex_I; zt3 = -cimagf(cu[3*(j+k1+l1)]) + crealf(cu[3*(j+k1+l1)])*_Complex_I; bxyz[3*(j+k1+l1)] = -at3*zt1 + at4*zt2; bxyz[1+3*(j+k1+l1)] = -at4*zt3 - at2*zt1; bxyz[2+3*(j+k1+l1)] = at2*zt2 + at3*zt3; wp += at1*(cu[3*(j+kj+lj)]*conjf(cu[3*(j+kj+lj)]) + cu[1+3*(j+kj+lj)]*conjf(cu[1+3*(j+kj+lj)]) + cu[2+3*(j+kj+lj)]*conjf(cu[2+3*(j+kj+lj)]) + cu[3*(j+k1+lj)]*conjf(cu[3*(j+k1+lj)]) + cu[1+3*(j+k1+lj)]*conjf(cu[1+3*(j+k1+lj)]) + cu[2+3*(j+k1+lj)]*conjf(cu[2+3*(j+k1+lj)]) + cu[3*(j+kj+l1)]*conjf(cu[3*(j+kj+l1)]) + cu[1+3*(j+kj+l1)]*conjf(cu[1+3*(j+kj+l1)]) + cu[2+3*(j+kj+l1)]*conjf(cu[2+3*(j+kj+l1)]) + cu[3*(j+k1+l1)]*conjf(cu[3*(j+k1+l1)]) + cu[1+3*(j+k1+l1)]*conjf(cu[1+3*(j+k1+l1)]) + cu[2+3*(j+k1+l1)]*conjf(cu[2+3*(j+k1+l1)])); } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; at1 = ci2*crealf(ffc[kk+ll])*cimagf(ffc[kk+ll]); at3 = at1*dny*(float) k; at4 = dkz*at1; zt1 = -cimagf(cu[2+3*(kj+lj)]) + crealf(cu[2+3*(kj+lj)])*_Complex_I; zt2 = -cimagf(cu[1+3*(kj+lj)]) + crealf(cu[1+3*(kj+lj)])*_Complex_I; zt3 = -cimagf(cu[3*(kj+lj)]) + crealf(cu[3*(kj+lj)])*_Complex_I; bxyz[3*(kj+lj)] = at3*zt1 - at4*zt2; bxyz[1+3*(kj+lj)] = at4*zt3; bxyz[2+3*(kj+lj)] = -at3*zt3; bxyz[3*(k1+lj)] = zero; bxyz[1+3*(k1+lj)] = zero; bxyz[2+3*(k1+lj)] = zero; zt1 = -cimagf(cu[2+3*(kj+l1)]) + crealf(cu[2+3*(kj+l1)])*_Complex_I; zt2 = -cimagf(cu[1+3*(kj+l1)]) + crealf(cu[1+3*(kj+l1)])*_Complex_I; zt3 = -cimagf(cu[3*(kj+l1)]) + crealf(cu[3*(kj+l1)])*_Complex_I; bxyz[3*(kj+l1)] = at3*zt1 + at4*zt2; bxyz[1+3*(kj+l1)] = -at4*zt3; bxyz[2+3*(kj+l1)] = -at3*zt3; bxyz[3*(k1+l1)] = zero; bxyz[1+3*(k1+l1)] = zero; bxyz[2+3*(k1+l1)] = zero; wp += at1*(cu[3*(kj+lj)]*conjf(cu[3*(kj+lj)]) + cu[1+3*(kj+lj)]*conjf(cu[1+3*(kj+lj)]) + cu[2+3*(kj+lj)]*conjf(cu[2+3*(kj+lj)]) + cu[3*(kj+l1)]*conjf(cu[3*(kj+l1)]) + cu[1+3*(kj+l1)]*conjf(cu[1+3*(kj+l1)]) + cu[2+3*(kj+l1)]*conjf(cu[2+3*(kj+l1)])); } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at1 = ci2*crealf(ffc[j+ll])*cimagf(ffc[j+ll]); at2 = at1*dnx*(float) j; at4 = dkz*at1; zt1 = -cimagf(cu[2+3*(j+lj)]) + crealf(cu[2+3*(j+lj)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+lj)]) + crealf(cu[1+3*(j+lj)])*_Complex_I; zt3 = -cimagf(cu[3*(j+lj)]) + crealf(cu[3*(j+lj)])*_Complex_I; bxyz[3*(j+lj)] = -at4*zt2; bxyz[1+3*(j+lj)] = at4*zt3 - at2*zt1; bxyz[2+3*(j+lj)] = at2*zt2; bxyz[3*(j+k1+lj)] = zero; bxyz[1+3*(j+k1+lj)] = zero; bxyz[2+3*(j+k1+lj)] = zero; zt1 = -cimagf(cu[2+3*(j+l1)]) + crealf(cu[2+3*(j+l1)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+l1)]) + crealf(cu[1+3*(j+l1)])*_Complex_I; zt3 = -cimagf(cu[3*(j+l1)]) + crealf(cu[3*(j+l1)])*_Complex_I; bxyz[3*(j+l1)] = at4*zt2; bxyz[1+3*(j+l1)] = -at4*zt3 - at2*zt1; bxyz[2+3*(j+l1)] = at2*zt2; bxyz[3*(j+k1+l1)] = zero; bxyz[1+3*(j+k1+l1)] = zero; bxyz[2+3*(j+k1+l1)] = zero; wp += at1*(cu[3*(j+lj)]*conjf(cu[3*(j+lj)]) + cu[1+3*(j+lj)]*conjf(cu[1+3*(j+lj)]) + cu[2+3*(j+lj)]*conjf(cu[2+3*(j+lj)]) + cu[3*(j+l1)]*conjf(cu[3*(j+l1)]) + cu[1+3*(j+l1)]*conjf(cu[1+3*(j+l1)]) + cu[2+3*(j+l1)]*conjf(cu[2+3*(j+l1)])); } /* mode numbers kx = 0, nx/2 */ at1 = ci2*crealf(ffc[ll])*cimagf(ffc[ll]); at4 = dkz*at1; zt2 = -cimagf(cu[1+3*(lj)]) + crealf(cu[1+3*(lj)])*_Complex_I; zt3 = -cimagf(cu[3*(lj)]) + crealf(cu[3*(lj)])*_Complex_I; bxyz[3*lj] = -at4*zt2; bxyz[1+3*lj] = at4*zt3; bxyz[2+3*lj] = zero; bxyz[3*(k1+lj)] = zero; bxyz[1+3*(k1+lj)] = zero; bxyz[2+3*(k1+lj)] = zero; bxyz[3*l1] = zero; bxyz[1+3*l1] = zero; bxyz[2+3*l1] = zero; bxyz[3*(k1+l1)] = zero; bxyz[1+3*(k1+l1)] = zero; bxyz[2+3*(k1+l1)] = zero; wp += at1*(cu[3*lj]*conjf(cu[3*lj]) + cu[1+3*lj]*conjf(cu[1+3*lj]) + cu[2+3*lj]*conjf(cu[2+3*lj])); sum1 += wp; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; sum2 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,dky,at1,at2,at3,zt1,zt2,zt3,wp) \ reduction(+:sum2) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; for (j = 1; j < nxh; j++) { at1 = ci2*crealf(ffc[j+kk])*cimagf(ffc[j+kk]); at2 = at1*dnx*(float) j; at3 = dky*at1; zt1 = -cimagf(cu[2+3*(j+kj)]) + crealf(cu[2+3*(j+kj)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+kj)]) + crealf(cu[1+3*(j+kj)])*_Complex_I; zt3 = -cimagf(cu[3*(j+kj)]) + crealf(cu[3*(j+kj)])*_Complex_I; bxyz[3*(j+kj)] = at3*zt1; bxyz[1+3*(j+kj)] = -at2*zt1; bxyz[2+3*(j+kj)] = at2*zt2 - at3*zt3; zt1 = -cimagf(cu[2+3*(j+k1)]) + crealf(cu[2+3*(j+k1)])*_Complex_I; zt2 = -cimagf(cu[1+3*(j+k1)]) + crealf(cu[1+3*(j+k1)])*_Complex_I; zt3 = -cimagf(cu[3*(j+k1)]) + crealf(cu[3*(j+k1)])*_Complex_I; bxyz[3*(j+k1)] = -at3*zt1; bxyz[1+3*(j+k1)] = -at2*zt1; bxyz[2+3*(j+k1)] = at2*zt2 + at3*zt3; bxyz[3*(j+kj+l1)] = zero; bxyz[1+3*(j+kj+l1)] = zero; bxyz[2+3*(j+kj+l1)] = zero; bxyz[3*(j+k1+l1)] = zero; bxyz[1+3*(j+k1+l1)] = zero; bxyz[2+3*(j+k1+l1)] = zero; wp += at1*(cu[3*(j+kj)]*conjf(cu[3*(j+kj)]) + cu[1+3*(j+kj)]*conjf(cu[1+3*(j+kj)]) + cu[2+3*(j+kj)]*conjf(cu[2+3*(j+kj)]) + cu[3*(j+k1)]*conjf(cu[3*(j+k1)]) + cu[1+3*(j+k1)]*conjf(cu[1+3*(j+k1)]) + cu[2+3*(j+k1)]*conjf(cu[2+3*(j+k1)])); } /* mode numbers kx = 0, nx/2 */ at1 = ci2*crealf(ffc[kk])*cimagf(ffc[kk]); at3 = at1*dny*(float) k; zt1 = -cimagf(cu[2+3*(kj)]) + crealf(cu[2+3*(kj)])*_Complex_I; zt3 = -cimagf(cu[3*(kj)]) + crealf(cu[3*(kj)])*_Complex_I; bxyz[3*kj] = at3*zt1; bxyz[1+3*kj] = zero; bxyz[2+3*kj] = -at3*zt3; bxyz[3*k1] = zero; bxyz[1+3*k1] = zero; bxyz[2+3*k1] = zero; bxyz[3*(kj+l1)] = zero; bxyz[1+3*(kj+l1)] = zero; bxyz[2+3*(kj+l1)] = zero; bxyz[3*(k1+l1)] = zero; bxyz[1+3*(k1+l1)] = zero; bxyz[2+3*(k1+l1)] = zero; wp += at1*(cu[3*kj]*conjf(cu[3*kj]) + cu[1+3*kj]*conjf(cu[1+3*kj]) + cu[2+3*kj]*conjf(cu[2+3*kj])); sum2 += wp; } wp = 0.0; /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at1 = ci2*crealf(ffc[j])*cimagf(ffc[j]); at2 = at1*dnx*(float) j; zt1 = -cimagf(cu[2+3*j]) + crealf(cu[2+3*j])*_Complex_I; zt2 = -cimagf(cu[1+3*j]) + crealf(cu[1+3*j])*_Complex_I; bxyz[3*j] = zero; bxyz[1+3*j] = -at2*zt1; bxyz[2+3*j] = at2*zt2; bxyz[3*(j+k1)] = zero; bxyz[1+3*(j+k1)] = zero; bxyz[2+3*(j+k1)] = zero; bxyz[3*(j+l1)] = zero; bxyz[1+3*(j+l1)] = zero; bxyz[2+3*(j+l1)] = zero; bxyz[3*(j+k1+l1)] = zero; bxyz[1+3*(j+k1+l1)] = zero; bxyz[2+3*(j+k1+l1)] = zero; wp += at1*(cu[3*j]*conjf(cu[3*j]) + cu[1+3*j]*conjf(cu[1+3*j]) + cu[2+3*j]*conjf(cu[2+3*j])); } bxyz[0] = zero; bxyz[1] = zero; bxyz[2] = zero; bxyz[3*k1] = zero; bxyz[1+3*k1] = zero; bxyz[2+3*k1] = zero; bxyz[3*l1] = zero; bxyz[1+3*l1] = zero; bxyz[2+3*l1] = zero; bxyz[3*(k1+l1)] = zero; bxyz[1+3*(k1+l1)] = zero; bxyz[2+3*(k1+l1)] = zero; *wm = (sum1 + sum2 + wp)*((float) nx)*((float) ny)*((float) nz); return; } /*--------------------------------------------------------------------*/ void cbaddext3(float bxyz[], float omx, float omy, float omz, int nx, int ny, int nz, int nxe, int nye, int nze) { /* adds constant to magnetic field for 3d code bxy = magnetic field omx/omy/omz = magnetic field electron cyclotron frequency in x/y/z nx/ny/nz = system length in x/y/z direction nxe = second dimension of magnetic field array, nxe must be >= nx nye = third dimension of magnetic field array, nye must be >= ny nze = fourth dimension of magnetic field array, nze must be >= nz local data */ int j, k, l, nxye3, ll; nxye3 = 3*nxe*nye; #pragma omp parallel for private(j,k,l,ll) for (l = 0; l < nz; l++) { ll = nxye3*l; for (k = 0; k < ny; k++) { for (j = 0; j < nx; j++) { bxyz[3*j+3*nxe*k+ll] += omx; bxyz[1+3*j+3*nxe*k+ll] += omy; bxyz[2+3*j+3*nxe*k+ll] += omz; } } } return; } /*--------------------------------------------------------------------*/ void cmdcuperp3(float complex dcu[], float complex amu[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { /* this subroutine calculates transverse part of the derivative of the current density from the momentum flux in 3d with periodic boundary conditions. input: all, output: dcu approximate flop count is: 244*nxc*nyc*nzc + 82*(nxc*nyc + nxc*nzc + nyc*nzc) and (nx/2)*nyc*nzc divides where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 the derivative of the current is calculated using the equations: dcu[kz][ky][kx][0] = -sqrt(-1)*(kx*vx*vx+ky*vx*vy+kz*vx*vz) dcu[kz][ky][kx][1] = -sqrt(-1)*(kx*vx*vy+ky*vy*vy+kz*vy*vz) dcu[kz][ky][kx][2] = -sqrt(-1)*(kx*vx*vz+ky*vy*vz+kz*vz*vz) where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, except for dcux(kx=pi) = dcuy(kx=pi) = dcuz(kx=pi) = 0, dcux(ky=pi) = dcuy(ky=pi) = dcux(ky=pi) = 0, dcux(kz=pi) = dcuy(kz=pi) = dcuz(kz=pi) = 0, dcux(kx=0,ky=0,kz=0) = dcuy(kx=0,ky=0,kz=0) = dcuz(kx=0,ky=0,kz=0) = 0 the transverse part is calculated using the equation: dcu[kz][ky][kx][0] = dcu[kz][ky][kx][0] - kx*(kx*dcu([kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2)/(kx*kx+ky*ky+kz*kz) dcu[kz][ky][kx][1] = dcu(2,kx,ky,kz) - ky*(kx*dcu[kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2)/(kx*kx+ky*ky+kz*kz) dcu[kz][ky][kx][2] = dcu(3,kx,ky,kz) - kz*(kx*dcu[kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2)/(kx*kx+ky*ky+kz*kz) on output: dcu[l][k][j][i] = transverse part of complex derivative of current for fourier mode (j,k,l) amu[l][k][j][0] = xx component of complex momentum flux amu[l][k][j][1] = xy component of complex momentum flux amu[l][k][j][2] = xz component of complex momentum flux amu[l][k][j][3] = yy component of complex momentum flux amu[l][k][j][4] = yz component of complex momentum flux amu[l][k][j][5] = zz component of complex momentum flux all for fourier mode (j,k,l) nx/ny/nz = system length in x/y/z direction nxvh = second dimension of field arrays, must be >= nxh nyv = third dimension of field arrays, must be >= ny nzv = fourth dimension of field arrays, must be >= nz local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kj, lj, nxvyh; float dnx, dny, dnz, dkx, dky, dkz, dky2, dkz2, dkyz2, at1; float complex zero, zt1, zt2, zt3, zt4, zt5; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; /* calculate transverse part of current */ /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,lj,kj,dkx,dky,dkz,dkz2,dkyz2,at1,zt1,zt2,zt3,zt4, \ zt5) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; lj = nxvyh*l; l1 = nxvyh*nz - lj; dkz2 = dkz*dkz; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dkyz2 = dky*dky + dkz2; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkyz2); zt1 = cimagf(amu[6*(j+kj+lj)]) - crealf(amu[6*(j+kj+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj+lj)]) - crealf(amu[1+6*(j+kj+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj+lj)]) - crealf(amu[2+6*(j+kj+lj)])*_Complex_I; zt1 = dkx*zt1 + dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(j+kj+lj)]) - crealf(amu[3+6*(j+kj+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj+lj)]) - crealf(amu[4+6*(j+kj+lj)])*_Complex_I; zt2 = dkx*zt2 + dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+kj+lj)]) - crealf(amu[5+6*(j+kj+lj)])*_Complex_I; zt3 = dkx*zt3 + dky*zt5 + dkz*zt4; zt4 = at1*(dkx*zt1 + dky*zt2 + dkz*zt3); dcu[3*(j+kj+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+kj+lj)] = zt2 - dky*zt4; dcu[2+3*(j+kj+lj)] = zt3 - dkz*zt4; zt1 = cimagf(amu[6*(j+k1+lj)]) - crealf(amu[6*(j+k1+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1+lj)]) - crealf(amu[1+6*(j+k1+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1+lj)]) - crealf(amu[2+6*(j+k1+lj)])*_Complex_I; zt1 = dkx*zt1 - dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(j+k1+lj)]) - crealf(amu[3+6*(j+k1+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1+lj)]) - crealf(amu[4+6*(j+k1+lj)])*_Complex_I; zt2 = dkx*zt2 - dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+k1+lj)]) - crealf(amu[5+6*(j+k1+lj)])*_Complex_I; zt3 = dkx*zt3 - dky*zt5 + dkz*zt4; zt4 = at1*(dkx*zt1 - dky*zt2 + dkz*zt3); dcu[3*(j+k1+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+k1+lj)] = zt2 + dky*zt4; dcu[2+3*(j+k1+lj)] = zt3 - dkz*zt4; zt1 = cimagf(amu[6*(j+kj+l1)]) - crealf(amu[6*(j+kj+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj+l1)]) - crealf(amu[1+6*(j+kj+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj+l1)]) - crealf(amu[2+6*(j+kj+l1)])*_Complex_I; zt1 = dkx*zt1 + dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(j+kj+l1)]) - crealf(amu[3+6*(j+kj+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj+l1)]) - crealf(amu[4+6*(j+kj+l1)])*_Complex_I; zt2 = dkx*zt2 + dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+kj+l1)]) - crealf(amu[5+6*(j+kj+l1)])*_Complex_I; zt3 = dkx*zt3 + dky*zt5 - dkz*zt4; zt4 = at1*(dkx*zt1 + dky*zt2 - dkz*zt3); dcu[3*(j+kj+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+kj+l1)] = zt2 - dky*zt4; dcu[2+3*(j+kj+l1)] = zt3 + dkz*zt4; zt1 = cimagf(amu[6*(j+k1+l1)]) - crealf(amu[6*(j+k1+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1+l1)]) - crealf(amu[1+6*(j+k1+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1+l1)]) - crealf(amu[2+6*(j+k1+l1)])*_Complex_I; zt1 = dkx*zt1 - dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(j+k1+l1)]) - crealf(amu[3+6*(j+k1+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1+l1)]) - crealf(amu[4+6*(j+k1+l1)])*_Complex_I; zt2 = dkx*zt2 - dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+k1+l1)]) - crealf(amu[5+6*(j+k1+l1)])*_Complex_I; zt3 = dkx*zt3 - dky*zt5 - dkz*zt4; zt4 = at1*(dkx*zt1 - dky*zt2 - dkz*zt3); dcu[3*(j+k1+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+k1+l1)] = zt2 + dky*zt4; dcu[2+3*(j+k1+l1)] = zt3 + dkz*zt4; } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kj = nxvh*k; k1 = nxvh*ny - kj; dky = dny*(float) k; at1 = 1.0/(dky*dky + dkz2); zt2 = cimagf(amu[1+6*(kj+lj)]) - crealf(amu[1+6*(kj+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(kj+lj)]) - crealf(amu[2+6*(kj+lj)])*_Complex_I; zt1 = dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(kj+lj)]) - crealf(amu[3+6*(kj+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(kj+lj)]) - crealf(amu[4+6*(kj+lj)])*_Complex_I; zt2 = dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(kj+lj)]) - crealf(amu[5+6*(kj+lj)])*_Complex_I; zt3 = dky*zt5 + dkz*zt4; zt4 = at1*(dky*zt2 + dkz*zt3); dcu[3*(kj+lj)] = zt1; dcu[1+3*(kj+lj)] = zt2 - dky*zt4; dcu[2+3*(kj+lj)] = zt3 - dkz*zt4; dcu[3*(k1+lj)] = zero; dcu[1+3*(k1+lj)] = zero; dcu[2+3*(k1+lj)] = zero; zt2 = cimagf(amu[1+6*(kj+l1)]) - crealf(amu[1+6*(kj+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(kj+l1)]) - crealf(amu[2+6*(kj+l1)])*_Complex_I; zt1 = dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(kj+l1)]) - crealf(amu[3+6*(kj+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(kj+l1)]) - crealf(amu[4+6*(kj+l1)])*_Complex_I; zt2 = dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(kj+l1)]) - crealf(amu[5+6*(kj+l1)])*_Complex_I; zt3 = dky*zt5 - dkz*zt4; zt4 = at1*(dky*zt2 - dkz*zt3); dcu[3*(kj+l1)] = zt1; dcu[1+3*(kj+l1)] = zt2 - dky*zt4; dcu[2+3*(kj+l1)] = zt3 + dkz*zt4; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkz2); zt1 = cimagf(amu[6*(j+lj)]) - crealf(amu[6*(j+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+lj)]) - crealf(amu[1+6*(j+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+lj)]) - crealf(amu[2+6*(j+lj)])*_Complex_I; zt1 = dkx*zt1 + dkz*zt3; zt5 = cimagf(amu[4+6*(j+lj)]) - crealf(amu[4+6*(j+lj)])*_Complex_I; zt2 = dkx*zt2 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+lj)]) - crealf(amu[5+6*(j+lj)])*_Complex_I; zt3 = dkx*zt3 + dkz*zt4; zt4 = at1*(dkx*zt1 + dkz*zt3); dcu[3*(j+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+lj)] = zt2; dcu[2+3*(j+lj)] = zt3 - dkz*zt4; dcu[3*(j+k1+lj)] = zero; dcu[1+3*(j+k1+lj)] = zero; dcu[2+3*(j+k1+lj)] = zero; zt1 = cimagf(amu[6*(j+l1)]) - crealf(amu[6*(j+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+l1)]) - crealf(amu[1+6*(j+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+l1)]) - crealf(amu[2+6*(j+l1)])*_Complex_I; zt1 = dkx*zt1 - dkz*zt3; zt5 = cimagf(amu[4+6*(j+l1)]) - crealf(amu[4+6*(j+l1)])*_Complex_I; zt2 = dkx*zt2 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+l1)]) - crealf(amu[5+6*(j+l1)])*_Complex_I; zt3 = dkx*zt3 - dkz*zt4; zt4 = at1*(dkx*zt1 - dkz*zt3); dcu[3*(j+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+l1)] = zt2; dcu[2+3*(j+l1)] = zt3 + dkz*zt4; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)] = zero; } /* mode numbers kx = 0, nx/2 */ zt3 = cimagf(amu[2+6*(lj)]) - crealf(amu[2+6*(lj)])*_Complex_I; zt1 = dkz*zt3; zt5 = cimagf(amu[4+6*(lj)]) - crealf(amu[4+6*(lj)])*_Complex_I; zt2 = dkz*zt5; dcu[3*lj] = zt1; dcu[1+3*lj]= zt2; dcu[2+3*lj] = zero; dcu[3*(k1+lj)] = zero; dcu[1+3*(k1+lj)] = zero; dcu[2+3*(k1+lj)] = zero; dcu[3*l1] = zero; dcu[1+3*l1] = zero; dcu[2+3*l1] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; #pragma omp parallel for \ private(j,k,k1,kj,dky,dky2,dkx,at1,zt1,zt2,zt3,zt4,zt5) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dky2 = dky*dky; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dky2); zt1 = cimagf(amu[6*(j+kj)]) - crealf(amu[6*(j+kj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj)]) - crealf(amu[1+6*(j+kj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj)]) - crealf(amu[2+6*(j+kj)])*_Complex_I; zt1 = dkx*zt1 + dky*zt2; zt4 = cimagf(amu[3+6*(j+kj)]) - crealf(amu[3+6*(j+kj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj)]) - crealf(amu[4+6*(j+kj)])*_Complex_I; zt2 = dkx*zt2 + dky*zt4; zt3 = dkx*zt3 + dky*zt5; zt4 = at1*(dkx*zt1 + dky*zt2); dcu[3*(j+kj)] = zt1 - dkx*zt4; dcu[1+3*(j+kj)] = zt2 - dky*zt4; dcu[2+3*(j+kj)] = zt3; dcu[3*(j+kj+l1)] = zero; dcu[1+3*(j+kj+l1)] = zero; dcu[2+3*(j+kj+l1)] = zero; zt1 = cimagf(amu[6*(j+k1)]) - crealf(amu[6*(j+k1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1)]) - crealf(amu[1+6*(j+k1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1)]) - crealf(amu[2+6*(j+k1)])*_Complex_I; zt1 = dkx*zt1 - dky*zt2; zt4 = cimagf(amu[3+6*(j+k1)]) - crealf(amu[3+6*(j+k1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1)]) - crealf(amu[4+6*(j+k1)])*_Complex_I; zt2 = dkx*zt2 - dky*zt4; zt3 = dkx*zt3 - dky*zt5; zt4 = at1*(dkx*zt1 - dky*zt2); dcu[3*(j+k1)] = zt1 - dkx*zt4; dcu[1+3*(j+k1)] = zt2 + dky*zt4; dcu[2+3*(j+k1)] = zt3; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)]= zero; } /* mode numbers kx = 0, nx/2 */ zt2 = cimagf(amu[1+6*(kj)]) - crealf(amu[1+6*(kj)])*_Complex_I; zt1 = dky*zt2; zt5 = cimagf(amu[4+6*(kj)]) - crealf(amu[4+6*(kj)])*_Complex_I; zt3 = dky*zt5; dcu[3*kj] = zt1; dcu[1+3*kj] = zero; dcu[2+3*kj] = zt3; dcu[3*k1] = zero; dcu[1+3*k1] = zero; dcu[2+3*k1] = zero; dcu[3*(kj+l1)] = zero; dcu[1+3*(kj+l1)] = zero; dcu[2+3*(kj+l1)] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; zt2 = cimagf(amu[1+6*j]) - crealf(amu[1+6*j])*_Complex_I; zt3 = cimagf(amu[2+6*j]) - crealf(amu[2+6*j])*_Complex_I; zt2 = dkx*zt2; zt3 = dkx*zt3; dcu[3*j] = zero; dcu[1+3*j] = zt2; dcu[2+3*j] = zt3; dcu[3*(j+k1)] = zero; dcu[1+3*(j+k1)] = zero; dcu[2+3*(j+k1)] = zero; dcu[3*(j+l1)] = zero; dcu[1+3*(j+l1)] = zero; dcu[2+3*(j+l1)] = zero; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)] = zero; } dcu[0] = zero; dcu[1] = zero; dcu[2] = zero; dcu[3*k1] = zero; dcu[1+3*k1] = zero; dcu[2+3*k1] = zero; dcu[3*l1] = zero; dcu[1+3*l1] = zero; dcu[2+3*l1] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; return; } /*--------------------------------------------------------------------*/ void cmadcuperp3(float complex dcu[], float complex amu[], int nx, int ny, int nz, int nxvh, int nyv, int nzv) { /* this subroutine calculates transverse part of the derivative of the current density from the momentum flux and acceleration density in 3d with periodic boundary conditions. input: all, output: dcu approximate flop count is: 244*nxc*nyc*nzc + 82*(nxc*nyc + nxc*nzc + nyc*nzc) and (nx/2)*nyc*nzc divides where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 the derivative of the current is calculated using the equations: dcu[kz][ky][kx][0] = dcu[kz][ky][kx][0] -sqrt(-1)*(kx*vx*vx+ky*vx*vy+kz*vx*vz) dcu[kz][ky][kx][1] = dcu[kz][ky][kx][1] -sqrt(-1)*(kx*vx*vy+ky*vy*vy+kz*vy*vz) dcu[kz][ky][kx][2] = dcu[kz][ky][kx][2] -sqrt(-1)*(kx*vx*vz+ky*vy*vz+kz*vz*vz) where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, except for dcux(kx=pi) = dcuy(kx=pi) = dcuz(kx=pi) = 0, dcux(ky=pi) = dcuy(ky=pi) = dcux(ky=pi) = 0, dcux(kz=pi) = dcuy(kz=pi) = dcuz(kz=pi) = 0, dcux(kx=0,ky=0,kz=0) = dcuy(kx=0,ky=0,kz=0) = dcuz(kx=0,ky=0,kz=0) = 0 the transverse part is calculated using the equation: dcu[kz][ky][kx][0] = dcu[kz][ky][kx][0] - kx*(kx*dcu[kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2])/(kx*kx+ky*ky+kz*kz) dcu[kz][ky][kx][1] = dcu(2,kx,ky,kz) - ky*(kx*dcu[kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2])/(kx*kx+ky*ky+kz*kz) dcu[kz][ky][kx][2] = dcu(3,kx,ky,kz) - kz*(kx*dcu[kz][ky][kx][0]+ky*dcu[kz][ky][kx][1] + kz*dcu[kz][ky][kx][2])/(kx*kx+ky*ky+kz*kz) on input: dcu[l][k][j][i] = complex acceleration density for fourier mode (j-1,k-1) on output: dcu[l][k][j][i] = transverse part of complex derivative of current for fourier mode (j,k,l) amu[l][k][j][0] = xx component of complex momentum flux amu[l][k][j][1] = xy component of complex momentum flux amu[l][k][j][2] = xz component of complex momentum flux amu[l][k][j][3] = yy component of complex momentum flux amu[l][k][j][4] = yz component of complex momentum flux amu[l][k][j][5] = zz component of complex momentum flux all for fourier mode (j,k,l) nx/ny/nz = system length in x/y/z direction nxvh = second dimension of field arrays, must be >= nxh nyv = third dimension of field arrays, must be >= ny nzv = fourth dimension of field arrays, must be >= nz local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kj, lj, nxvyh; float dnx, dny, dnz, dkx, dky, dkz, dky2, dkz2, dkyz2, at1; float complex zero, zt1, zt2, zt3, zt4, zt5; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; /* calculate transverse part of current */ /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,lj,kj,dkx,dky,dkz,dkz2,dkyz2,at1,zt1,zt2,zt3,zt4, \ zt5) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; lj = nxvyh*l; l1 = nxvyh*nz - lj; dkz2 = dkz*dkz; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dkyz2 = dky*dky + dkz2; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkyz2); zt1 = cimagf(amu[6*(j+kj+lj)]) - crealf(amu[6*(j+kj+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj+lj)]) - crealf(amu[1+6*(j+kj+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj+lj)]) - crealf(amu[2+6*(j+kj+lj)])*_Complex_I; zt1 = dcu[3*(j+kj+lj)] + dkx*zt1 + dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(j+kj+lj)]) - crealf(amu[3+6*(j+kj+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj+lj)]) - crealf(amu[4+6*(j+kj+lj)])*_Complex_I; zt2 = dcu[1+3*(j+kj+lj)] + dkx*zt2 + dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+kj+lj)]) - crealf(amu[5+6*(j+kj+lj)])*_Complex_I; zt3 = dcu[2+3*(j+kj+lj)] + dkx*zt3 + dky*zt5 + dkz*zt4; zt4 = at1*(dkx*zt1 + dky*zt2 + dkz*zt3); dcu[3*(j+kj+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+kj+lj)] = zt2 - dky*zt4; dcu[2+3*(j+kj+lj)] = zt3 - dkz*zt4; zt1 = cimagf(amu[6*(j+k1+lj)]) - crealf(amu[6*(j+k1+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1+lj)]) - crealf(amu[1+6*(j+k1+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1+lj)]) - crealf(amu[2+6*(j+k1+lj)])*_Complex_I; zt1 = dcu[3*(j+k1+lj)] + dkx*zt1 - dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(j+k1+lj)]) - crealf(amu[3+6*(j+k1+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1+lj)]) - crealf(amu[4+6*(j+k1+lj)])*_Complex_I; zt2 = dcu[1+3*(j+k1+lj)] + dkx*zt2 - dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+k1+lj)]) - crealf(amu[5+6*(j+k1+lj)])*_Complex_I; zt3 = dcu[2+3*(j+k1+lj)] + dkx*zt3 - dky*zt5 + dkz*zt4; zt4 = at1*(dkx*zt1 - dky*zt2 + dkz*zt3); dcu[3*(j+k1+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+k1+lj)] = zt2 + dky*zt4; dcu[2+3*(j+k1+lj)] = zt3 - dkz*zt4; zt1 = cimagf(amu[6*(j+kj+l1)]) - crealf(amu[6*(j+kj+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj+l1)]) - crealf(amu[1+6*(j+kj+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj+l1)]) - crealf(amu[2+6*(j+kj+l1)])*_Complex_I; zt1 = dcu[3*(j+kj+l1)] + dkx*zt1 + dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(j+kj+l1)]) - crealf(amu[3+6*(j+kj+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj+l1)]) - crealf(amu[4+6*(j+kj+l1)])*_Complex_I; zt2 = dcu[1+3*(j+kj+l1)] + dkx*zt2 + dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+kj+l1)]) - crealf(amu[5+6*(j+kj+l1)])*_Complex_I; zt3 = dcu[2+3*(j+kj+l1)] + dkx*zt3 + dky*zt5 - dkz*zt4; zt4 = at1*(dkx*zt1 + dky*zt2 - dkz*zt3); dcu[3*(j+kj+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+kj+l1)] = zt2 - dky*zt4; dcu[2+3*(j+kj+l1)] = zt3 + dkz*zt4; zt1 = cimagf(amu[6*(j+k1+l1)]) - crealf(amu[6*(j+k1+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1+l1)]) - crealf(amu[1+6*(j+k1+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1+l1)]) - crealf(amu[2+6*(j+k1+l1)])*_Complex_I; zt1 = dcu[3*(j+k1+l1)] + dkx*zt1 - dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(j+k1+l1)]) - crealf(amu[3+6*(j+k1+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1+l1)]) - crealf(amu[4+6*(j+k1+l1)])*_Complex_I; zt2 = dcu[1+3*(j+k1+l1)] + dkx*zt2 - dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+k1+l1)]) - crealf(amu[5+6*(j+k1+l1)])*_Complex_I; zt3 = dcu[2+3*(j+k1+l1)] + dkx*zt3 - dky*zt5 - dkz*zt4; zt4 = at1*(dkx*zt1 - dky*zt2 - dkz*zt3); dcu[3*(j+k1+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+k1+l1)] = zt2 + dky*zt4; dcu[2+3*(j+k1+l1)] = zt3 + dkz*zt4; } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kj = nxvh*k; k1 = nxvh*ny - kj; dky = dny*(float) k; at1 = 1.0/(dky*dky + dkz2); zt2 = cimagf(amu[1+6*(kj+lj)]) - crealf(amu[1+6*(kj+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(kj+lj)]) - crealf(amu[2+6*(kj+lj)])*_Complex_I; zt1 = dcu[3*(kj+lj)] + dky*zt2 + dkz*zt3; zt4 = cimagf(amu[3+6*(kj+lj)]) - crealf(amu[3+6*(kj+lj)])*_Complex_I; zt5 = cimagf(amu[4+6*(kj+lj)]) - crealf(amu[4+6*(kj+lj)])*_Complex_I; zt2 = dcu[1+3*(kj+lj)] + dky*zt4 + dkz*zt5; zt4 = cimagf(amu[5+6*(kj+lj)]) - crealf(amu[5+6*(kj+lj)])*_Complex_I; zt3 = dcu[2+3*(kj+lj)] + dky*zt5 + dkz*zt4; zt4 = at1*(dky*zt2 + dkz*zt3); dcu[3*(kj+lj)] = zt1; dcu[1+3*(kj+lj)] = zt2 - dky*zt4; dcu[2+3*(kj+lj)] = zt3 - dkz*zt4; dcu[3*(k1+lj)] = zero; dcu[1+3*(k1+lj)] = zero; dcu[2+3*(k1+lj)] = zero; zt2 = cimagf(amu[1+6*(kj+l1)]) - crealf(amu[1+6*(kj+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(kj+l1)]) - crealf(amu[2+6*(kj+l1)])*_Complex_I; zt1 = dcu[3*(kj+l1)] + dky*zt2 - dkz*zt3; zt4 = cimagf(amu[3+6*(kj+l1)]) - crealf(amu[3+6*(kj+l1)])*_Complex_I; zt5 = cimagf(amu[4+6*(kj+l1)]) - crealf(amu[4+6*(kj+l1)])*_Complex_I; zt2 = dcu[1+3*(kj+l1)] + dky*zt4 - dkz*zt5; zt4 = cimagf(amu[5+6*(kj+l1)]) - crealf(amu[5+6*(kj+l1)])*_Complex_I; zt3 = dcu[2+3*(kj+l1)] + dky*zt5 - dkz*zt4; zt4 = at1*(dky*zt2 - dkz*zt3); dcu[3*(kj+l1)] = zt1; dcu[1+3*(kj+l1)] = zt2 - dky*zt4; dcu[2+3*(kj+l1)] = zt3 + dkz*zt4; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dkz2); zt1 = cimagf(amu[6*(j+lj)]) - crealf(amu[6*(j+lj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+lj)]) - crealf(amu[1+6*(j+lj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+lj)]) - crealf(amu[2+6*(j+lj)])*_Complex_I; zt1 = dcu[3*(j+lj)] + dkx*zt1 + dkz*zt3; zt5 = cimagf(amu[4+6*(j+lj)]) - crealf(amu[4+6*(j+lj)])*_Complex_I; zt2 = dcu[1+3*(j+lj)] + dkx*zt2 + dkz*zt5; zt4 = cimagf(amu[5+6*(j+lj)]) - crealf(amu[5+6*(j+lj)])*_Complex_I; zt3 = dcu[2+3*(j+lj)] + dkx*zt3 + dkz*zt4; zt4 = at1*(dkx*zt1 + dkz*zt3); dcu[3*(j+lj)] = zt1 - dkx*zt4; dcu[1+3*(j+lj)] = zt2; dcu[2+3*(j+lj)] = zt3 - dkz*zt4; dcu[3*(j+k1+lj)] = zero; dcu[1+3*(j+k1+lj)] = zero; dcu[2+3*(j+k1+lj)] = zero; zt1 = cimagf(amu[6*(j+l1)]) - crealf(amu[6*(j+l1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+l1)]) - crealf(amu[1+6*(j+l1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+l1)]) - crealf(amu[2+6*(j+l1)])*_Complex_I; zt1 = dcu[3*(j+l1)] + dkx*zt1 - dkz*zt3; zt5 = cimagf(amu[4+6*(j+l1)]) - crealf(amu[4+6*(j+l1)])*_Complex_I; zt2 = dcu[1+3*(j+l1)] + dkx*zt2 - dkz*zt5; zt4 = cimagf(amu[5+6*(j+l1)]) - crealf(amu[5+6*(j+l1)])*_Complex_I; zt3 = dcu[2+3*(j+l1)] + dkx*zt3 - dkz*zt4; zt4 = at1*(dkx*zt1 - dkz*zt3); dcu[3*(j+l1)] = zt1 - dkx*zt4; dcu[1+3*(j+l1)] = zt2; dcu[2+3*(j+l1)] = zt3 + dkz*zt4; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)] = zero; } /* mode numbers kx = 0, nx/2 */ zt3 = cimagf(amu[2+6*(lj)]) - crealf(amu[2+6*(lj)])*_Complex_I; zt1 = dcu[3*lj] + dkz*zt3; zt5 = cimagf(amu[4+6*(lj)]) - crealf(amu[4+6*(lj)])*_Complex_I; zt2 = dcu[1+3*lj] + dkz*zt5; dcu[3*lj] = zt1; dcu[1+3*lj]= zt2; dcu[2+3*lj] = zero; dcu[3*(k1+lj)] = zero; dcu[1+3*(k1+lj)] = zero; dcu[2+3*(k1+lj)] = zero; dcu[3*l1] = zero; dcu[1+3*l1] = zero; dcu[2+3*l1] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; #pragma omp parallel for \ private(j,k,k1,kj,dky,dky2,dkx,at1,zt1,zt2,zt3,zt4,zt5) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kj = nxvh*k; k1 = nxvh*ny - kj; dky2 = dky*dky; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; at1 = 1.0/(dkx*dkx + dky2); zt1 = cimagf(amu[6*(j+kj)]) - crealf(amu[6*(j+kj)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+kj)]) - crealf(amu[1+6*(j+kj)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+kj)]) - crealf(amu[2+6*(j+kj)])*_Complex_I; zt1 = dcu[3*(j+kj)] + dkx*zt1 + dky*zt2; zt4 = cimagf(amu[3+6*(j+kj)]) - crealf(amu[3+6*(j+kj)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+kj)]) - crealf(amu[4+6*(j+kj)])*_Complex_I; zt2 = dcu[1+3*(j+kj)] + dkx*zt2 + dky*zt4; zt3 = dcu[2+3*(j+kj)] + dkx*zt3 + dky*zt5; zt4 = at1*(dkx*zt1 + dky*zt2); dcu[3*(j+kj)] = zt1 - dkx*zt4; dcu[1+3*(j+kj)] = zt2 - dky*zt4; dcu[2+3*(j+kj)] = zt3; dcu[3*(j+kj+l1)] = zero; dcu[1+3*(j+kj+l1)] = zero; dcu[2+3*(j+kj+l1)] = zero; zt1 = cimagf(amu[6*(j+k1)]) - crealf(amu[6*(j+k1)])*_Complex_I; zt2 = cimagf(amu[1+6*(j+k1)]) - crealf(amu[1+6*(j+k1)])*_Complex_I; zt3 = cimagf(amu[2+6*(j+k1)]) - crealf(amu[2+6*(j+k1)])*_Complex_I; zt1 = dcu[3*(j+k1)] + dkx*zt1 - dky*zt2; zt4 = cimagf(amu[3+6*(j+k1)]) - crealf(amu[3+6*(j+k1)])*_Complex_I; zt5 = cimagf(amu[4+6*(j+k1)]) - crealf(amu[4+6*(j+k1)])*_Complex_I; zt2 = dcu[1+3*(j+k1)] + dkx*zt2 - dky*zt4; zt3 = dcu[2+3*(j+k1)] + dkx*zt3 - dky*zt5; zt4 = at1*(dkx*zt1 - dky*zt2); dcu[3*(j+k1)] = zt1 - dkx*zt4; dcu[1+3*(j+k1)] = zt2 + dky*zt4; dcu[2+3*(j+k1)] = zt3; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)]= zero; } zt2 = cimagf(amu[1+6*(kj)]) - crealf(amu[1+6*(kj)])*_Complex_I; zt1 = dcu[3*kj] + dky*zt2; zt5 = cimagf(amu[4+6*(kj)]) - crealf(amu[4+6*(kj)])*_Complex_I; zt3 = dcu[2+3*kj] + dky*zt5; dcu[3*kj] = zt1; dcu[1+3*kj] = zero; dcu[2+3*kj] = zt3; dcu[3*k1] = zero; dcu[1+3*k1] = zero; dcu[2+3*k1] = zero; dcu[3*(kj+l1)] = zero; dcu[1+3*(kj+l1)] = zero; dcu[2+3*(kj+l1)] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { dkx = dnx*(float) j; zt2 = cimagf(amu[1+6*j]) - crealf(amu[1+6*j])*_Complex_I; zt3 = cimagf(amu[2+6*j]) - crealf(amu[2+6*j])*_Complex_I; zt2 = dcu[1+3*j] + dkx*zt2; zt3 = dcu[2+3*j] + dkx*zt3; dcu[3*j] = zero; dcu[1+3*j] = zt2; dcu[2+3*j] = zt3; dcu[3*(j+k1)] = zero; dcu[1+3*(j+k1)] = zero; dcu[2+3*(j+k1)] = zero; dcu[3*(j+l1)] = zero; dcu[1+3*(j+l1)] = zero; dcu[2+3*(j+l1)] = zero; dcu[3*(j+k1+l1)] = zero; dcu[1+3*(j+k1+l1)] = zero; dcu[2+3*(j+k1+l1)] = zero; } dcu[0] = zero; dcu[1] = zero; dcu[2] = zero; dcu[3*k1] = zero; dcu[1+3*k1] = zero; dcu[2+3*k1] = zero; dcu[3*l1] = zero; dcu[1+3*l1] = zero; dcu[2+3*l1] = zero; dcu[3*(k1+l1)] = zero; dcu[1+3*(k1+l1)] = zero; dcu[2+3*(k1+l1)] = zero; return; } /*--------------------------------------------------------------------*/ void cmepois33(float complex dcu[], float complex exyz[], int isign, float complex ffe[], float ax, float ay, float az, float affp, float wp0, float ci, float *wf, int nx, int ny, int nz, int nxvh, int nyv, int nzv, int nxhd, int nyhd, int nzhd) { /* this subroutine solves 3d poisson's equation in fourier space for transverse electric field (or convolution of transverse electric field over particle shape), with periodic boundary conditions. using algorithm described in J. Busnardo-Neto, P. L. Pritchett, A. T. Lin, and J. M. Dawson, J. Computational Phys. 23, 300 (1977). for isign = 0, output: ffe input: isign,ax,ay,az,affp,wp0,nx,ny,nz,nxvh,nyv,nzv,nxhd,nyhd,nzhd for isign /= 0, output: exyz, wf input: dcu,ffe,isign,ci,nx,ny,nz,nxvh,nyv,nzv,nxhd,nyhd,nzhd approximate flop count is: 128*nxc*nyc*nzc + 66*(nxc*nyc + nxc*nzc + nyc*nzc) where nxc = nx/2 - 1, nyc = ny/2 - 1, nzc = nz/2 - 1 if isign = -1, smoothed transverse electric field is calculated using the equation: ex[kz][ky][kx] = -ci*ci*g[kz][ky][kx]*dcux[kz][ky][kx]*s[kz][ky][kx] ey[kz][ky][kx] = -ci*ci*g[kz][ky][kx]*dcuy[kz][ky][kx]*s[kz][ky][kx] ez[kz][ky][kx] = -ci*ci*g[kz][ky][kx]*dcuz[kz][ky][kx]*s[kz][ky][kx] where kx = 2pi*j/nx, ky = 2pi*k/ny, kz = 2pi*l/nz, and j,k,l = fourier mode numbers, g[kz][ky][kx] = (affp/(kx**2+ky**2+kz**2))*s[kz][ky][kx], s[kz][ky][kx] = exp(-((kx*ax)**2+(ky*ay)**2+(kz*az)**2)/2), except for ex(kx=pi) = ey(kx=pi) = ez(kx=pi) = 0, ex(ky=pi) = ey(ky=pi) = ex(ky=pi) = 0, ex(kz=pi) = ey(kz=pi) = ez(kz=pi) = 0, ex(kx=0,ky=0,kz=0) = ey(kx=0,ky=0,kz=0) = ez(kx=0,ky=0,kz=0) = 0. if isign = 1, unsmoothed transverse electric field is calculated using the equation: ex[kz][ky][kx] = -ci*ci*g[kz][ky][kx]*dcux[kz][ky][kx] ey[kz][ky][kx] = -ci*ci*g[kz][ky][kx])*dcuy[kz][ky][kx] ez[kz][ky][kx] = -ci*ci*g[kz][ky][kx]*dcuz[kz][ky][kx] dcu[l][k][j][i] = transverse part of complex derivative of current for fourier mode (j,k,l) exyz[l][k][j][0] = x component of complex transverse electric field exyz[l][k][j][1] = y component of complex transverse electric field exyz[l][k][j][2] = z component of complex transverse electric field all for fourier mode (j,k,l) cimag(ffe[l][k][j]) = finite-size particle shape factor s for fourier mode (j,k,l) creal(ffe[l][k][j]) = potential green's function g for fourier mode (j,k,l) ax/ay/az = half-width of particle in x/y/z direction affp = normalization constant = nx*ny*nz/np, where np=number of particles wp0 = normalized total plasma frequency squared where np=number of particles ci = reciprocal of velocity of light transverse electric field energy is also calculated, using wf = nx*ny*nz*sum((affp/((kx**2+ky**2+kz**2)*ci*ci)**2) |dcu[kz][ky][kx]*s[kz][ky][kx]|**2) this expression is valid only if the derivative of current is divergence-free nx/ny/nz = system length in x/y/z direction nxvh = first dimension of field arrays, must be >= nxh nyv = second dimension of field arrays, must be >= ny nzv = third dimension of field arrays, must be >= nz nxhd = first dimension of form factor array, must be >= nxh nyhd = second dimension of form factor array, must be >= nyh nzhd = third dimension of form factor array, must be >= nzh local data */ int nxh, nyh, nzh, j, k, l, k1, l1, kk, kj, ll, lj, nxyhd, nxvyh; float dnx, dny, dnz, dkx, dky, dkz, ci2, wpc; float at1, at2, at3, at4, at5, at6; float complex zero; double wp, sum1, sum2; nxh = nx/2; nyh = 1 > ny/2 ? 1 : ny/2; nzh = 1 > nz/2 ? 1 : nz/2; nxyhd = nxhd*nyhd; nxvyh = nxvh*nyv; dnx = 6.28318530717959/(float) nx; dny = 6.28318530717959/(float) ny; dnz = 6.28318530717959/(float) nz; zero = 0.0 + 0.0*_Complex_I; ci2 = ci*ci; if (isign != 0) goto L40; wpc = wp0*ci2; /* prepare form factor array */ for (l = 0; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; at1 = dkz*dkz; at2 = pow((dkz*az),2); for (k = 0; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; at3 = dky*dky + at1; at4 = pow((dky*ay),2) + at2; for (j = 0; j < nxh; j++) { dkx = dnx*(float) j; at5 = dkx*dkx + at3; at6 = exp(-0.5*(pow((dkx*ax),2) + at4)); if (at5==0.0) { ffe[j+kk+ll] = affp + 1.0*_Complex_I; } else { ffe[j+kk+ll] = (affp*at6/(at5 + wpc*at6*at6)) + at6*_Complex_I; } } } } return; L40: if (isign > 0) goto L130; /* calculate smoothed transverse electric field and sum field energy */ sum1 = 0.0; /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,ll,lj,kk,kj,at1,at2,wp) \ reduction(+:sum1) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; lj = nxvyh*l; l1 = nxvyh*nz - lj; wp = 0.0; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+kk+ll]); at1 = at2*cimagf(ffe[j+kk+ll]); at2 = at2*at2; exyz[3*(j+kj+lj)] = at1*dcu[3*(j+kj+lj)]; exyz[1+3*(j+kj+lj)] = at1*dcu[1+3*(j+kj+lj)]; exyz[2+3*(j+kj+lj)] = at1*dcu[2+3*(j+kj+lj)]; exyz[3*(j+k1+lj)] = at1*dcu[3*(j+k1+lj)]; exyz[1+3*(j+k1+lj)] = at1*dcu[1+3*(j+k1+lj)]; exyz[2+3*(j+k1+lj)] = at1*dcu[2+3*(j+k1+lj)]; exyz[3*(j+kj+l1)] = at1*dcu[3*(j+kj+l1)]; exyz[1+3*(j+kj+l1)] = at1*dcu[1+3*(j+kj+l1)]; exyz[2+3*(j+kj+l1)] = at1*dcu[2+3*(j+kj+l1)]; exyz[3*(j+k1+l1)] = at1*dcu[3*(j+k1+l1)]; exyz[1+3*(j+k1+l1)] = at1*dcu[1+3*(j+k1+l1)]; exyz[2+3*(j+k1+l1)] = at1*dcu[2+3*(j+k1+l1)]; wp += at2*(dcu[3*(j+kj+lj)]*conjf(dcu[3*(j+kj+lj)]) + dcu[1+3*(j+kj+lj)]*conjf(dcu[1+3*(j+kj+lj)]) + dcu[2+3*(j+kj+lj)]*conjf(dcu[2+3*(j+kj+lj)]) + dcu[3*(j+k1+lj)]*conjf(dcu[3*(j+k1+lj)]) + dcu[1+3*(j+k1+lj)]*conjf(dcu[1+3*(j+k1+lj)]) + dcu[2+3*(j+k1+lj)]*conjf(dcu[2+3*(j+k1+lj)]) + dcu[3*(j+kj+l1)]*conjf(dcu[3*(j+kj+l1)]) + dcu[1+3*(j+kj+l1)]*conjf(dcu[1+3*(j+kj+l1)]) + dcu[2+3*(j+kj+l1)]*conjf(dcu[2+3*(j+kj+l1)]) + dcu[3*(j+k1+l1)]*conjf(dcu[3*(j+k1+l1)]) + dcu[1+3*(j+k1+l1)]*conjf(dcu[1+3*(j+k1+l1)]) + dcu[2+3*(j+k1+l1)]*conjf(dcu[2+3*(j+k1+l1)])); } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; at2 = -ci2*crealf(ffe[kk+ll]); at1 = at2*cimagf(ffe[kk+ll]); at2 = at2*at2; exyz[3*(kj+lj)] = at1*dcu[3*(kj+lj)]; exyz[1+3*(kj+lj)] = at1*dcu[1+3*(kj+lj)]; exyz[2+3*(kj+lj)] = at1*dcu[2+3*(kj+lj)]; exyz[3*(k1+lj)] = zero; exyz[1+3*(k1+lj)] = zero; exyz[2+3*(k1+lj)] = zero; exyz[3*(kj+l1)] = at1*dcu[3*(kj+l1)]; exyz[1+3*(kj+l1)] = at1*dcu[1+3*(kj+l1)]; exyz[2+3*(kj+l1)] = at1*dcu[2+3*(kj+l1)]; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at2*(dcu[3*(kj+lj)]*conjf(dcu[3*(kj+lj)]) + dcu[1+3*(kj+lj)]*conjf(dcu[1+3*(kj+lj)]) + dcu[2+3*(kj+lj)]*conjf(dcu[2+3*(kj+lj)]) + dcu[3*(kj+l1)]*conjf(dcu[3*(kj+l1)]) + dcu[1+3*(kj+l1)]*conjf(dcu[1+3*(kj+l1)]) + dcu[2+3*(kj+l1)]*conjf(dcu[2+3*(kj+l1)])); } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+ll]); at1 = at2*cimagf(ffe[j+ll]); at2 = at2*at2; exyz[3*(j+lj)] = at1*dcu[3*(j+lj)]; exyz[1+3*(j+lj)] = at1*dcu[1+3*(j+lj)]; exyz[2+3*(j+lj)] = at1*dcu[2+3*(j+lj)]; exyz[3*(j+k1+lj)] = zero; exyz[1+3*(j+k1+lj)] = zero; exyz[2+3*(j+k1+lj)] = zero; exyz[3*(j+l1)] = at1*dcu[3*(j+l1)]; exyz[1+3*(j+l1)] = at1*dcu[1+3*(j+l1)]; exyz[2+3*(j+l1)] = at1*dcu[2+3*(j+l1)]; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at2*(dcu[3*(j+lj)]*conjf(dcu[3*(j+lj)]) + dcu[1+3*(j+lj)]*conjf(dcu[1+3*(j+lj)]) + dcu[2+3*(j+lj)]*conjf(dcu[2+3*(j+lj)]) + dcu[3*(j+l1)]*conjf(dcu[3*(j+l1)]) + dcu[1+3*(j+l1)]*conjf(dcu[1+3*(j+l1)]) + dcu[2+3*(j+l1)]*conjf(dcu[2+3*(j+l1)])); } /* mode numbers kx = 0, nx/2 */ at2 = -ci2*crealf(ffe[ll]); at1 = at2*cimagf(ffe[ll]); at2 = at2*at2; exyz[3*lj] = at1*dcu[3*lj]; exyz[1+3*lj] = at1*dcu[1+3*lj]; exyz[2+3*lj] = at1*dcu[2+3*lj]; exyz[3*(k1+lj)] = zero; exyz[1+3*(k1+lj)] = zero; exyz[2+3*(k1+lj)] = zero; exyz[3*l1] = zero; exyz[1+3*l1] = zero; exyz[2+3*l1] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at2*(dcu[3*lj]*conjf(dcu[3*lj]) + dcu[1+3*lj]*conjf(dcu[1+3*lj]) + dcu[2+3*lj]*conjf(dcu[2+3*lj])); sum1 += wp; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; sum2 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,at1,at2,wp) \ reduction(+:sum2) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+kk]); at1 = at2*cimagf(ffe[j+kk]); at2 = at2*at2; exyz[3*(j+kj)] = at1*dcu[3*(j+kj)]; exyz[1+3*(j+kj)] = at1*dcu[1+3*(j+kj)]; exyz[2+3*(j+kj)] = at1*dcu[2+3*(j+kj)]; exyz[3*(j+k1)] = at1*dcu[3*(j+k1)]; exyz[1+3*(j+k1)] = at1*dcu[1+3*(j+k1)]; exyz[2+3*(j+k1)] = at1*dcu[2+3*(j+k1)]; exyz[3*(j+kj+l1)] = zero; exyz[1+3*(j+kj+l1)] = zero; exyz[2+3*(j+kj+l1)] = zero; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at2*(dcu[3*(j+kj)]*conjf(dcu[3*(j+kj)]) + dcu[1+3*(j+kj)]*conjf(dcu[1+3*(j+kj)]) + dcu[2+3*(j+kj)]*conjf(dcu[2+3*(j+kj)]) + dcu[3*(j+k1)]*conjf(dcu[3*(j+k1)]) + dcu[1+3*(j+k1)]*conjf(dcu[1+3*(j+k1)]) + dcu[2+3*(j+k1)]*conjf(dcu[2+3*(j+k1)])); } /* mode numbers kx = 0, nx/2 */ at2 = -ci2*crealf(ffe[kk]); at1 = at2*cimagf(ffe[kk]); at2 = at2*at2; exyz[3*kj] = at1*dcu[3*kj]; exyz[1+3*kj] = at1*dcu[1+3*kj]; exyz[2+3*kj] = at1*dcu[2+3*kj]; exyz[3*k1] = zero; exyz[1+3*k1] = zero; exyz[2+3*k1] = zero; exyz[3*(kj+l1)] = zero; exyz[1+3*(kj+l1)] = zero; exyz[2+3*(kj+l1)] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at2*(dcu[3*kj]*conjf(dcu[3*kj]) + dcu[1+3*kj]*conjf(dcu[1+3*kj]) + dcu[2+3*kj]*conjf(dcu[2+3*kj])); sum2 += wp; } wp = 0.0; /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j]); at1 = at2*cimagf(ffe[j]); at2 = at2*at2; exyz[3*j] = at1*dcu[3*j]; exyz[1+3*j] = at1*dcu[1+3*j]; exyz[2+3*j] = at1*dcu[2+3*j]; exyz[3*(j+k1)]= zero; exyz[1+3*(j+k1)] = zero; exyz[2+3*(j+k1)] = zero; exyz[3*(j+l1)] = zero; exyz[1+3*(j+l1)] = zero; exyz[2+3*(j+l1)] = zero; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at2*(dcu[3*j]*conjf(dcu[3*j]) + dcu[1+3*j]*conjf(dcu[1+3*j]) + dcu[2+3*j]*conjf(dcu[2+3*j])); } exyz[0] = zero; exyz[1] = zero; exyz[2] = zero; exyz[3*k1] = zero; exyz[1+3*k1] = zero; exyz[2+3*k1] = zero; exyz[3*l1] = zero; exyz[1+3*l1] = zero; exyz[2+3*l1] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; *wf = (sum1 + sum2 + wp)*((float) nx)*((float) ny) *((float) nz)/crealf(ffe[0]); return; /* calculate unsmoothed transverse electric field and sum field energy */ L130: sum1 = 0.0; /* mode numbers 0 < kx < nx/2, 0 < ky < ny/2, and 0 < kz < nz/2 */ #pragma omp parallel { #pragma omp for nowait \ private(j,k,l,k1,l1,ll,lj,kk,kj,at1,at2,wp) \ reduction(+:sum1) for (l = 1; l < nzh; l++) { dkz = dnz*(float) l; ll = nxyhd*l; lj = nxvyh*l; l1 = nxvyh*nz - lj; wp = 0.0; for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+kk+ll]); at1 = at2*at2; exyz[3*(j+kj+lj)] = at2*dcu[3*(j+kj+lj)]; exyz[1+3*(j+kj+lj)] = at2*dcu[1+3*(j+kj+lj)]; exyz[2+3*(j+kj+lj)] = at2*dcu[2+3*(j+kj+lj)]; exyz[3*(j+k1+lj)] = at2*dcu[3*(j+k1+lj)]; exyz[1+3*(j+k1+lj)] = at2*dcu[1+3*(j+k1+lj)]; exyz[2+3*(j+k1+lj)] = at2*dcu[2+3*(j+k1+lj)]; exyz[3*(j+kj+l1)] = at2*dcu[3*(j+kj+l1)]; exyz[1+3*(j+kj+l1)] = at2*dcu[1+3*(j+kj+l1)]; exyz[2+3*(j+kj+l1)] = at2*dcu[2+3*(j+kj+l1)]; exyz[3*(j+k1+l1)] = at2*dcu[3*(j+k1+l1)]; exyz[1+3*(j+k1+l1)] = at2*dcu[1+3*(j+k1+l1)]; exyz[2+3*(j+k1+l1)] = at2*dcu[2+3*(j+k1+l1)]; wp += at1*(dcu[3*(j+kj+lj)]*conjf(dcu[3*(j+kj+lj)]) + dcu[1+3*(j+kj+lj)]*conjf(dcu[1+3*(j+kj+lj)]) + dcu[2+3*(j+kj+lj)]*conjf(dcu[2+3*(j+kj+lj)]) + dcu[3*(j+k1+lj)]*conjf(dcu[3*(j+k1+lj)]) + dcu[1+3*(j+k1+lj)]*conjf(dcu[1+3*(j+k1+lj)]) + dcu[2+3*(j+k1+lj)]*conjf(dcu[2+3*(j+k1+lj)]) + dcu[3*(j+kj+l1)]*conjf(dcu[3*(j+kj+l1)]) + dcu[1+3*(j+kj+l1)]*conjf(dcu[1+3*(j+kj+l1)]) + dcu[2+3*(j+kj+l1)]*conjf(dcu[2+3*(j+kj+l1)]) + dcu[3*(j+k1+l1)]*conjf(dcu[3*(j+k1+l1)]) + dcu[1+3*(j+k1+l1)]*conjf(dcu[1+3*(j+k1+l1)]) + dcu[2+3*(j+k1+l1)]*conjf(dcu[2+3*(j+k1+l1)])); } } /* mode numbers kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; at2 = -ci2*crealf(ffe[kk+ll]); at1 = at2*at2; exyz[3*(kj+lj)] = at2*dcu[3*(kj+lj)]; exyz[1+3*(kj+lj)] = at2*dcu[1+3*(kj+lj)]; exyz[2+3*(kj+lj)] = at2*dcu[2+3*(kj+lj)]; exyz[3*(k1+lj)] = zero; exyz[1+3*(k1+lj)] = zero; exyz[2+3*(k1+lj)] = zero; exyz[3*(kj+l1)] = at2*dcu[3*(kj+l1)]; exyz[1+3*(kj+l1)] = at2*dcu[1+3*(kj+l1)]; exyz[2+3*(kj+l1)] = at2*dcu[2+3*(kj+l1)]; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at1*(dcu[3*(kj+lj)]*conjf(dcu[3*(kj+lj)]) + dcu[1+3*(kj+lj)]*conjf(dcu[1+3*(kj+lj)]) + dcu[2+3*(kj+lj)]*conjf(dcu[2+3*(kj+lj)]) + dcu[3*(kj+l1)]*conjf(dcu[3*(kj+l1)]) + dcu[1+3*(kj+l1)]*conjf(dcu[1+3*(kj+l1)]) + dcu[2+3*(kj+l1)]*conjf(dcu[2+3*(kj+l1)])); } /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+ll]); at1 = at2*at2; exyz[3*(j+lj)] = at2*dcu[3*(j+lj)]; exyz[1+3*(j+lj)] = at2*dcu[1+3*(j+lj)]; exyz[2+3*(j+lj)] = at2*dcu[2+3*(j+lj)]; exyz[3*(j+k1+lj)] = zero; exyz[1+3*(j+k1+lj)] = zero; exyz[2+3*(j+k1+lj)] = zero; exyz[3*(j+l1)] = at2*dcu[3*(j+l1)]; exyz[1+3*(j+l1)] = at2*dcu[1+3*(j+l1)]; exyz[2+3*(j+l1)] = at2*dcu[2+3*(j+l1)]; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at1*(dcu[3*(j+lj)]*conjf(dcu[3*(j+lj)]) + dcu[1+3*(j+lj)]*conjf(dcu[1+3*(j+lj)]) + dcu[2+3*(j+lj)]*conjf(dcu[2+3*(j+lj)]) + dcu[3*(j+l1)]*conjf(dcu[3*(j+l1)]) + dcu[1+3*(j+l1)]*conjf(dcu[1+3*(j+l1)]) + dcu[2+3*(j+l1)]*conjf(dcu[2+3*(j+l1)])); } /* mode numbers kx = 0, nx/2 */ at2 = -ci2*crealf(ffe[ll]); at1 = at2*at2; exyz[3*lj] = at2*dcu[3*lj]; exyz[1+3*lj] = at2*dcu[1+3*lj]; exyz[2+3*lj] = at2*dcu[2+3*lj]; exyz[3*(k1+lj)] = zero; exyz[1+3*(k1+lj)] = zero; exyz[2+3*(k1+lj)] = zero; exyz[3*l1] = zero; exyz[1+3*l1] = zero; exyz[2+3*l1] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at1*(dcu[3*lj]*conjf(dcu[3*lj]) + dcu[1+3*lj]*conjf(dcu[1+3*lj]) + dcu[2+3*lj]*conjf(dcu[2+3*lj])); sum1 += wp; } } /* mode numbers kz = 0, nz/2 */ l1 = nxvyh*nzh; sum2 = 0.0; #pragma omp parallel for \ private(j,k,k1,kk,kj,at1,at2,wp) \ reduction(+:sum2) for (k = 1; k < nyh; k++) { dky = dny*(float) k; kk = nxhd*k; kj = nxvh*k; k1 = nxvh*ny - kj; wp = 0.0; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j+kk]); at1 = at2*at2; exyz[3*(j+kj)] = at2*dcu[3*(j+kj)]; exyz[1+3*(j+kj)] = at2*dcu[1+3*(j+kj)]; exyz[2+3*(j+kj)] = at2*dcu[2+3*(j+kj)]; exyz[3*(j+k1)] = at2*dcu[3*(j+k1)]; exyz[1+3*(j+k1)] = at2*dcu[1+3*(j+k1)]; exyz[2+3*(j+k1)] = at2*dcu[2+3*(j+k1)]; exyz[3*(j+kj+l1)] = zero; exyz[1+3*(j+kj+l1)] = zero; exyz[2+3*(j+kj+l1)] = zero; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at1*(dcu[3*(j+kj)]*conjf(dcu[3*(j+kj)]) + dcu[1+3*(j+kj)]*conjf(dcu[1+3*(j+kj)]) + dcu[2+3*(j+kj)]*conjf(dcu[2+3*(j+kj)]) + dcu[3*(j+k1)]*conjf(dcu[3*(j+k1)]) + dcu[1+3*(j+k1)]*conjf(dcu[1+3*(j+k1)]) + dcu[2+3*(j+k1)]*conjf(dcu[2+3*(j+k1)])); } /* mode numbers kx = 0, nx/2 */ at2 = -ci2*crealf(ffe[kk]); at1 = at2*at2; exyz[3*kj] = at2*dcu[3*kj]; exyz[1+3*kj] = at2*dcu[1+3*kj]; exyz[2+3*kj] = at2*dcu[2+3*kj]; exyz[3*k1]= zero; exyz[1+3*k1] = zero; exyz[2+3*k1] = zero; exyz[3*(kj+l1)] = zero; exyz[1+3*(kj+l1)] = zero; exyz[2+3*(kj+l1)] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; wp += at1*(dcu[3*kj]*conjf(dcu[3*kj]) + dcu[1+3*kj]*conjf(dcu[1+3*kj]) + dcu[2+3*kj]*conjf(dcu[2+3*kj])); sum2 += wp; } wp = 0.0; /* mode numbers ky = 0, ny/2 */ k1 = nxvh*nyh; for (j = 1; j < nxh; j++) { at2 = -ci2*crealf(ffe[j]); at1 = at2*at2; exyz[3*j] = at2*dcu[3*j]; exyz[1+3*j] = at2*dcu[1+3*j]; exyz[2+3*j] = at2*dcu[2+3*j]; exyz[3*(j+k1)] = zero; exyz[1+3*(j+k1)] = zero; exyz[2+3*(j+k1)] = zero; exyz[3*(j+l1)] = zero; exyz[1+3*(j+l1)] = zero; exyz[2+3*(j+l1)] = zero; exyz[3*(j+k1+l1)] = zero; exyz[1+3*(j+k1+l1)] = zero; exyz[2+3*(j+k1+l1)] = zero; wp += at1*(dcu[3*j]*conjf(dcu[3*j]) + dcu[1+3*j]*conjf(dcu[1+3*j]) + dcu[2+3*j]*conjf(dcu[2+3*j])); } exyz[0] = zero; exyz[1] = zero; exyz[2] = zero; exyz[3*k1] = zero; exyz[1+3*k1] = zero; exyz[2+3*k1] = zero; exyz[3*l1] = zero; exyz[1+3*l1] = zero; exyz[2+3*l1] = zero; exyz[3*(k1+l1)] = zero; exyz[1+3*(k1+l1)] = zero; exyz[2+3*(k1+l1)] = zero; *wf = (sum1+sum2+wp)*((float) nx)*((float) ny) *((float) nz)/crealf(ffe[0]); return; } /*--------------------------------------------------------------------*/ void caddvrfield3(float a[], float b[], float c[], int ndim, int nxe, int nye, int nze) { /* this subroutine calculates a = b + c for real vector fields local data */ int i, j, k, l, nnxye, ll; nnxye = ndim*nxe*nye; #pragma omp parallel for private(i,j,k,l,ll) for (l = 0; l < nze; l++) { ll = nnxye*l; for (k = 0; k < nye; k++) { for (j = 0; j < nxe; j++) { for (i = 0; i < ndim; i++) { a[i+ndim*(j+nxe*k)+ll] = b[i+ndim*(j+nxe*k)+ll] + c[i+ndim*(j+nxe*k)+ll]; } } } } return; } /*--------------------------------------------------------------------*/ void cwfft3rinit(int mixup[], float complex sct[], int indx, int indy, int indz, int nxhyzd, int nxyzhd) { /* this subroutine calculates tables needed by a three dimensional real to complex fast fourier transform and its inverse. input: indx, indy, indz, nxhyzd, nxyzhd output: mixup, sct mixup = array of bit reversed addresses sct = sine/cosine table indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = one half of maximum of (nx,ny,nz) written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, ny, nz, nxyz, nxhyz, nxyzh; int j, k, lb, ll, jb, it; float dnxyz, arg; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; ny = 1L<<indy; nz = 1L<<indz; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; /* bit-reverse index table: mixup[j] = 1 + reversed bits of j */ for (j = 0; j < nxhyz; j++) { lb = j; ll = 0; for (k = 0; k < ndx1yz; k++) { jb = lb/2; it = lb - 2*jb; lb = jb; ll = 2*ll + it; } mixup[j] = ll + 1; } /* sine/cosine table for the angles 2*n*pi/nxyz */ nxyzh = nxyz/2; dnxyz = 6.28318530717959/(float) nxyz; for (j = 0; j < nxyzh; j++) { arg = dnxyz*(float) j; sct[j] = cosf(arg) - sinf(arg)*_Complex_I; } return; } /*--------------------------------------------------------------------*/ void cfft3rmxy(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nzi, int nzp, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* this subroutine performs the x-y part of a three dimensional real to complex fast fourier transform and its inverse, for a subset of z, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, an inverse fourier transform in x and y is performed f[i][m][n] = (1/nx*ny*nz)*sum(f[i][k][j]*exp(-sqrt(-1)*2pi*n*j/nx)* exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, a forward fourier transform in x and y is performed f[l][k][j] = sum(f[l][m][n]*exp(sqrt(-1)*2pi*n*j/nx)* exp(sqrt(-1)*2pi*m*k/ny)) mixup = array of bit reversed addresses sct = sine/cosine table nzi = initial z index used nzp = number of z indices used nxhd = first dimension of f nyd,nzd = second and third dimensions of f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0] = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, nxhh, ny, nyh; int nz, nxyz, nxhyz, nzt, nrx, nry, nrxb, nryb, nxhyd; int i, j, k, l, n, nn, j1, j2, k1, k2, ns, ns2, km, kmr, joff; float ani; float complex t1, t2, t3; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nzt = nzi + nzp - 1; nxhyd = nxhd*nyd; if (isign > 0) goto L180; /* inverse fourier transform */ nrxb = nxhyz/nxh; nrx = nxyz/nxh; nryb = nxhyz/ny; nry = nxyz/ny; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,nn,joff,ani,t1,t2,t3) for (n = nzi-1; n < nzt; n++) { nn = nxhyd*n; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nxhd*i + nn; t1 = f[j1+joff]; f[j1+joff] = f[j+joff]; f[j+joff] = t1; } } } /* first transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; for (i = 0; i < ny; i++) { joff = nxhd*i + nn; t2 = t1*f[j2+joff]; f[j2+joff] = f[j1+joff] - t2; f[j1+joff] += t2; } } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxyz/nx; ani = 0.5/(((float) nx)*((float) ny)*((float) nz)); for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nxhd*k + nn; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = ani*(t1 + t2); f[nxh-j+joff] = ani*conjf(t1 - t2); } } ani = 2.0*ani; for (k = 0; k < ny; k++) { joff = nxhd*k + nn; f[nxhh+joff] = ani*conjf(f[nxhh+joff]); f[joff] = ani*((crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I); } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nxhd*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1 + nn; for (i = 0; i < nxh; i++) { t1 = f[i+k1]; f[i+k1] = f[i+joff]; f[i+joff] = t1; } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd*(j + k1) + nn; j2 = nxhd*(j + k2) + nn; t1 = sct[kmr*j]; for (i = 0; i < nxh; i++) { t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } } ns = ns2; } /* unscramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nxhd*k; k1 = nxhd*ny - joff + nn; joff += nn; t1 = f[k1]; f[k1] = 0.5*(cimagf(f[joff] + t1) + crealf(f[joff] - t1)*_Complex_I); f[joff] = 0.5*(crealf(f[joff] + t1) + cimagf(f[joff] - t1)*_Complex_I); } } return; /* forward fourier transform */ L180: nryb = nxhyz/ny; nry = nxyz/ny; nrxb = nxhyz/nxh; nrx = nxyz/nxh; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,nn,joff,t1,t2,t3) for (n = nzi-1; n < nzt; n++) { nn = nxhyd*n; /* scramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nxhd*k; k1 = nxhd*ny - joff + nn; joff += nn; t1 = cimagf(f[k1]) + crealf(f[k1])*_Complex_I; f[k1] = conjf(f[joff] - t1); f[joff] += t1; } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nxhd*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd*k1 + nn; for (i = 0; i < nxh; i++) { t1 = f[i+k1]; f[i+k1] = f[i+joff]; f[i+joff] = t1; } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd*(j + k1) + nn; j2 = nxhd*(j + k2) + nn; t1 = conjf(sct[kmr*j]); for (i = 0; i < nxh; i++) { t2 = t1*f[i+j2]; f[i+j2] = f[i+j1] - t2; f[i+j1] += t2; } } } ns = ns2; } /* scramble coefficients */ kmr = nxyz/nx; for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nxhd*k + nn; t2 = conjf(f[nxh-j+joff]); t1 = f[j+joff] + t2; t2 = (f[j+joff] - t2)*t3; f[j+joff] = t1 + t2; f[nxh-j+joff] = conjf(t1 - t2); } } for (k = 0; k < ny; k++) { joff = nxhd*k + nn; f[nxhh+joff] = 2.0*conjf(f[nxhh+joff]); f[joff] = (crealf(f[joff]) + cimagf(f[joff])) + (crealf(f[joff]) - cimagf(f[joff]))*_Complex_I; } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nxhd*i + nn; t1 = f[j1+joff]; f[j1+joff] = f[j+joff]; f[j+joff] = t1; } } } /* finally transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = conjf(sct[kmr*j]); for (i = 0; i < ny; i++) { joff = nxhd*i + nn; t2 = t1*f[j2+joff]; f[j2+joff] = f[j1+joff] - t2; f[j1+joff] += t2; } } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cfft3rmxz(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nyi, int nyp, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* this subroutine performs the z part of a three dimensional real to complex fast fourier transform and its inverse, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, an inverse fourier transform in z is performed f[l][k][j] = sum(f[i][k][j]*exp(-sqrt(-1)*2pi*l*i/nz)) if isign = 1, a forward fourier transform in z is performed f[i][m][n] = sum(f[l][m][n]*exp(sqrt(-1)*2pi*l*i/nz)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = first dimension of f nyd,nzd = second and third dimensions of f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0] = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, ny, nyh; int nz, nzh, nxyz, nxhyz, nyt, nrz, nrzb, nxhyd, ioff; int i, j, k, l, n, ll, j1, j2, k1, k2, l1, ns, ns2, km, kmr, i0, i1; float complex t1, t2; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nzh = nz/2; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nyt = nyi + nyp - 1; nxhyd = nxhd*nyd; if (isign > 0) goto L90; /* inverse fourier transform */ nrzb = nxhyz/nz; nrz = nxyz/nz; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,ll,l1,i0,i1,ioff,t1,t2) for (n = nyi-1; n < nyt; n++) { ioff = nxhd*n; /* bit-reverse array elements in z */ for (l = 0; l < nz; l++) { ll = nxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nxhyd*l1; i0 = ioff + ll; i1 = ioff + l1; for (i = 0; i < nxh; i++) { t1 = f[i+i1]; f[i+i1] = f[i+i0]; f[i+i0] = t1; } } } /* finally transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhyd*(j + k1); j2 = nxhyd*(j + k2); t1 = sct[kmr*j]; i0 = ioff + j1; i1 = ioff + j2; for (i = 0; i < nxh; i++) { t2 = t1*f[i+i1]; f[i+i1] = f[i+i0] - t2; f[i+i0] += t2; } } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nxhyd*n; l1 = nxhyd*nz - ll; if (nyi==1) { t1 = f[l1]; f[l1] = 0.5*(cimagf(f[ll] + t1) + crealf(f[ll] - t1)*_Complex_I); f[ll] = 0.5*(crealf(f[ll] + t1) + cimagf(f[ll] - t1)*_Complex_I); } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { i1 = nxhd*nyh; i0 = i1 + ll; i1 += l1; t1 = f[i1]; f[i1] = 0.5*(cimagf(f[i0] + t1) + crealf(f[i0] - t1)*_Complex_I); f[i0] = 0.5*(crealf(f[i0] + t1) + cimagf(f[i0] - t1)*_Complex_I); } } return; /* forward fourier transform */ L90: nrzb = nxhyz/nz; nrz = nxyz/nz; /* scramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nxhyd*n; l1 = nxhyd*nz - ll; if (nyi==1) { t1 = cimagf(f[l1]) + crealf(f[l1])*_Complex_I; f[l1] = conjf(f[ll] - t1); f[ll] += t1; } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { i1 = nxhd*nyh; i0 = i1 + ll; i1 += l1; t1 = cimagf(f[i1]) + crealf(f[i1])*_Complex_I; f[i1] = conjf(f[i0] - t1); f[i0] += t1; } } /* bit-reverse array elements in z */ #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,ll,l1,i0,i1,ioff,t1,t2) for (n = nyi-1; n < nyt; n++) { ioff = nxhd*n; for (l = 0; l < nz; l++) { ll = nxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nxhyd*l1; i0 = ioff + ll; i1 = ioff + l1; for (i = 0; i < nxh; i++) { t1 = f[i+i1]; f[i+i1] = f[i+i0]; f[i+i0] = t1; } } } /* first transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhyd*(j + k1); j2 = nxhyd*(j + k2); t1 = conjf(sct[kmr*j]); i0 = ioff + j1; i1 = ioff + j2; for (i = 0; i < nxh; i++) { t2 = t1*f[i+i1]; f[i+i1] = f[i+i0] - t2; f[i+i0] += t2; } } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cfft3rm3xy(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nzi, int nzp, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* this subroutine performs the x-y part of 3 three dimensional complex to real fast fourier transforms and their inverses, for a subset of z, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, three inverse fourier transforms in x and y are performed f[i][m][n][0:2] = (1/nx*ny*nz)*sum(f[i][k][j][0:2]*exp(-sqrt(-1)*2pi*n*j/nx) *exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, three forward fourier transforms in x and y are performed f[l][k][j][0:2] = sum(f[l][m][n][0:2]*exp(sqrt(-1)*2pi*n*j/nx)* exp(sqrt(-1)*2pi*m*k/ny)) mixup = array of bit reversed addresses sct = sine/cosine table nzi = initial z index used nzp = number of z indices used nxhd = second dimension of f nyd,nzd = third and fourth dimensions of f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j][0:2] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0][0:2] = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0][0:2] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0][0:2] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0][0:2]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0][0:2]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0][0:2]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0][0:2]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, nxhh, ny, nyh; int nz, nxyz, nxhyz, nzt, nrx, nry, nrxb, nryb, nxhd3, nxhyd; int i, j, k, l, n, nn, jj, j1, j2, k1, k2, ns, ns2, km, kmr, joff; float at1, at2, ani; float complex t1, t2, t3, t4; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nzt = nzi + nzp - 1; nxhd3 = 3*nxhd; nxhyd = nxhd3*nyd; if (isign > 0) goto L230; /* inverse fourier transform */ nrxb = nxhyz/nxh; nrx = nxyz/nxh; nryb = nxhyz/ny; nry = nxyz/ny; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,joff,at1,at2,ani,t1, \ t2,t3,t4) for (n = nzi-1; n < nzt; n++) { nn = nxhyd*n; /* swap complex components */ for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; for (j = 0; j < nxh; j++) { at1 = crealf(f[2+3*j+joff]); f[2+3*j+joff] = crealf(f[1+3*j+joff]) + cimagf(f[2+3*j+joff])*_Complex_I; at2 = cimagf(f[1+3*j+joff]); f[1+3*j+joff] = cimagf(f[3*j+joff]) + at1*_Complex_I; f[3*j+joff] = crealf(f[3*j+joff]) + at2*_Complex_I; } } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; t1 = f[3*j1+joff]; t2 = f[1+3*j1+joff]; t3 = f[2+3*j1+joff]; f[3*j1+joff] = f[3*j+joff]; f[1+3*j1+joff] = f[1+3*j+joff]; f[2+3*j1+joff] = f[2+3*j+joff]; f[3*j+joff] = t1; f[1+3*j+joff] = t2; f[2+3*j+joff] = t3; } } } /* first transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; t2 = t1*f[3*j2+joff]; t3 = t1*f[1+3*j2+joff]; t4 = t1*f[2+3*j2+joff]; f[3*j2+joff] = f[3*j1+joff] - t2; f[1+3*j2+joff] = f[1+3*j1+joff] - t3; f[2+3*j2+joff] = f[2+3*j1+joff] - t4; f[3*j1+joff] += t2; f[1+3*j1+joff] += t3; f[2+3*j1+joff] += t4; } } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxyz/nx; ani = 0.5/(((float) nx)*((float) ny)*((float) nz)); for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; for (jj = 0; jj < 3; jj++) { t2 = conjf(f[jj+3*(nxh-j)+joff]); t1 = f[jj+3*j+joff] + t2; t2 = (f[jj+3*j+joff] - t2)*t3; f[jj+3*j+joff] = ani*(t1 + t2); f[jj+3*(nxh-j)+joff] = ani*conjf(t1 - t2); } } } ani = 2.0*ani; for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; for (jj = 0; jj < 3; jj++) { f[jj+3*nxhh+joff] = ani*conjf(f[jj+3*nxhh+joff]); f[jj+joff] = ani*((crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I); } } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd3*k1 + nn; for (i = 0; i < nxh; i++) { t1 = f[3*i+k1]; t2 = f[1+3*i+k1]; t3 = f[2+3*i+k1]; f[3*i+k1] = f[3*i+joff]; f[1+3*i+k1] = f[1+3*i+joff]; f[2+3*i+k1] = f[2+3*i+joff]; f[3*i+joff] = t1; f[1+3*i+joff] = t2; f[2+3*i+joff] = t3; } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd3*(j + k1) + nn; j2 = nxhd3*(j + k2) + nn; t1 = sct[kmr*j]; for (i = 0; i < nxh; i++) { t2 = t1*f[3*i+j2]; t3 = t1*f[1+3*i+j2]; t4 = t1*f[2+3*i+j2]; f[3*i+j2] = f[3*i+j1] - t2; f[1+3*i+j2] = f[1+3*i+j1] - t3; f[2+3*i+j2] = f[2+3*i+j1] - t4; f[3*i+j1] += t2; f[1+3*i+j1] += t3; f[2+3*i+j1] += t4; } } } ns = ns2; } /* unscramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nxhd3*k; k1 = nxhd3*ny - joff + nn; joff += nn; for (jj = 0; jj < 3; jj++) { t1 = f[jj+k1]; f[jj+k1] = 0.5*(cimagf(f[jj+joff] + t1) + crealf(f[jj+joff] - t1)*_Complex_I); f[jj+joff] = 0.5*(crealf(f[jj+joff] + t1) + cimagf(f[jj+joff] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L230: nryb = nxhyz/ny; nry = nxyz/ny; nrxb = nxhyz/nxh; nrx = nxyz/nxh; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,joff,at1,at2,t1,t2, \ t3,t4) for (n = nzi-1; n < nzt; n++) { nn = nxhyd*n; /* scramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nxhd3*k; k1 = nxhd3*ny - joff + nn; joff += nn; for (jj = 0; jj < 3; jj++) { t1 = cimagf(f[jj+k1]) + crealf(f[jj+k1])*_Complex_I; f[jj+k1] = conjf(f[jj+joff] - t1); f[jj+joff] += t1; } } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nxhd3*k1 + nn; for (i = 0; i < nxh; i++) { t1 = f[3*i+k1]; t2 = f[1+3*i+k1]; t3 = f[2+3*i+k1]; f[3*i+k1] = f[3*i+joff]; f[1+3*i+k1] = f[1+3*i+joff]; f[2+3*i+k1] = f[2+3*i+joff]; f[3*i+joff] = t1; f[1+3*i+joff] = t2; f[2+3*i+joff] = t3; } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhd3*(j + k1) + nn; j2 = nxhd3*(j + k2) + nn; t1 = conjf(sct[kmr*j]); for (i = 0; i < nxh; i++) { t2 = t1*f[3*i+j2]; t3 = t1*f[1+3*i+j2]; t4 = t1*f[2+3*i+j2]; f[3*i+j2] = f[3*i+j1] - t2; f[1+3*i+j2] = f[1+3*i+j1] - t3; f[2+3*i+j2] = f[2+3*i+j1] - t4; f[3*i+j1] += t2; f[1+3*i+j1] += t3; f[2+3*i+j1] += t4; } } } ns = ns2; } /* scramble coefficients */ kmr = nxyz/nx; for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; for (jj = 0; jj < 3; jj++) { t2 = conjf(f[jj+3*(nxh-j)+joff]); t1 = f[jj+3*j+joff] + t2; t2 = (f[jj+3*j+joff] - t2)*t3; f[jj+3*j+joff] = t1 + t2; f[jj+3*(nxh-j)+joff] = conjf(t1 - t2); } } } for (k = 0; k < ny; k++) { joff = nxhd3*k + nn; for (jj = 0; jj < 3; jj++) { f[jj+3*nxhh+joff] = 2.0*conjf(f[jj+3*nxhh+joff]); f[jj+joff] = (crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I; } } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; t1 = f[3*j1+joff]; t2 = f[1+3*j1+joff]; t3 = f[2+3*j1+joff]; f[3*j1+joff] = f[3*j+joff]; f[1+3*j1+joff] = f[1+3*j+joff]; f[2+3*j1+joff] = f[2+3*j+joff]; f[3*j+joff] = t1; f[1+3*j+joff] = t2; f[2+3*j+joff] = t3; } } } /* finally transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = conjf(sct[kmr*j]); for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; t2 = t1*f[3*j2+joff]; t3 = t1*f[1+3*j2+joff]; t4 = t1*f[2+3*j2+joff]; f[3*j2+joff] = f[3*j1+joff] - t2; f[1+3*j2+joff] = f[1+3*j1+joff] - t3; f[2+3*j2+joff] = f[2+3*j1+joff] - t4; f[3*j1+joff] += t2; f[1+3*j1+joff] += t3; f[2+3*j1+joff] += t4; } } } ns = ns2; } /* swap complex components */ for (i = 0; i < ny; i++) { joff = nxhd3*i + nn; for (j = 0; j < nxh; j++) { at1 = crealf(f[2+3*j+joff]); f[2+3*j+joff] = cimagf(f[1+3*j+joff]) + cimagf(f[2+3*j+joff])*_Complex_I; at2 = crealf(f[1+3*j+joff]); f[1+3*j+joff] = at1 + cimagf(f[3*j+joff])*_Complex_I; f[3*j+joff] = crealf(f[3*j+joff]) + at2*_Complex_I; } } } return; } /*--------------------------------------------------------------------*/ void cfft3rm3z(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nyi, int nyp, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* this subroutine performs the z part of 3 three dimensional complex to real fast fourier transforms and their inverses, for a subset of y, using complex arithmetic, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: N*(5*log2(N) + 19/2) for isign = 1, approximate flop count: N*(5*log2(N) + 15/2) where N = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, three inverse fourier transforms in z are performed f[l][k][j][0:2] = sum(f[i][k][j][0:2]*exp(-sqrt(-1)*2pi*l*i/nz)) if isign = 1, three forward fourier transforms in z are performed f[i][m][n][0:2] = sum(f[l][m][n][0:2]*exp(sqrt(-1)*2pi*l*i/nz)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = second dimension of f nyd,nzd = third and fourth dimensions of f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j][0:2] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0][0:2], = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0][0:2] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0][0:2] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0][0:2]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0][0:2]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0][0:2]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0][0:2]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, ny, nyh; int nz, nzh, nxyz, nxhyz, nyt, nrz, nrzb, nxhd3, nxhyd, ioff; int i, j, k, l, n, ll, jj, j1, j2, k1, k2, l1, ns, ns2, km, kmr; int i0, i1; float complex t1, t2, t3, t4; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nzh = nz/2; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nyt = nyi + nyp - 1; nxhd3 = 3*nxhd; nxhyd = nxhd3*nyd; if (isign > 0) goto L110; /* inverse fourier transform */ nrzb = nxhyz/nz; nrz = nxyz/nz; /* bit-reverse array elements in z */ #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,ll,l1,i0,i1,ioff,t1,t2,t3, \ t4) for (n = nyi-1; n < nyt; n++) { ioff = nxhd3*n; for (l = 0; l < nz; l++) { ll = nxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nxhyd*l1; i0 = ioff + ll; i1 = ioff + l1; for (i = 0; i < nxh; i++) { t1 = f[3*i+i1]; t2 = f[1+3*i+i1]; t3 = f[2+3*i+i1]; f[3*i+i1] = f[3*i+i0]; f[1+3*i+i1] = f[1+3*i+i0]; f[2+3*i+i1] = f[2+3*i+i0]; f[3*i+i0] = t1; f[1+3*i+i0] = t2; f[2+3*i+i0] = t3; } } } /* finally transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhyd*(j + k1); j2 = nxhyd*(j + k2); t1 = sct[kmr*j]; i0 = ioff + j1; i1 = ioff + j2; for (i = 0; i < nxh; i++) { t2 = t1*f[3*i+i1]; t3 = t1*f[1+3*i+i1]; t4 = t1*f[2+3*i+i1]; f[3*i+i1] = f[3*i+i0] - t2; f[1+3*i+i1] = f[1+3*i+i0] - t3; f[2+3*i+i1] = f[2+3*i+i0] - t4; f[3*i+i0] += t2; f[1+3*i+i0] += t3; f[2+3*i+i0] += t4; } } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nxhyd*n; l1 = nxhyd*nz - ll; if (nyi==1) { for (jj = 0; jj < 3; jj++) { t1 = f[jj+l1]; f[jj+l1] = 0.5*(cimagf(f[jj+ll] + t1) + crealf(f[jj+ll] - t1)*_Complex_I); f[jj+ll] = 0.5*(crealf(f[jj+ll] + t1) + cimagf(f[jj+ll] - t1)*_Complex_I); } } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { for (jj = 0; jj < 3; jj++) { i1 = nxhd3*nyh; i0 = i1 + ll; i1 += l1; t1 = f[jj+i1]; f[jj+i1] = 0.5*(cimagf(f[jj+i0] + t1) + crealf(f[jj+i0] - t1)*_Complex_I); f[jj+i0] = 0.5*(crealf(f[jj+i0] + t1) + cimagf(f[jj+i0] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L110: nrzb = nxhyz/nz; nrz = nxyz/nz; /* scramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nxhyd*n; l1 = nxhyd*nz - ll; if (nyi==1) { for (jj = 0; jj < 3; jj++) { t1 = cimagf(f[jj+l1]) + crealf(f[jj+l1])*_Complex_I; f[jj+l1] = conjf(f[jj+ll] - t1); f[jj+ll] += t1; } } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { for (jj = 0; jj < 3; jj++) { i1 = nxhd3*nyh; i0 = i1 + ll; i1 += l1; t1 = cimagf(f[jj+i1]) + crealf(f[jj+i1])*_Complex_I; f[jj+i1] = conjf(f[jj+i0] - t1); f[jj+i0] += t1; } } } /* bit-reverse array elements in z */ #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,j1,j2,ll,l1,i0,i1,ioff,t1,t2,t3, \ t4) for (n = nyi-1; n < nyt; n++) { ioff = nxhd3*n; for (l = 0; l < nz; l++) { ll = nxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nxhyd*l1; i0 = ioff + ll; i1 = ioff+ l1; for (i = 0; i < nxh; i++) { t1 = f[3*i+i1]; t2 = f[1+3*i+i1]; t3 = f[2+3*i+i1]; f[3*i+i1] = f[3*i+i0]; f[1+3*i+i1] = f[1+3*i+i0]; f[2+3*i+i1] = f[2+3*i+i0]; f[3*i+i0] = t1; f[1+3*i+i0] = t2; f[2+3*i+i0] = t3; } } } /* first transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nxhyd*(j + k1); j2 = nxhyd*(j + k2); t1 = conjf(sct[kmr*j]); i0 = ioff + j1; i1 = ioff + j2; for (i = 0; i < nxh; i++) { t2 = t1*f[3*i+i1]; t3 = t1*f[1+3*i+i1]; t4 = t1*f[2+3*i+i1]; f[3*i+i1] = f[3*i+i0] - t2; f[1+3*i+i1] = f[1+3*i+i0] - t3; f[2+3*i+i1] = f[2+3*i+i0] - t4; f[3*i+i0] += t2; f[1+3*i+i0] += t3; f[2+3*i+i0] += t4; } } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cmswap3cn(float f[], float s[], int isign, int nxh, int ny, int nzi, int nzt, int nxhd, int nyd, int nzd, int ndim) { /* this subroutine swaps components for multiple ffts f = input array s = scratch array isign = (-1,1) = swap (real-to-complex,complex-to-real) nxh = complex dimension in x direction ny = complex dimension in y direction nzi/nzt = initial/final z index used nxhd = half of the second dimension of f nyd,nzd = third and fourth dimension of f ndim = leading dimension of array f local data */ int i, j, k, l, ll, ioff, nnxhd2, nnxhyd, nl, nk; /* swap complex components */ nnxhd2 = 2*ndim*nxhd; nnxhyd = nnxhd2*nyd; /* real to complex */ if (isign < 0) { #pragma omp for private(i,j,k,l,ll,nl,nk,ioff) for (l = nzi-1; l < nzt; l++) { ll = nnxhd2*l; nl = nnxhyd*l; for (k = 0; k < ny; k++) { nk = nnxhd2*k + nl; for (j = 0; j < nxh; j++) { ioff = 2*ndim*j + ll; for (i = 0; i < ndim; i++) { s[2*i+ioff] = f[i+ndim*(2*j)+nk]; s[2*i+ioff+1] = f[i+ndim*(2*j+1)+nk]; } } for (j = 0; j < nxh; j++) { ioff = 2*ndim*j + ll; for (i = 0; i < ndim; i++) { f[i+ndim*(2*j)+nk] = s[i+ioff]; } ioff += ndim; for (i = 0; i < ndim; i++) { f[i+ndim*(2*j+1)+nk] = s[i+ioff]; } } } } } /* complex to real */ else if (isign > 0) { #pragma omp for private(i,j,k,l,ll,nl,nk,ioff) for (l = nzi-1; l < nzt; l++) { ll = nnxhd2*l; nl = nnxhyd*l; for (k = 0; k < ny; k++) { nk = nnxhd2*k + nl; for (j = 0; j < nxh; j++) { ioff = 2*ndim*j + ll; for (i = 0; i < ndim; i++) { s[i+ioff] = f[i+ndim*(2*j)+nk]; } ioff += ndim; for (i = 0; i < ndim; i++) { s[i+ioff] = f[i+ndim*(2*j+1)+nk]; } } for (j = 0; j < nxh; j++) { ioff = 2*ndim*j + ll; for (i = 0; i < ndim; i++) { f[i+ndim*(2*j)+nk] = s[2*i+ioff]; f[i+ndim*(2*j+1)+nk] = s[2*i+ioff+1]; } } } } } return; } /*--------------------------------------------------------------------*/ void cfft3rmnxy(float complex f[], float complex ss[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nzi, int nzp, int nxhd, int nyd, int nzd, int ndim, int nxhyzd, int nxyzhd) { /* this subroutine performs the x-y part of N three dimensional complex to real fast fourier transforms and their inverses, for a subset of z, using complex arithmetic, where N = ndim, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: M*(5*log2(M) + 19/2) for isign = 1, approximate flop count: M*(5*log2(M) + 15/2) where M = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, N inverse fourier transforms in x and y are performed f[i][m][n][0:N-1] = (1/nx*ny*nz)*sum(f[i][k][j][0:N-1]* exp(-sqrt(-1)*2pi*n*j/nx)*exp(-sqrt(-1)*2pi*m*k/ny)) if isign = 1, N forward fourier transforms in x and y are performed f[l][k][j][0:N-1] = sum([l][m][n][0:N-1]*exp(sqrt(-1)*2pi*n*j/nx)* exp(sqrt(-1)*2pi*m*k/ny)) ss = scratch array mixup = array of bit reversed addresses sct = sine/cosine table nzi = initial z index used nzp = number of z indices used nxhd = second dimension of f nyd,nzd = third and fourth dimensions of f ndim = leading dimension of array f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j][0:N-1] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0][0:N-1] = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0][0:N-1] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0][0:N-1] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0][0:N-1]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0][0:N-1]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0][0:N-1]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0][0:N-1]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, nxhh, ny, nyh, nnxhd, nnxhyd; int nz, nxyz, nxhyz, nzt, nrx, nry, ns, ns2, km, kmr, joff; int i, j, k, l, n, nn, k1, k2, j1, j2, jj, nrxb, nryb; float ani; float complex t1, t2, t3; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; nxhh = nx/4; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nzt = nzi + nzp - 1; nnxhd = ndim*nxhd; nnxhyd = nnxhd*nyd; if (isign > 0) goto L250; /* inverse fourier transform */ nrxb = nxhyz/nxh; nrx = nxyz/nxh; nryb = nxhyz/ny; nry = nxyz/ny; /* swap complex components */ cmswap3cn((float *)f,(float *)ss,isign,nxh,ny,nzi,nzt,nxhd,nyd,nzd, ndim); #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,joff,ani,t1,t2,t3) for (n = nzi-1; n < nzt; n++) { nn = nnxhyd*n; /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nnxhd*i + nn; for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*j1+joff]; f[jj+ndim*j1+joff] = f[jj+ndim*j+joff]; f[jj+ndim*j+joff] = t1; } } } } /* first transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = sct[kmr*j]; for (i = 0; i < ny; i++) { joff = nnxhd*i + nn; for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*j2+joff]; f[jj+ndim*j2+joff] = f[jj+ndim*j1+joff] - t2; f[jj+ndim*j1+joff] += t2; } } } } ns = ns2; } /* unscramble coefficients and normalize */ kmr = nxyz/nx; ani = 0.5/(((float) nx)*((float) ny)*((float) nz)); for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) - crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; for (jj = 0; jj < ndim; jj++) { t2 = conjf(f[jj+ndim*(nxh-j)+joff]); t1 = f[jj+ndim*j+joff] + t2; t2 = (f[jj+ndim*j+joff] - t2)*t3; f[jj+ndim*j+joff] = ani*(t1 + t2); f[jj+ndim*(nxh-j)+joff] = ani*conjf(t1 - t2); } } } ani = 2.0*ani; for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; for (jj = 0; jj < ndim; jj++) { f[jj+ndim*nxhh+joff] = ani*conjf(f[jj+ndim*nxhh+joff]); f[jj+joff] = ani*((crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I); } } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nnxhd*k1 + nn; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*i+k1]; f[jj+ndim*i+k1] = f[jj+ndim*i+joff]; f[jj+ndim*i+joff] = t1; } } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nnxhd*(j + k1) + nn; j2 = nnxhd*(j + k2) + nn; t1 = sct[kmr*j]; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*i+j2]; f[jj+ndim*i+j2] = f[jj+ndim*i+j1] - t2; f[jj+ndim*i+j1] += t2; } } } } ns = ns2; } /* unscramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nnxhd*k; k1 = nnxhd*ny - joff + nn; joff += nn; for (jj = 0; jj < ndim; jj++) { t1 = f[jj+k1]; f[jj+k1] = 0.5*(cimagf(f[jj+joff] + t1) + crealf(f[jj+joff] - t1)*_Complex_I); f[jj+joff] = 0.5*(crealf(f[jj+joff] + t1) + cimagf(f[jj+joff] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L250: nryb = nxhyz/ny; nry = nxyz/ny; nrxb = nxhyz/nxh; nrx = nxyz/nxh; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,joff,ani,t1,t2,t3) for (n = nzi-1; n < nzt; n++) { nn = nnxhyd*n; /* scramble modes kx = 0, nx/2 */ for (k = 1; k < nyh; k++) { joff = nnxhd*k; k1 = nnxhd*ny - joff + nn; joff += nn; for (jj = 0; jj < ndim; jj++) { t1 = cimagf(f[jj+k1]) + crealf(f[jj+k1])*_Complex_I; f[jj+k1] = conjf(f[jj+joff] - t1); f[jj+joff] += t1; } } /* bit-reverse array elements in y */ for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; k1 = (mixup[k] - 1)/nryb; if (k < k1) { k1 = nnxhd*k1 + nn; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*i+k1]; f[jj+ndim*i+k1] = f[jj+ndim*i+joff]; f[jj+ndim*i+joff] = t1; } } } } /* then transform in y */ ns = 1; for (l = 0; l < indy; l++) { ns2 = ns + ns; km = nyh/ns; kmr = km*nry; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nnxhd*(j + k1) + nn; j2 = nnxhd*(j + k2) + nn; t1 = conjf(sct[kmr*j]); for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*i+j2]; f[jj+ndim*i+j2] = f[jj+ndim*i+j1] - t2; f[jj+ndim*i+j1] += t2; } } } } ns = ns2; } /* scramble coefficients */ kmr = nxyz/nx; for (j = 1; j < nxhh; j++) { t3 = cimagf(sct[kmr*j]) + crealf(sct[kmr*j])*_Complex_I; for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; for (jj = 0; jj < ndim; jj++) { t2 = conjf(f[jj+ndim*(nxh-j)+joff]); t1 = f[jj+ndim*j+joff] + t2; t2 = (f[jj+ndim*j+joff] - t2)*t3; f[jj+ndim*j+joff] = t1 + t2; f[jj+ndim*(nxh-j)+joff] = conjf(t1 - t2); } } } for (k = 0; k < ny; k++) { joff = nnxhd*k + nn; for (jj = 0; jj < ndim; jj++) { f[jj+ndim*nxhh+joff] = 2.0*conjf(f[jj+ndim*nxhh+joff]); f[jj+joff] = (crealf(f[jj+joff]) + cimagf(f[jj+joff])) + (crealf(f[jj+joff]) - cimagf(f[jj+joff]))*_Complex_I; } } /* bit-reverse array elements in x */ for (j = 0; j < nxh; j++) { j1 = (mixup[j] - 1)/nrxb; if (j < j1) { for (i = 0; i < ny; i++) { joff = nnxhd*i + nn; for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*j1+joff]; f[jj+ndim*j1+joff] = f[jj+ndim*j+joff]; f[jj+ndim*j+joff] = t1; } } } } /* finally transform in x */ ns = 1; for (l = 0; l < indx1; l++) { ns2 = ns + ns; km = nxhh/ns; kmr = km*nrx; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = j + k1; j2 = j + k2; t1 = conjf(sct[kmr*j]); for (i = 0; i < ny; i++) { joff = nnxhd*i + nn; for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*j2+joff]; f[jj+ndim*j2+joff] = f[jj+ndim*j1+joff] - t2; f[jj+ndim*j1+joff] += t2; } } } } ns = ns2; } } /* swap complex components */ cmswap3cn((float *)f,(float *)ss,isign,nxh,ny,nzi,nzt,nxhd,nyd,nzd, ndim); return; } /*--------------------------------------------------------------------*/ void cfft3rmnz(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nyi, int nyp, int nxhd, int nyd, int nzd, int ndim, int nxhyzd, int nxyzhd) { /* this subroutine performs the z part of N three dimensional complex to real fast fourier transforms and their inverses, for a subset of y, using complex arithmetic, where N = ndim, with OpenMP for isign = (-1,1), input: all, output: f for isign = -1, approximate flop count: M*(5*log2(M) + 19/2) for isign = 1, approximate flop count: M*(5*log2(M) + 15/2) where M = (nx/2)*ny*nz indx/indy/indz = exponent which determines length in x/y/z direction, where nx=2**indx, ny=2**indy, nz=2**indz if isign = -1, three inverse fourier transforms is performed f[l][k][j][0:N-1] = sum(f[i][k][j][0:N-1]*exp(-sqrt(-1)*2pi*l*i/nz)) if isign = 1, three forward fourier transforms are performed f[i][m][n][0:N-1] = sum(f[l][m][n][0:N-1]*exp(sqrt(-1)*2pi*l*i/nz)) mixup = array of bit reversed addresses sct = sine/cosine table nyi = initial y index used nyp = number of y indices used nxhd = second dimension of f nyd,nzd = third and fourth dimensions of f ndim = leading dimension of array f nxhyzd = maximum of (nx/2,ny,nz) nxyzhd = maximum of (nx,ny,nz)/2 fourier coefficients are stored as follows: f[l][k][j][0:N-1] = real, imaginary part of mode j,k,l where 0 <= j < nx/2, 0 <= k < ny, 0 <= l < nz, except for f[l][k][0][0:N-1], = real, imaginary part of mode nx/2,k,l, where ny/2+1 <= k < ny and 0 <= l < nz, and f[l][0][0][0:N-1] = real, imaginary part of mode nx/2,0,l, f[l][ny/2][0][0:N-1] = real, imaginary part mode nx/2,ny/2,l, where nz/2+1 <= l < nz, and imag(f[0][0][0][0:N-1]) = real part of mode nx/2,0,0 imag(f[0][ny/2][0][0:N-1]) = real part of mode nx/2,ny/2,0 imag(f[nz/2][0][0][0:N-1]) = real part of mode nx/2,0,nz/2 imag(f[nz/2][ny/2][0][0:N-1]) = real part of mode nx/2,ny/2,nz/2 using jpl storage convention, as described in: E. Huang, P. C. Liewer, V. K. Decyk, and R. D. Ferraro, "Concurrent Three-Dimensional Fast Fourier Transform Algorithms for Coarse-Grained Distributed Memory Parallel Computers," Caltech CRPC Report 217-50, December 1993. written by viktor k. decyk, ucla local data */ int indx1, ndx1yz, nx, nxh, ny, nyh, nnxhd, nnxhyd; int nz, nzh, nxyz, nxhyz, nyt, nrz, ns, ns2, km, kmr; int i, j, k, l, n, nn, ll, k1, k2, j1, j2, l1, jj, i0, i1, nrzb; float complex t1, t2; if (isign==0) return; indx1 = indx - 1; ndx1yz = indx1 > indy ? indx1 : indy; ndx1yz = ndx1yz > indz ? ndx1yz : indz; nx = 1L<<indx; nxh = nx/2; ny = 1L<<indy; nyh = ny/2; nz = 1L<<indz; nzh = nz/2; nxyz = nx > ny ? nx : ny; nxyz = nxyz > nz ? nxyz : nz; nxhyz = 1L<<ndx1yz; nyt = nyi + nyp - 1; nnxhd = ndim*nxhd; nnxhyd = nnxhd*nyd; if (isign > 0) goto L130; /* inverse fourier transform */ nrzb = nxhyz/nz; nrz = nxyz/nz; #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,ll,l1,i0,i1,t1,t2) for (n = nyi-1; n < nyt; n++) { nn = nnxhd*n; /* bit-reverse array elements in z */ for (l = 0; l < nz; l++) { ll = nnxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nnxhyd*l1; i1 = nn; i0 = i1 + ll; i1 += l1; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*i+i1]; f[jj+ndim*i+i1] = f[jj+ndim*i+i0]; f[jj+ndim*i+i0] = t1; } } } } /* finally transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nnxhyd*(j + k1); j2 = nnxhyd*(j + k2); t1 = sct[kmr*j]; i1 = nn; i0 = i1 + j1; i1 += j2; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*i+i1]; f[jj+ndim*i+i1] = f[jj+ndim*i+i0] - t2; f[jj+ndim*i+i0] += t2; } } } } ns = ns2; } } /* unscramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nnxhyd*n; l1 = nnxhyd*nz - ll; if (nyi==1) { for (jj = 0; jj < ndim; jj++) { t1 = f[jj+l1]; f[jj+l1] = 0.5*(cimagf(f[jj+ll] + t1) + crealf(f[jj+ll] - t1)*_Complex_I); f[jj+ll] = 0.5*(crealf(f[jj+ll] + t1) + cimagf(f[jj+ll] - t1)*_Complex_I); } } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { for (jj = 0; jj < ndim; jj++) { i1 = nnxhd*nyh; i0 = i1 + ll; i1 += l1; t1 = f[jj+i1]; f[jj+i1] = 0.5*(cimagf(f[jj+i0] + t1) + crealf(f[jj+i0] - t1)*_Complex_I); f[jj+i0] = 0.5*(crealf(f[jj+i0] + t1) + cimagf(f[jj+i0] - t1)*_Complex_I); } } } return; /* forward fourier transform */ L130: nrzb = nxhyz/nz; nrz = nxyz/nz; /* scramble modes kx = 0, nx/2 */ for (n = 1; n < nzh; n++) { ll = nnxhyd*n; l1 = nnxhyd*nz - ll; if (nyi==1) { for (jj = 0; jj < ndim; jj++) { t1 = cimagf(f[jj+l1]) + crealf(f[jj+l1])*_Complex_I; f[jj+l1] = conjf(f[jj+ll] - t1); f[jj+ll] += t1; } } if ((nyi <= (nyh+1)) && (nyt >= (nyh+1))) { for (jj = 0; jj < ndim; jj++) { i1 = nnxhd*nyh; i0 = i1 + ll; i1 += l1; t1 = cimagf(f[jj+i1]) + crealf(f[jj+i1])*_Complex_I; f[jj+i1] = conjf(f[jj+i0] - t1); f[jj+i0] += t1; } } } /* bit-reverse array elements in z */ #pragma omp parallel for \ private(i,j,k,l,n,ns,ns2,km,kmr,k1,k2,jj,j1,j2,nn,ll,l1,i0,i1,t1,t2) for (n = nyi-1; n < nyt; n++) { nn = nnxhd*n; for (l = 0; l < nz; l++) { ll = nnxhyd*l; l1 = (mixup[l] - 1)/nrzb; if (l < l1) { l1 = nnxhyd*l1; i1 = nn; i0 = i1 + ll; i1 += l1; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t1 = f[jj+ndim*i+i1]; f[jj+ndim*i+i1] = f[jj+ndim*i+i0]; f[jj+ndim*i+i0] = t1; } } } } /* first transform in z */ ns = 1; for (l = 0; l < indz; l++) { ns2 = ns + ns; km = nzh/ns; kmr = km*nrz; for (k = 0; k < km; k++) { k1 = ns2*k; k2 = k1 + ns; for (j = 0; j < ns; j++) { j1 = nnxhyd*(j + k1); j2 = nnxhyd*(j + k2); t1 = conjf(sct[kmr*j]); i1 = nn; i0 = i1 + j1; i1 += j2; for (i = 0; i < nxh; i++) { for (jj = 0; jj < ndim; jj++) { t2 = t1*f[jj+ndim*i+i1]; f[jj+ndim*i+i1] = f[jj+ndim*i+i0] - t2; f[jj+ndim*i+i0] += t2; } } } } ns = ns2; } } return; } /*--------------------------------------------------------------------*/ void cwfft3rmx(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* wrapper function for real to complex fft, with packed data */ /* local data */ int ny, nz; static int nyi = 1, nzi = 1; /* calculate range of indices */ ny = 1L<<indy; nz = 1L<<indz; /* inverse fourier transform */ if (isign < 0) { /* perform xy fft */ cfft3rmxy(f,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd,nzd, nxhyzd,nxyzhd); /* perform z fft */ cfft3rmxz(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, nxhyzd,nxyzhd); } /* forward fourier transform */ else if (isign > 0) { /* perform z fft */ cfft3rmxz(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, nxhyzd,nxyzhd); /* perform xy fft */ cfft3rmxy(f,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd,nzd, nxhyzd,nxyzhd); } return; } /*--------------------------------------------------------------------*/ void cwfft3rm3(float complex f[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nxhd, int nyd, int nzd, int nxhyzd, int nxyzhd) { /* wrapper function for 3 3d real to complex ffts, with packed data */ /* parallelized with OpenMP */ /* local data */ int ny, nz; static int nyi = 1, nzi = 1; /* calculate range of indices */ ny = 1L<<indy; nz = 1L<<indz; /* inverse fourier transform */ if (isign < 0) { /* perform xy fft */ cfft3rm3xy(f,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd,nzd, nxhyzd,nxyzhd); /* perform z fft */ cfft3rm3z(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, nxhyzd,nxyzhd); } /* forward fourier transform */ else if (isign > 0) { /* perform z fft */ cfft3rm3z(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, nxhyzd,nxyzhd); /* perform xy fft */ cfft3rm3xy(f,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd,nzd, nxhyzd,nxyzhd); } return; } /*--------------------------------------------------------------------*/ void cwfft3rmn(float complex f[], float complex ss[], int isign, int mixup[], float complex sct[], int indx, int indy, int indz, int nxhd, int nyd, int nzd, int ndim, int nxhyzd, int nxyzhd) { /* wrapper function for multiple 3d real to complex ffts, packed data */ /* parallelized with OpenMP */ /* local data */ int ny, nz; static int nyi = 1, nzi = 1; /* calculate range of indices */ ny = 1L<<indy; nz = 1L<<indz; /* inverse fourier transform */ if (isign < 0) { /* perform xy fft */ cfft3rmnxy(f,ss,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd, nzd,ndim,nxhyzd,nxyzhd); /* perform z fft */ cfft3rmnz(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, ndim,nxhyzd,nxyzhd); } /* forward fourier transform */ else if (isign > 0) { /* perform z fft */ cfft3rmnz(f,isign,mixup,sct,indx,indy,indz,nyi,ny,nxhd,nyd,nzd, ndim,nxhyzd,nxyzhd); /* perform xy fft */ cfft3rmnxy(f,ss,isign,mixup,sct,indx,indy,indz,nzi,nz,nxhd,nyd, nzd,ndim,nxhyzd,nxyzhd); } return; } /* Interfaces to Fortran */ /*--------------------------------------------------------------------*/ void cdistr3_(float *part, float *vtx, float *vty, float *vtz, float *vdx, float *vdy, float *vdz, int *npx, int *npy, int *npz, int *idimp, int *nop, int *nx, int *ny, int *nz, int *ipbc) { cdistr3(part,*vtx,*vty,*vtz,*vdx,*vdy,*vdz,*npx,*npy,*npz,*idimp, *nop,*nx,*ny,*nz,*ipbc); return; } /*--------------------------------------------------------------------*/ void cdblkp3l_(float *part, int *kpic, int *nppmx, int *idimp, int *nop, int *mx, int *my, int *mz, int *mx1, int *my1, int *mxyz1, int *irc) { cdblkp3l(part,kpic,nppmx,*idimp,*nop,*mx,*my,*mz,*mx1,*my1,*mxyz1, irc); return; } /*--------------------------------------------------------------------*/ void cppmovin3l_(float *part, float *ppart, int *kpic, int *nppmx, int *idimp, int *nop, int *mx, int *my, int *mz, int *mx1, int *my1, int *mxyz1, int *irc) { cppmovin3l(part,ppart,kpic,*nppmx,*idimp,*nop,*mx,*my,*mz,*mx1,*my1, *mxyz1,irc); return; } /*--------------------------------------------------------------------*/ void cppcheck3l_(float *ppart, int *kpic, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *mx1, int *my1, int *mz1, int *irc) { cppcheck3l(ppart,kpic,*idimp,*nppmx,*nx,*ny,*nz,*mx,*my,*mz,*mx1, *my1,*mz1,irc); return; } /*--------------------------------------------------------------------*/ void cgbppush3l_(float *ppart, float *fxyz, float *bxyz, int *kpic, float *qbm, float *dt, float *dtc, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1, int *ipbc) { cgbppush3l(ppart,fxyz,bxyz,kpic,*qbm,*dt,*dtc,ek,*idimp,*nppmx,*nx, *ny,*nz,*mx,*my,*mz,*nxv,*nyv,*nzv,* mx1,*my1,*mxyz1, *ipbc); return; } /*--------------------------------------------------------------------*/ void cgbppushf3l_(float *ppart, float *fxyz, float *bxyz, int *kpic, int *ncl, int *ihole, float *qbm, float *dt, float *dtc, float *ek, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1, int *ntmax, int *irc) { cgbppushf3l(ppart,fxyz,bxyz,kpic,ncl,ihole,*qbm,*dt,*dtc,ek,*idimp, *nppmx,*nx,*ny,*nz,*mx,*my,*mz,*nxv,*nyv,*nzv,*mx1,*my1, *mxyz1,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void cgppost3l_(float *ppart, float *q, int *kpic, float *qm, int *nppmx, int *idimp, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1) { cgppost3l(ppart,q,kpic,*qm,*nppmx,*idimp,*mx,*my,*mz,*nxv,*nyv,*nzv, *mx1,*my1,*mxyz1); return; } /*--------------------------------------------------------------------*/ void cgjppost3l_(float *ppart, float *cu, int *kpic, float *qm, float *dt, int *nppmx, int *idimp, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1, int *ipbc) { cgjppost3l(ppart,cu,kpic,*qm,*dt,*nppmx,*idimp,*nx,*ny,*nz,*mx,*my, *mz,*nxv,*nyv,*nzv,*mx1,*my1,*mxyz1,*ipbc); return; } /*--------------------------------------------------------------------*/ void cgmjppost3l_(float *ppart, float *amu, int *kpic, float *qm, int *nppmx, int *idimp, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1) { cgmjppost3l(ppart,amu,kpic,*qm,*nppmx,*idimp,*mx,*my,*mz,*nxv,*nyv, *nzv,*mx1,*my1,*mxyz1); return; } /*--------------------------------------------------------------------*/ void cgdjppost3l_(float *ppart, float *fxyz, float *bxyz, int *kpic, float *dcu, float *amu, float *qm, float *qbm, float *dt, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1) { cgdjppost3l(ppart,fxyz,bxyz,kpic,dcu,amu,*qm,*qbm,*dt,*idimp,*nppmx, *nx,*ny,*nz,*mx,*my,*mz,*nxv,*nyv,*nzv,*mx1,*my1,*mxyz1); return; } /*--------------------------------------------------------------------*/ void cgdcjppost3l_(float *ppart, float *fxyz, float *bxyz, int *kpic, float *cu, float *dcu, float *amu, float *qm, float *qbm, float *dt, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *nxv, int *nyv, int *nzv, int *mx1, int *my1, int *mxyz1) { cgdcjppost3l(ppart,fxyz,bxyz,kpic,cu,dcu,amu,*qm,*qbm,*dt,*idimp, *nppmx,*nx,*ny,*nz,*mx,*my,*mz,*nxv,*nyv,*nzv,*mx1,*my1, *mxyz1); return; } /*--------------------------------------------------------------------*/ void cpporder3l_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *nx, int *ny, int *nz, int *mx, int *my, int *mz, int *mx1, int *my1, int *mz1, int *npbmx, int *ntmax, int *irc) { cpporder3l(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*nx,*ny,*nz,*mx, *my,*mz,*mx1,*my1,*mz1,*npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void cpporderf3l_(float *ppart, float *ppbuff, int *kpic, int *ncl, int *ihole, int *idimp, int *nppmx, int *mx1, int *my1, int *mz1, int *npbmx, int *ntmax, int *irc) { cpporderf3l(ppart,ppbuff,kpic,ncl,ihole,*idimp,*nppmx,*mx1,*my1,*mz1, *npbmx,*ntmax,irc); return; } /*--------------------------------------------------------------------*/ void ccguard3l_(float *fxyz, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { ccguard3l(fxyz,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void cacguard3l_(float *cu, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { cacguard3l(cu,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void caguard3l_(float *q, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { caguard3l(q,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void camcguard3l_(float *amu, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze, int *ndim) { camcguard3l(amu,*nx,*ny,*nz,*nxe,*nye,*nze,*ndim); return; } /*--------------------------------------------------------------------*/ void cascfguard3l_(float *dcu, float *cus, float *q2m0, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { cascfguard3l(dcu,cus,*q2m0,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void cfwpminmx3_(float *qe, float *qbme, float *wpmax, float *wpmin, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { cfwpminmx3(qe,*qbme,wpmax,wpmin,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void cmpois33_(float complex *q, float complex *fxyz, int *isign, float complex *ffc, float *ax, float *ay, float *az, float *affp, float *we, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd) { cmpois33(q,fxyz,*isign,ffc,*ax,*ay,*az,*affp,we,*nx,*ny,*nz,*nxvh, *nyv,*nzv,*nxhd,*nyhd,*nzhd); return; } /*--------------------------------------------------------------------*/ void cmcuperp3_(float complex *cu, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv) { cmcuperp3(cu,*nx,*ny,*nz,*nxvh,*nyv,*nzv); return; } /*--------------------------------------------------------------------*/ void cmbbpois33_(float complex *cu, float complex *bxyz, float complex *ffc, float *ci, float *wm, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd) { cmbbpois33(cu,bxyz,ffc,*ci,wm,*nx,*ny,*nz,*nxvh,*nyv,*nzv,*nxhd, *nyhd,*nzhd); return; } /*--------------------------------------------------------------------*/ void cbaddext3_(float *bxyz, float *omx, float *omy, float *omz, int *nx, int *ny, int *nz, int *nxe, int *nye, int *nze) { cbaddext3(bxyz,*omx,*omy,*omz,*nx,*ny,*nz,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void cmdcuperp3_(float complex *dcu, float complex *amu, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv) { cmdcuperp3(dcu,amu,*nx,*ny,*nz,*nxvh,*nyv,*nzv); return; } /*--------------------------------------------------------------------*/ void cmadcuperp3_(float complex *dcu, float complex *amu, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv) { cmadcuperp3(dcu,amu,*nx,*ny,*nz,*nxvh,*nyv,*nzv); return; } /*--------------------------------------------------------------------*/ void cmepois33_(float complex *dcu, float complex *exyz, int *isign, float complex *ffe, float *ax, float *ay, float *az, float *affp, float *wp0, float *ci, float *wf, int *nx, int *ny, int *nz, int *nxvh, int *nyv, int *nzv, int *nxhd, int *nyhd, int *nzhd) { cmepois33(dcu,exyz,*isign,ffe,*ax,*ay,*az,*affp,*wp0,*ci,wf,*nx,*ny, *nz,*nxvh,*nyv,*nzv,*nxhd,*nyhd,*nzhd); return; } /*--------------------------------------------------------------------*/ void caddvrfield3_(float *a, float *b, float *c, int *ndim, int *nxe, int *nye, int *nze) { caddvrfield3(a,b,c,*ndim,*nxe,*nye,*nze); return; } /*--------------------------------------------------------------------*/ void cwfft3rinit_(int *mixup, float complex *sct, int *indx, int *indy, int *indz, int *nxhyzd, int *nxyzhd) { cwfft3rinit(mixup,sct,*indx,*indy,*indz,*nxhyzd,*nxyzhd); return; } /*--------------------------------------------------------------------*/ void cwfft3rmx_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *indz, int *nxhd, int *nyd, int *nzd, int *nxhyzd, int *nxyzhd) { cwfft3rmx(f,*isign,mixup,sct,*indx,*indy,*indz,*nxhd,*nyd,*nzd, *nxhyzd,*nxyzhd); return; } /*--------------------------------------------------------------------*/ void cwfft3rm3_(float complex *f, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *indz, int *nxhd, int *nyd, int *nzd, int *nxhyzd, int *nxyzhd) { cwfft3rm3(f,*isign,mixup,sct,*indx,*indy,*indz,*nxhd,*nyd,*nzd, *nxhyzd,*nxyzhd); return; } /*--------------------------------------------------------------------*/ void cwfft3rmn_(float complex *f, float complex *ss, int *isign, int *mixup, float complex *sct, int *indx, int *indy, int *indz, int *nxhd, int *nyd, int *nzd, int *ndim, int *nxhyzd, int *nxyzhd) { cwfft3rmn(f,ss,*isign,mixup,sct,*indx,*indy,*indz,*nxhd,*nyd,*nzd, *ndim,*nxhyzd,*nxyzhd); return; }
pi_omp_padding.c
/* * Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * Parallel version using OpenMP */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <omp.h> /* OpenMP */ double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%0.6f\n", stamp); #define MAXTHREADS 16 #define CACHE_SIZE 64 double sumvector[MAXTHREADS][CACHE_SIZE/sizeof(double)]; // sum for each thread, with padding to avoid false sharing int main(int argc, char *argv[]) { double stamp; double x, sum=0.0, pi=0.0; double step; const char Usage[] = "Usage: pi <num_steps> <num_threads>\n"; if (argc < 3) { fprintf(stderr, Usage); exit(1); } long int num_steps = atoi(argv[1]); step = 1.0/(double) num_steps; int num_threads = atoi(argv[2]); START_COUNT_TIME; for (int i=0; i<num_threads; i++) sumvector[i][0] = 0.0; #pragma omp parallel private(x) num_threads(num_threads) { int myid = omp_get_thread_num(); #pragma omp for for (long int i=0; i<num_steps; ++i) { x = (i+0.5)*step; sumvector[myid][0] += 4.0/(1.0+x*x); } } for (int i=0; i<num_threads; i++) sum += sumvector[i][0]; pi = step * sum; STOP_COUNT_TIME("Total execution time"); /* print results */ // printf("Number pi after %ld iterations = %.15f\n", num_steps, pi); return EXIT_SUCCESS; }
many_transfers.c
#include <stdio.h> #define N 17 #define M 100 void init(int* array, int size, int scale) { for (int i = 0; i < size; i++) array[i] = i*scale; } int main() { int tab[N][M]; /* The schedule(static, 1) enforces each iteration to be executed in a different thread, whatever the number of CPU is: */ #pragma omp parallel for schedule(static, 1) for (int i = 0; i < N; i++) { // Map on STHORM in a cyclic way on the cluster first: #pragma smecy map(STHORM, i%2, (i/4)%2) \ arg(1,out,[N][M],/[i][]) \ arg(2,in) \ arg(3,in) init(&tab[i][0], M, i+1); } for (int i = 0; i < N; i++) { printf("Line %d :", i); for (int j = 0; j < M; j += M/10) printf("tab[%d][%d] = %d ", i, j, tab[i][j]); puts(""); } return 0; }
gm_property_of_collection.h
#ifndef GM_TESTSET_H #define GM_TESTSET_H #include <stdio.h> #include <omp.h> #include "gm_set.h" #include "gm_lock.h" class gm_complex_data_type { public: virtual ~gm_complex_data_type() { } }; template<class T> class gm_property_of_collection: public gm_complex_data_type { public: virtual T& operator[](int index) = 0; virtual ~gm_property_of_collection() { } }; template<class T, bool lazy> class gm_property_of_collection_impl: public gm_property_of_collection<T> { private: T** data; gm_spinlock_t* locks; int size; inline void lazyInit(int index) { gm_spinlock_acquire(locks + index); if (data[index] == NULL) data[index] = new T(size); gm_spinlock_release(locks + index); } public: gm_property_of_collection_impl(int size) : size(size), locks(NULL) { data = new T*[size]; if(lazy) locks = new gm_spinlock_t[size]; #pragma omp parallel for for (int i = 0; i < size; i++) { if (lazy) { data[i] = NULL; locks[i] = 0; } else { data[i] = new T(size); } } } ~gm_property_of_collection_impl() { for (int i = 0; i < size; i++) delete data[i]; delete[] data; if (lazy) delete[] locks; } T& operator[](int index) { if (lazy && data[index] == NULL) lazyInit(index); return *data[index]; } }; #endif
convolutiondepthwise_3x3_int8.h
// SenseNets is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2018 SenseNets Technology Ltd. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON #if __aarch64__ static void convdw3x3s1_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const signed char *kernel0 = (const signed char *)_kernel + p * 9; int *outptr = out; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr = sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); const signed char *kernel0 = (const signed char *)_kernel + p * 9; int *outptr = out; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } #else // __aarch64__ static void convdw3x3s1_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out0 = top_blob.channel(p); const signed char* kernel = (const signed char *)_kernel + p*9; int* outptr0_s32 = out0; int* outptr0n_s32 = outptr0_s32 + outw; const signed char* img0 = bottom_blob.channel(p); const signed char* r0 = img0; const signed char* r1 = img0 + w; const signed char* r2 = img0 + w*2; const signed char* r3 = img0 + w*3; int i = 0; for (; i+1 < outh; i+=2) { int nn = outw >> 3; int remain = outw & 7; if (nn > 0) { asm volatile( "vld1.8 {d26-d27}, [%0] \n" : "=r"(kernel) // %0 : "0"(kernel) : "cc", "memory" ); asm volatile( "0: \n" "pld [%3, #128] \n" "vld1.32 {d0-d1}, [%3] \n"// r0 "add %3, #8 \n" "vext.8 d2, d0, d1, #1 \n" "vext.8 d3, d0, d1, #2 \n" "vdup.s8 d1, d26[0] \n" "vdup.s8 d30, d26[1] \n" "vdup.s8 d31, d26[2] \n" "vmull.s8 q2, d0, d1 \n"// k0 "vmlal.s8 q2, d2, d30 \n"// k1 "vmlal.s8 q2, d3, d31 \n"// k2 "pld [%4, #128] \n" "vld1.32 {d6-d7}, [%4] \n"// r1 "add %4, #8 \n" "vext.8 d8, d6, d7, #1 \n" "vext.8 d9, d6, d7, #2 \n" "vdup.s8 d1, d26[3] \n" "vdup.s8 d30, d26[4] \n" "vdup.s8 d31, d26[5] \n" "vmlal.s8 q2, d6, d1 \n"// k3 "vmlal.s8 q2, d8, d30 \n"// k4 "vmlal.s8 q2, d9, d31 \n"// k5 "pld [%5, #128] \n" "vld1.32 {d10-d11}, [%5] \n"// r2 "add %5, #8 \n" "vext.8 d12, d10, d11, #1 \n" "vext.8 d13, d10, d11, #2 \n" "vdup.s8 d1, d26[6] \n" "vdup.s8 d30, d26[7] \n" "vdup.s8 d31, d27[0] \n" "vmlal.s8 q2, d10, d1 \n"// k6 "vmlal.s8 q2, d12, d30 \n"// k7 "vmlal.s8 q2, d13, d31 \n"// k8 "pld [%6, #128] \n" "vld1.32 {d14-d15}, [%6] \n"// r3 "add %6, #8 \n" "vext.8 d16, d14, d15, #1 \n" "vext.8 d17, d14, d15, #2 \n" "vmovl.s16 q9, d4 \n" "vmovl.s16 q10, d5 \n" "vst1.32 {d18-d21}, [%1]! \n"// sum0 "vdup.s8 d1, d26[0] \n" "vdup.s8 d30, d26[1] \n" "vdup.s8 d31, d26[2] \n" "vmull.s8 q2, d6, d1 \n"// k0 "vmlal.s8 q2, d8, d30 \n"// k1 "vmlal.s8 q2, d9, d31 \n"// k2 "vdup.s8 d1, d26[3] \n" "vdup.s8 d30, d26[4] \n" "vdup.s8 d31, d26[5] \n" "vmlal.s8 q2, d10, d1 \n"// k3 "vmlal.s8 q2, d12, d30 \n"// k4 "vmlal.s8 q2, d13, d31 \n"// k5 "vdup.s8 d1, d26[6] \n" "vdup.s8 d30, d26[7] \n" "vdup.s8 d31, d27[0] \n" "vmlal.s8 q2, d14, d1 \n"// k6 "vmlal.s8 q2, d16, d30 \n"// k7 "vmlal.s8 q2, d17, d31 \n"// k8 "vmovl.s16 q9, d4 \n" "vmovl.s16 q10, d5 \n" "vst1.32 {d18-d21}, [%2]! \n"// sum0n "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0_s32), // %1 "=r"(outptr0n_s32), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr0_s32), "2"(outptr0n_s32), "3"(r0), "4"(r1), "5"(r2), "6"(r3) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } for (; remain>0; remain--) { //Todo Neon int sum0 = 0; int sum0n = 0; sum0 += (int)r0[0] * kernel[0]; sum0 += (int)r0[1] * kernel[1]; sum0 += (int)r0[2] * kernel[2]; sum0 += (int)r1[0] * kernel[3]; sum0 += (int)r1[1] * kernel[4]; sum0 += (int)r1[2] * kernel[5]; sum0 += (int)r2[0] * kernel[6]; sum0 += (int)r2[1] * kernel[7]; sum0 += (int)r2[2] * kernel[8]; sum0n += (int)r1[0] * kernel[0]; sum0n += (int)r1[1] * kernel[1]; sum0n += (int)r1[2] * kernel[2]; sum0n += (int)r2[0] * kernel[3]; sum0n += (int)r2[1] * kernel[4]; sum0n += (int)r2[2] * kernel[5]; sum0n += (int)r3[0] * kernel[6]; sum0n += (int)r3[1] * kernel[7]; sum0n += (int)r3[2] * kernel[8]; *outptr0_s32 = sum0; *outptr0n_s32 = sum0n; r0++; r1++; r2++; r3++; outptr0_s32++; outptr0n_s32++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr0_s32 += outw; outptr0n_s32 += outw; } for (; i < outh; i++) { int nn = outw >> 3; int remain = outw & 7; if (nn > 0) { asm volatile( "vld1.8 {d26-d27}, [%0] \n" : "=r"(kernel) // %0 : "0"(kernel) : "cc", "memory" ); asm volatile( "0: \n" "pld [%2, #128] \n" "vld1.32 {d0-d1}, [%2] \n"// r0 "add %2, #8 \n" "vext.8 d2, d0, d1, #1 \n" "vext.8 d3, d0, d1, #2 \n" "vdup.s8 d1, d26[0] \n" "vdup.s8 d30, d26[1] \n" "vdup.s8 d31, d26[2] \n" "vmull.s8 q2, d0, d1 \n"// k0 "vmlal.s8 q2, d2, d30 \n"// k1 "vmlal.s8 q2, d3, d31 \n"// k2 "pld [%3, #128] \n" "vld1.32 {d6-d7}, [%3] \n"// r1 "add %3, #8 \n" "vext.8 d8, d6, d7, #1 \n" "vext.8 d9, d6, d7, #2 \n" "vdup.s8 d1, d26[3] \n" "vdup.s8 d30, d26[4] \n" "vdup.s8 d31, d26[5] \n" "vmlal.s8 q2, d6, d1 \n"// k3 "vmlal.s8 q2, d8, d30 \n"// k4 "vmlal.s8 q2, d9, d31 \n"// k5 "pld [%4, #128] \n" "vld1.32 {d10-d11}, [%4] \n"// r2 "add %4, #8 \n" "vext.8 d12, d10, d11, #1 \n" "vext.8 d13, d10, d11, #2 \n" "vdup.s8 d1, d26[6] \n" "vdup.s8 d30, d26[7] \n" "vdup.s8 d31, d27[0] \n" "vmlal.s8 q2, d10, d1 \n"// k6 "vmlal.s8 q2, d12, d30 \n"// k7 "vmlal.s8 q2, d13, d31 \n"// k8 "vmovl.s16 q9, d4 \n" "vmovl.s16 q10, d5 \n" "vst1.32 {d18-d21}, [%1]! \n"// sum0 "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0_s32), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr0_s32), "2"(r0), "3"(r1), "4"(r2) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } for (; remain>0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr0_s32 = sum; r0++; r1++; r2++; outptr0_s32++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const signed char* kernel = (const signed char*)_kernel + p*9; int* outptr_s32 = out; const signed char* img = bottom_blob.channel(p); const signed char* r0 = img; const signed char* r1 = img + w; const signed char* r2 = img + w*2; int i = 0; int8x8_t _k0 = vdup_n_s8(kernel[0]); int8x8_t _k1 = vdup_n_s8(kernel[1]); int8x8_t _k2 = vdup_n_s8(kernel[2]); int8x8_t _k3 = vdup_n_s8(kernel[3]); int8x8_t _k4 = vdup_n_s8(kernel[4]); int8x8_t _k5 = vdup_n_s8(kernel[5]); int8x8_t _k6 = vdup_n_s8(kernel[6]); int8x8_t _k7 = vdup_n_s8(kernel[7]); int8x8_t _k8 = vdup_n_s8(kernel[8]); for (; i < outh; i++) { int nn = outw >> 3; int remain = outw & 7; if (nn > 0) { asm volatile( "0: \n" "pld [%2, #192] \n" "vld2.s8 {d0-d1}, [%2]! \n" // r0 "vld2.s8 {d2-d3}, [%2] \n" // "vext.8 d3, d0, d2, #1 \n" "vmull.s8 q2, d0, %P10 \n" // k00 "vmull.s8 q3, d1, %P11 \n" // k01 "vmull.s8 q4, d3, %P12 \n" // k02 "veor q7, q0, q0 \n" "veor q8, q0, q0 \n" "pld [%3, #192] \n" "vld2.s8 {d0-d1}, [%3]! \n" // r1 "vld2.s8 {d2-d3}, [%3] \n" // "vext.8 d3, d0, d2, #1 \n" "vmlal.s8 q2, d0, %P13 \n" // k03 "vmlal.s8 q3, d1, %P14 \n" // k04 "vmlal.s8 q4, d3, %P15 \n" // k05 "pld [%4, #192] \n" "vld2.s8 {d0-d1}, [%4]! \n" // r2 "vld2.s8 {d2-d3}, [%4] \n" // "vext.8 d3, d0, d2, #1 \n" "vmlal.s8 q2, d0, %P16 \n" // k06 "vmlal.s8 q3, d1, %P17 \n" // k07 "vmlal.s8 q4, d3, %P18 \n" // k08 "vadd.s16 q2, q2, q3 \n" "vadd.s16 q2, q2, q4 \n" "vaddw.s16 q7, q7, d4 \n" "vaddw.s16 q8, q8, d5 \n" "vst1.32 {d14-d17}, [%1]! \n" // sum "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr_s32), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr_s32), "2"(r0), // %7 "3"(r1), // %8 "4"(r2), // %9 "w"(_k0), // %10 "w"(_k1), // %11 "w"(_k2), // %12 "w"(_k3), // %13 "w"(_k4), // %14 "w"(_k5), // %15 "w"(_k6), // %16 "w"(_k7), // %17 "w"(_k8) // %18 : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q6", "q7", "q8", "q13", "q14" ); } for (; remain>0; remain--) { int sum = 0; sum += (int)r0[0] * kernel[0]; sum += (int)r0[1] * kernel[1]; sum += (int)r0[2] * kernel[2]; sum += (int)r1[0] * kernel[3]; sum += (int)r1[1] * kernel[4]; sum += (int)r1[2] * kernel[5]; sum += (int)r2[0] * kernel[6]; sum += (int)r2[1] * kernel[7]; sum += (int)r2[2] * kernel[8]; *outptr_s32 = sum; r0 += 2; r1 += 2; r2 += 2; outptr_s32++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } #endif
SoftmaxLoss.h
#ifndef SOFTMAXLOSS_H #define SOFTMAXLOSS_H #include <Eigen/Dense> #include "multinomial.h" #include "util.h" namespace nplm { // is this cheating? using Eigen::Matrix; using Eigen::MatrixBase; using Eigen::Dynamic; ///// Softmax layer plus log-loss function. enum loss_function_type { LogLoss, NCELoss, InvalidLoss }; inline loss_function_type string_to_loss_function (const std::string &s) { if (s == "log") return LogLoss; else if (s == "nce") return NCELoss; else return InvalidLoss; } inline std::string loss_function_to_string (loss_function_type f) { if (f == LogLoss) return "log"; else if (f == NCELoss) return "nce"; } /// Note: Outputs log-probabilities. struct SoftmaxLogLoss { template <typename DerivedI, typename DerivedW, typename DerivedO> void fProp(const MatrixBase<DerivedI> &input, const MatrixBase<DerivedW> &output_words, const MatrixBase<DerivedO> &output_const, double &loss) { UNCONST(DerivedO, output_const, output); double log_likelihood = 0.0; #pragma omp parallel for reduction(+:log_likelihood) for (int train_id = 0; train_id < input.cols(); train_id++) { double normalization = logsum(input.col(train_id)); output.col(train_id).array() = input.col(train_id).array() - normalization; log_likelihood += output(output_words(train_id), train_id); } loss = log_likelihood; } template <typename DerivedW, typename DerivedO, typename DerivedI> void bProp(const MatrixBase<DerivedW> &output_words, const MatrixBase<DerivedO> &output, const MatrixBase<DerivedI> &grad_input_const) { UNCONST(DerivedI, grad_input_const, grad_input); grad_input.setZero(); #pragma omp parallel for for (int train_id = 0; train_id < output.cols(); train_id++) { grad_input(output_words(train_id), train_id) += 1.; grad_input.col(train_id) -= output.col(train_id).array().exp().matrix(); } } }; ///// Softmax layer plus NCE loss function. ///// Note: Outputs probabilities. ///// Note: Unlike SoftmaxLogLoss, does not compute *or* apply precomputed ///// normalizations. Currently the caller is expected to do normalization. template <typename Multinomial> class SoftmaxNCELoss { const Multinomial &unigram; public: SoftmaxNCELoss(const Multinomial &unigram) : unigram(unigram) { } template <typename DerivedI, typename DerivedW, typename DerivedO> void fProp(const MatrixBase<DerivedI> &scores, const MatrixBase<DerivedW> &minibatch_samples, const MatrixBase<DerivedO> &output_const, double &loss) { UNCONST(DerivedO, output_const, output); double log_likelihood = 0.0; int num_noise_samples = minibatch_samples.rows()-1; double log_num_noise_samples = std::log(num_noise_samples); #pragma omp parallel for reduction(+:log_likelihood) schedule(static) for (int train_id = 0; train_id < scores.cols(); train_id++) { for (int sample_id = 0;sample_id < minibatch_samples.rows(); sample_id++) { int sample = minibatch_samples(sample_id, train_id); // To avoid zero or infinite probabilities, // never take exp of score without normalizing first, // even if it's a little slower... double score = scores(sample_id, train_id); double score_noise = log_num_noise_samples + unigram.logprob(sample); double z = logadd(score, score_noise); double logprob = score - z; double logprob_noise = score_noise - z; output(sample_id, train_id) = std::exp(logprob); log_likelihood += sample_id == 0 ? logprob : logprob_noise; } } loss = log_likelihood; } template <typename DerivedO, typename DerivedI> void bProp(const MatrixBase<DerivedO> &probs, const MatrixBase<DerivedI> &output_const) { UNCONST(DerivedI, output_const, output); #pragma omp parallel for schedule(static) for (int train_id = 0; train_id < probs.cols(); train_id++) { output.col(train_id) = -probs.col(train_id); output(0, train_id) += 1.0; } } }; } // namespace nplm #endif
ndvi.c
#include<stdio.h> #include "gdal.h" #include<omp.h> #include "cpl_string.h" #define NODATA -28768 /* -1 Fill/No Data Not Processed 0 Good Data Use with confidence 1 Marginal data Useful, but look at other QA information 2 Snow/Ice Target covered with snow/ice 3 Cloudy Target not visible, covered with cloud */ void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--Serial code----\n"); printf( "-----------------------------------------\n"); printf( "./ndvi inNDVI inNDVI_QA\n"); printf( "\toutNDVI\n"); printf( "-----------------------------------------\n"); printf( "inNDVI\t\tModis MOD13Q1 NDVI 250m\n"); printf( "inNDVI_QA\t\tModis MOD13Q1 NDVI Reliability\n"); printf( "outNDVI\tQA corrected NDVI output [-]\n"); return; } int main( int argc, char *argv[] ) { if( argc < 4 ) { usage(); return 1; } char *inB2 = argv[1]; //NDVI char *inB3 = argv[2]; //NDVI_QA char *ndviF = argv[3]; GDALAllRegister(); GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//NDVI GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//NDVI_QA if(hD2==NULL||hD3==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } GDALDriverH hDr2 = GDALGetDatasetDriver(hD2); char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDatasetH hDOut = GDALCreateCopy(hDr2,ndviF,hD2,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); GDALSetRasterNoDataValue(hBOut, NODATA); GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//NDVI GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//NDVI_QA int nX = GDALGetRasterBandXSize(hB2); int nY = GDALGetRasterBandYSize(hB2); int N = nX*nY; float *l2 = (float *) malloc(sizeof(float)*N); float *l3 = (float *) malloc(sizeof(float)*N); float *lOut = (float *) malloc(sizeof(float)*N); int rowcol; int err=GDALRasterIO(hB2,GF_Read,0,0,nX,nY,l2,nX,nY,GDT_Float32,0,0); err=GDALRasterIO(hB3,GF_Read,0,0,nX,nY,l3,nX,nY,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private (rowcol) shared (N, l2, l3, lOut) for(rowcol=0;rowcol<N;rowcol++){ if( l3[rowcol] == 0||l3[rowcol] == 1) lOut[rowcol] = l2[rowcol]; else if(l2[rowcol] == -3000) lOut[rowcol] = NODATA; else lOut[rowcol] = NODATA; } #pragma omp barrier err=GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,lOut,nX,nY,GDT_Float32,0,0); err=err+1; if( l2 != NULL ) free( l2 ); if( l3 != NULL ) free( l3 ); GDALClose(hD2); GDALClose(hD3); GDALClose(hDOut); return(EXIT_SUCCESS); }
GB_reduce_to_scalar_template.c
//------------------------------------------------------------------------------ // GB_reduce_to_scalar_template: s=reduce(A), reduce a matrix to a scalar //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Reduce a matrix to a scalar, with typecasting and generic operators. // No panel is used. { //-------------------------------------------------------------------------- // get A //-------------------------------------------------------------------------- const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) A->x ; int64_t anz = GB_NNZ (A) ; ASSERT (anz > 0) ; //-------------------------------------------------------------------------- // reduce A to a scalar //-------------------------------------------------------------------------- if (nthreads == 1) { //---------------------------------------------------------------------- // single thread //---------------------------------------------------------------------- // s = (ztype) Ax [0] GB_CAST_ARRAY_TO_SCALAR (s, Ax, 0) ; for (int64_t p = 1 ; p < anz ; p++) { // check for early exit GB_BREAK_IF_TERMINAL (s) ; // s = op (s, (ztype) Ax [p]) GB_ADD_CAST_ARRAY_TO_SCALAR (s, Ax, p) ; } } else { //---------------------------------------------------------------------- // each thread reduces its own slice in parallel //---------------------------------------------------------------------- bool early_exit = false ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (tid = 0 ; tid < ntasks ; tid++) { int64_t pstart, pend ; GB_PARTITION (pstart, pend, anz, tid, ntasks) ; // ztype t = (ztype) Ax [pstart], with typecast GB_SCALAR (t) ; GB_CAST_ARRAY_TO_SCALAR (t, Ax, pstart) ; GB_IF_NOT_EARLY_EXIT { for (int64_t p = pstart+1 ; p < pend ; p++) { // check for early exit GB_PARALLEL_BREAK_IF_TERMINAL (t) ; // t = op (t, (ztype) Ax [p]), with typecast GB_ADD_CAST_ARRAY_TO_SCALAR (t, Ax, p) ; } } // W [tid] = t, no typecast GB_COPY_SCALAR_TO_ARRAY (W, tid, t) ; } //---------------------------------------------------------------------- // sum up the results of each slice using a single thread //---------------------------------------------------------------------- // s = W [0], no typecast GB_COPY_ARRAY_TO_SCALAR (s, W, 0) ; for (int tid = 1 ; tid < ntasks ; tid++) { // s = op (s, W [tid]), no typecast GB_ADD_ARRAY_TO_SCALAR (s, W, tid) ; } } }
GxB_Type_size.c
//------------------------------------------------------------------------------ // GxB_Type_size: return the size of a type //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB.h" GrB_Info GxB_Type_size // determine the size of the type ( size_t *size, // the sizeof the type GrB_Type type // type to determine the sizeof ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_Type_size (&size, type)") ; GB_RETURN_IF_NULL (size) ; GB_RETURN_IF_NULL_OR_FAULTY (type) ; //-------------------------------------------------------------------------- // return the size //-------------------------------------------------------------------------- (*size) = type->size ; #pragma omp flush return (GrB_SUCCESS) ; }
diffusion_grid.h
// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef CORE_DIFFUSION_GRID_H_ #define CORE_DIFFUSION_GRID_H_ #include <assert.h> #include <algorithm> #include <array> #include <cmath> #include <functional> #include <iostream> #include <string> #include <vector> #include "core/util/root.h" #include "core/container/math_array.h" #include "core/container/parallel_resize_vector.h" #include "core/param/param.h" #include "core/simulation.h" #include "core/util/log.h" #include "core/util/math.h" namespace bdm { /// A class that computes the diffusion of extracellular substances /// It maintains the concentration and gradient of a single substance class DiffusionGrid { public: explicit DiffusionGrid(TRootIOCtor* p) {} DiffusionGrid(int substance_id, std::string substance_name, double dc, double mu, int resolution = 11, unsigned int diffusion_step = 1) : substance_(substance_id), substance_name_(substance_name), dc_({{1 - dc, dc / 6, dc / 6, dc / 6, dc / 6, dc / 6, dc / 6}}), mu_(mu), resolution_(resolution), diffusion_step_(diffusion_step) {} virtual ~DiffusionGrid() {} /// @brief Initializes the grid by calculating the grid dimensions /// and number of boxes along the axis from the input arguments /// /// @param[in] grid_dimensions The grid dimensions /// @param[in] box_length The box length /// void Initialize(const std::array<int32_t, 6>& grid_dimensions) { // Get grid properties from neighbor grid grid_dimensions_ = grid_dimensions; assert(resolution_ > 0 && "The resolution cannot be zero!"); num_boxes_axis_[0] = resolution_; num_boxes_axis_[1] = resolution_; num_boxes_axis_[2] = resolution_; // Example: diffusion grid dimensions from 0-40 and resolution // of 4. Resolution must be adjusted otherwise one data pointer will be // missing. // Without adjustment: // box_length_: 10 // data points {0, 10, 20, 30} - 40 will be misssing! // With adjustment // box_length_: 13.3 // data points: {0, 13.3, 26.6, 39.9} box_length_ = (grid_dimensions_[1] - grid_dimensions_[0]) / static_cast<double>(resolution_ - 1); ParametersCheck(); box_volume_ = box_length_ * box_length_ * box_length_; assert(box_length_ > 0 && "Box length of diffusion grid must be greater than zero!"); // Set the parity of the number of boxes along the dimensions (since all // dimensions are the same, we just take the x-axis here) parity_ = num_boxes_axis_[0] % 2; total_num_boxes_ = num_boxes_axis_[0] * num_boxes_axis_[1] * num_boxes_axis_[2]; // Allocate memory for the concentration and gradient arrays c1_.resize(total_num_boxes_); c2_.resize(total_num_boxes_); gradients_.resize(3 * total_num_boxes_); // If we are utilising the Runge-Kutta method we need to resize an // additional vector, this will be used in estimating the concentration // between diffsuion steps. auto* param = Simulation::GetActive()->GetParam(); if (param->diffusion_type == "RK") { r1_.resize(total_num_boxes_); } initialized_ = true; } void ParametersCheck() { if (((1 - dc_[0]) * dt_) / (box_length_ * box_length_) >= (1.0 / 6)) { Log::Fatal( "DiffusionGrid", "The specified parameters of the diffusion grid with substance [", substance_name_, "] will result in unphysical behavior (diffusion coefficient = ", (1 - dc_[0]), ", resolution = ", resolution_, "). Please refer to the user guide for more information."); } else if (diffusion_step_ == 0) { Log::Fatal("DiffusionGrid", " The specified amount of diffusion steps for the grid with " "substance [", substance_name_, "] is not greater than or equal to 1, " "correct this and run the simulation again."); } } void RunInitializers() { assert(num_boxes_axis_[0] > 0 && "The number of boxes along an axis was found to be zero!"); if (initializers_.empty()) { return; } auto nx = num_boxes_axis_[0]; auto ny = num_boxes_axis_[1]; auto nz = num_boxes_axis_[2]; // Apply all functions that initialize this diffusion grid for (size_t f = 0; f < initializers_.size(); f++) { for (size_t x = 0; x < nx; x++) { double real_x = grid_dimensions_[0] + x * box_length_; for (size_t y = 0; y < ny; y++) { double real_y = grid_dimensions_[2] + y * box_length_; for (size_t z = 0; z < nz; z++) { double real_z = grid_dimensions_[4] + z * box_length_; std::array<uint32_t, 3> box_coord; box_coord[0] = x; box_coord[1] = y; box_coord[2] = z; size_t idx = GetBoxIndex(box_coord); ChangeConcentrationBy(idx, initializers_[f](real_x, real_y, real_z)); } } } } // Clear the initializer to free up space initializers_.clear(); initializers_.shrink_to_fit(); } /// @brief Updates the grid dimensions, based on the given threshold /// values. The diffusion grid dimensions need always be larger /// than the neighbor grid dimensions, so that each simulation /// object can obtain its local concentration / gradient /// /// @param[in] threshold_dimensions The threshold values /// void Update(const std::array<int32_t, 2>& threshold_dimensions) { // Update the grid dimensions such that each dimension ranges from // {treshold_dimensions[0] - treshold_dimensions[1]} auto min_gd = threshold_dimensions[0]; auto max_gd = threshold_dimensions[1]; grid_dimensions_ = {min_gd, max_gd, min_gd, max_gd, min_gd, max_gd}; // If the grid is not perfectly divisible along each dimension by the // box length, extend the grid so that it is int dimension_length = max_gd - min_gd; for (int i = 0; i < 3; i++) { int r = fmod(dimension_length, box_length_); if (r > 1e-9) { // std::abs for the case that box_length_ > dimension_length grid_dimensions_[2 * i + 1] += (box_length_ - r); } } // Calculate by how many boxes each dimension has grown int new_dimension_length = grid_dimensions_[1] - grid_dimensions_[0]; int new_num_boxes = std::ceil(new_dimension_length / box_length_); int growth = new_num_boxes - num_boxes_axis_[0]; if (growth > 0) { // Store the old number of boxes along each axis for comparison std::array<size_t, 3> tmp_num_boxes_axis = num_boxes_axis_; // Increase number of boxes along axis accordingly num_boxes_axis_[0] += growth; num_boxes_axis_[1] += growth; num_boxes_axis_[2] += growth; // We need to maintain the parity of the number of boxes along each // dimension, otherwise copying of the substances to the increases grid // will not be symmetrically done; resulting in shifting of boxes // We add a box in the negative direction, because the only way the parity // could have changed is because of adding a box in the positive direction // (due to the grid not being perfectly divisible; see above) if (num_boxes_axis_[0] % 2 != parity_) { for (int i = 0; i < 3; i++) { grid_dimensions_[2 * i] -= box_length_; num_boxes_axis_[i]++; } } // Temporarily save previous grid data auto tmp_c1 = c1_; auto tmp_gradients = gradients_; c1_.clear(); c2_.clear(); gradients_.clear(); total_num_boxes_ = num_boxes_axis_[0] * num_boxes_axis_[1] * num_boxes_axis_[2]; CopyOldData(tmp_c1, tmp_gradients, tmp_num_boxes_axis); assert(total_num_boxes_ >= tmp_num_boxes_axis[0] * tmp_num_boxes_axis[1] * tmp_num_boxes_axis[2] && "The diffusion grid tried to shrink! It can only become larger"); } // If we are utilising the Runge-Kutta method we need to resize an // additional vector, this will be used in estimating the concentration // between diffsuion steps. auto* param = Simulation::GetActive()->GetParam(); if (param->diffusion_type == "RK") { r1_.resize(total_num_boxes_); } } /// Copies the concentration and gradients values to the new /// (larger) grid. In the 2D case it looks like the following: /// /// [0 0 0 0] /// [v1 v2] --> [0 v1 v2 0] /// [v3 v4] --> [0 v3 v4 0] /// [0 0 0 0] /// /// The dimensions are doubled in this case from 2x2 to 4x4 /// If the dimensions would be increased from 2x2 to 3x3, it will still /// be increased to 4x4 in order for GetBoxIndex to function correctly /// void CopyOldData(const ParallelResizeVector<double>& old_c1, const ParallelResizeVector<double>& old_gradients, const std::array<size_t, 3>& old_num_boxes_axis) { // Allocate more memory for the grid data arrays c1_.resize(total_num_boxes_); c2_.resize(total_num_boxes_); gradients_.resize(3 * total_num_boxes_); auto incr_dim_x = num_boxes_axis_[0] - old_num_boxes_axis[0]; auto incr_dim_y = num_boxes_axis_[1] - old_num_boxes_axis[1]; auto incr_dim_z = num_boxes_axis_[2] - old_num_boxes_axis[2]; int off_x = incr_dim_x / 2; int off_y = incr_dim_y / 2; int off_z = incr_dim_z / 2; int num_box_xy = num_boxes_axis_[0] * num_boxes_axis_[1]; int old_box_xy = old_num_boxes_axis[0] * old_num_boxes_axis[1]; int new_origin = off_z * (num_boxes_axis_[0] * num_boxes_axis_[1]) + off_y * num_boxes_axis_[0] + off_x; for (size_t k = 0; k < old_num_boxes_axis[2]; k++) { int offset = new_origin + k * num_box_xy; for (size_t j = 0; j < old_num_boxes_axis[1]; j++) { if (j != 0) { offset += num_boxes_axis_[0]; } for (size_t i = 0; i < old_num_boxes_axis[0]; i++) { auto idx = k * old_box_xy + j * old_num_boxes_axis[0] + i; c1_[offset + i] = old_c1[idx]; gradients_[3 * (offset + i)] = old_gradients[3 * idx]; gradients_[3 * (offset + i) + 1] = old_gradients[3 * idx + 1]; gradients_[3 * (offset + i) + 2] = old_gradients[3 * idx + 2]; } } } } /// Solves a 5-point stencil diffusion equation, with leaking-edge /// boundary conditions. Substances are allowed to leave the simulation /// space. This prevents building up concentration at the edges /// void DiffuseWithLeakingEdge() { int nx = num_boxes_axis_[0]; int ny = num_boxes_axis_[1]; int nz = num_boxes_axis_[2]; #define YBF 16 #pragma omp parallel for collapse(2) for (int yy = 0; yy < ny; yy += YBF) { for (int z = 0; z < nz; z++) { // To let the edges bleed we set some diffusion coefficients // to zero. This prevents substance building up at the edges auto dc_2_ = dc_; int ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (int y = yy; y < ymax; y++) { dc_2_ = dc_; int x; int c, n, s, b, t; x = 0; c = x + y * nx + z * nx * ny; if (y == 0) { n = c; dc_2_[4] = 0; } else { n = c - nx; } if (y == (ny - 1)) { s = c; dc_2_[3] = 0; } else { s = c + nx; } if (z == 0) { b = c; dc_2_[5] = 0; } else { b = c - nx * ny; } if (z == (nz - 1)) { t = c; dc_2_[6] = 0; } else { t = c + nx * ny; } // x = 0; we leak out substances past this edge (so multiply by 0) c2_[c] = (dc_2_[0] * c1_[c] + 0 * c1_[c] + dc_2_[2] * c1_[c + 1] + dc_2_[3] * c1_[s] + dc_2_[4] * c1_[n] + dc_2_[5] * c1_[b] + dc_2_[6] * c1_[t]) * (1 - mu_); #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; c2_[c] = (dc_2_[0] * c1_[c] + dc_2_[1] * c1_[c - 1] + dc_2_[2] * c1_[c + 1] + dc_2_[3] * c1_[s] + dc_2_[4] * c1_[n] + dc_2_[5] * c1_[b] + dc_2_[6] * c1_[t]) * (1 - mu_); } ++c; ++n; ++s; ++b; ++t; // x = nx-1; we leak out substances past this edge (so multiply by 0) c2_[c] = (dc_2_[0] * c1_[c] + dc_2_[1] * c1_[c - 1] + 0 * c1_[c] + dc_2_[3] * c1_[s] + dc_2_[4] * c1_[n] + dc_2_[5] * c1_[b] + dc_2_[6] * c1_[t]) * (1 - mu_); } // tile ny } // tile nz } // block ny c1_.swap(c2_); } /// Solves a 5-point stencil diffusion equation, with closed-edge /// boundary conditions. Substances are not allowed to leave the simulation /// space. Keep in mind that the concentration can build up at the edges /// void DiffuseWithClosedEdge() { auto nx = num_boxes_axis_[0]; auto ny = num_boxes_axis_[1]; auto nz = num_boxes_axis_[2]; #define YBF 16 #pragma omp parallel for collapse(2) for (size_t yy = 0; yy < ny; yy += YBF) { for (size_t z = 0; z < nz; z++) { size_t ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (size_t y = yy; y < ymax; y++) { size_t x; int c, n, s, b, t; x = 0; c = x + y * nx + z * nx * ny; n = (y == 0) ? c : c - nx; s = (y == ny - 1) ? c : c + nx; b = (z == 0) ? c : c - nx * ny; t = (z == nz - 1) ? c : c + nx * ny; c2_[c] = (dc_[0] * c1_[c] + dc_[1] * c1_[c] + dc_[2] * c1_[c + 1] + dc_[3] * c1_[s] + dc_[4] * c1_[n] + dc_[5] * c1_[b] + dc_[6] * c1_[t]) * (1 - mu_); #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; c2_[c] = (dc_[0] * c1_[c] + dc_[1] * c1_[c - 1] + dc_[2] * c1_[c + 1] + dc_[3] * c1_[s] + dc_[4] * c1_[n] + dc_[5] * c1_[b] + dc_[6] * c1_[t]) * (1 - mu_); } ++c; ++n; ++s; ++b; ++t; c2_[c] = (dc_[0] * c1_[c] + dc_[1] * c1_[c - 1] + dc_[2] * c1_[c] + dc_[3] * c1_[s] + dc_[4] * c1_[n] + dc_[5] * c1_[b] + dc_[6] * c1_[t]) * (1 - mu_); } // tile ny } // tile nz } // block ny c1_.swap(c2_); } void DiffuseEuler() { // check if diffusion coefficient and decay constant are 0 // i.e. if we don't need to calculate diffusion update if (IsFixedSubstance()) { return; } const auto nx = num_boxes_axis_[0]; const auto ny = num_boxes_axis_[1]; const auto nz = num_boxes_axis_[2]; const double ibl2 = 1 / (box_length_ * box_length_); const double d = 1 - dc_[0]; #define YBF 16 #pragma omp parallel for collapse(2) for (size_t yy = 0; yy < ny; yy += YBF) { for (size_t z = 0; z < nz; z++) { size_t ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (size_t y = yy; y < ymax; y++) { size_t x = 0; int c, n, s, b, t; c = x + y * nx + z * nx * ny; #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; if (y == 0 || y == (ny - 1) || z == 0 || z == (nz - 1)) { continue; } n = c - nx; s = c + nx; b = c - nx * ny; t = c + nx * ny; c2_[c] = (c1_[c] + d * dt_ * (c1_[c - 1] - 2 * c1_[c] + c1_[c + 1]) * ibl2 + d * dt_ * (c1_[s] - 2 * c1_[c] + c1_[n]) * ibl2 + d * dt_ * (c1_[b] - 2 * c1_[c] + c1_[t]) * ibl2) * (1 - mu_); } ++c; ++n; ++s; ++b; ++t; } // tile ny } // tile nz } // block ny c1_.swap(c2_); } void DiffuseEulerLeakingEdge() { // check if diffusion coefficient and decay constant are 0 // i.e. if we don't need to calculate diffusion update if (IsFixedSubstance()) { return; } const auto nx = num_boxes_axis_[0]; const auto ny = num_boxes_axis_[1]; const auto nz = num_boxes_axis_[2]; const double ibl2 = 1 / (box_length_ * box_length_); const double d = 1 - dc_[0]; std::array<int, 4> l; #define YBF 16 #pragma omp parallel for collapse(2) for (size_t yy = 0; yy < ny; yy += YBF) { for (size_t z = 0; z < nz; z++) { size_t ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (size_t y = yy; y < ymax; y++) { size_t x = 0; int c, n, s, b, t; c = x + y * nx + z * nx * ny; l.fill(1); if (y == 0) { n = c; l[0] = 0; } else { n = c - nx; } if (y == ny - 1) { s = c; l[1] = 0; } else { s = c + nx; } if (z == 0) { b = c; l[2] = 0; } else { b = c - nx * ny; } if (z == nz - 1) { t = c; l[3] = 0; } else { t = c + nx * ny; } c2_[c] = (c1_[c] + d * dt_ * (0 - 2 * c1_[c] + c1_[c + 1]) * ibl2 + d * dt_ * (c1_[s] - 2 * c1_[c] + c1_[n]) * ibl2 + d * dt_ * (c1_[b] - 2 * c1_[c] + c1_[t]) * ibl2) * (1 - mu_); #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; c2_[c] = (c1_[c] + d * dt_ * (c1_[c - 1] - 2 * c1_[c] + c1_[c + 1]) * ibl2 + d * dt_ * (l[0] * c1_[s] - 2 * c1_[c] + l[1] * c1_[n]) * ibl2 + d * dt_ * (l[2] * c1_[b] - 2 * c1_[c] + l[3] * c1_[t]) * ibl2) * (1 - mu_); } ++c; ++n; ++s; ++b; ++t; c2_[c] = (c1_[c] + d * dt_ * (c1_[c - 1] - 2 * c1_[c] + 0) * ibl2 + d * dt_ * (c1_[s] - 2 * c1_[c] + c1_[n]) * ibl2 + d * dt_ * (c1_[b] - 2 * c1_[c] + c1_[t]) * ibl2) * (1 - mu_); } // tile ny } // tile nz } // block ny c1_.swap(c2_); } void RK() { // check if diffusion coefficient and decay constant are 0 // i.e. if we don't need to calculate diffusion update if (IsFixedSubstance()) { return; } const auto nx = num_boxes_axis_[0]; const auto ny = num_boxes_axis_[1]; const auto nz = num_boxes_axis_[2]; const double ibl2 = 1 / (box_length_ * box_length_); const double d = 1 - dc_[0]; double step = diffusion_step_; double h = dt_ / step; #define YBF 16 for (size_t i = 0; i < step; i++) { for (size_t order = 0; order < 2; order++) { #pragma omp parallel for collapse(2) for (size_t yy = 0; yy < ny; yy += YBF) { for (size_t z = 0; z < nz; z++) { size_t ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (size_t y = yy; y < ymax; y++) { size_t x = 0; int c, n, s, b, t; c = x + y * nx + z * nx * ny; #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; if (y == 0 || y == (ny - 1) || z == 0 || z == (nz - 1)) { continue; } n = c - nx; s = c + nx; b = c - nx * ny; t = c + nx * ny; double h2 = h / 2.0; if (order == 0) { k_[0] = (d * (c1_[c - 1] - 2 * c1_[c] + c1_[c + 1]) * ibl2 + d * (c1_[s] - 2 * c1_[c] + c1_[n]) * ibl2 + d * (c1_[b] - 2 * c1_[c] + c1_[t]) * ibl2); r1_[c] = c1_[c] + (k_[0] * h2); } else if (order == 1) { k_[1] = (d * (c1_[c - 1] - 2 * c1_[c] + c1_[c + 1]) * ibl2 + d * (c1_[s] - 2 * c1_[c] + c1_[n]) * ibl2 + d * (c1_[b] - 2 * c1_[c] + c1_[t]) * ibl2); c2_[c] = c1_[c] + (k_[1] * h); } } ++c; ++n; ++s; ++b; ++t; } // tile ny } // tile nz } // block ny } c1_.swap(c2_); } } void RKLeaking() { // check if diffusion coefficient and decay constant are 0 // i.e. if we don't need to calculate diffusion update if (IsFixedSubstance()) { return; } const auto nx = num_boxes_axis_[0]; const auto ny = num_boxes_axis_[1]; const auto nz = num_boxes_axis_[2]; const double ibl2 = 1 / (box_length_ * box_length_); const double d = 1 - dc_[0]; std::array<int, 6> l; double step = diffusion_step_; double h = dt_ / step; #define YBF 16 for (size_t i = 0; i < step; i++) { for (size_t order = 0; order < 2; order++) { #pragma omp parallel for collapse(2) for (size_t yy = 0; yy < ny; yy += YBF) { for (size_t z = 0; z < nz; z++) { size_t ymax = yy + YBF; if (ymax >= ny) { ymax = ny; } for (size_t y = yy; y < ymax; y++) { size_t x = 0; int c, cm, cp, n, s, b, t; c = x + y * nx + z * nx * ny; l.fill(1); if (y == 0) { n = c; l[2] = 0; } else { n = c - nx; } if (y == ny - 1) { s = c; l[3] = 0; } else { s = c + nx; } if (z == 0) { b = c; l[4] = 0; } else { b = c - nx * ny; } if (z == nz - 1) { t = c; l[5] = 0; } else { t = c + nx * ny; } #pragma omp simd for (x = 1; x < nx - 1; x++) { ++c; ++n; ++s; ++b; ++t; if (x == 0) { cm = c; l[0] = 0; } else { cm = c - 1; } if (y == ny - 1) { cp = c; l[1] = 0; } else { cp = c + 1; } double h2 = h / 2.0; if (order == 0) { k_[0] = d * (l[0] * c1_[cm] - 2 * c1_[c] + l[1] * c1_[cp]) * ibl2 + d * (l[2] * c1_[s] - 2 * c1_[c] + l[3] * c1_[n]) * ibl2 + d * (l[4] * c1_[b] - 2 * c1_[c] + l[5] * c1_[t]) * ibl2; r1_[c] = c1_[c] + (k_[0] * h2); } else if (order == 1) { k_[1] = d * (l[0] * c1_[cm] - 2 * c1_[c] + l[1] * c1_[cp]) * ibl2 + d * (l[2] * c1_[s] - 2 * c1_[c] + l[3] * c1_[n]) * ibl2 + d * (l[4] * c1_[b] - 2 * c1_[c] + l[5] * c1_[t]) * ibl2; c2_[c] = c1_[c] + (k_[1] * h); } } ++c; ++n; ++s; ++b; ++t; } // tile ny } // tile nz } // block ny } c1_.swap(c2_); } } /// Calculates the gradient for each box in the diffusion grid. /// The gradient is calculated in each direction (x, y, z) as following: /// /// c(x + box_length_) - c(x - box_length) / (2 * box_length_), /// /// where c(x) implies the concentration at position x /// /// At the edges the gradient is the same as the box next to it void CalculateGradient() { // check if gradient has been calculated once // and if diffusion coefficient and decay constant are 0 // i.e. if we don't need to calculate gradient update if (init_gradient_ && IsFixedSubstance()) { return; } double gd = 1 / (box_length_ * 2); auto nx = num_boxes_axis_[0]; auto ny = num_boxes_axis_[1]; auto nz = num_boxes_axis_[2]; #pragma omp parallel for collapse(2) for (size_t z = 0; z < nz; z++) { for (size_t y = 0; y < ny; y++) { for (size_t x = 0; x < nx; x++) { int c, e, w, n, s, b, t; c = x + y * nx + z * nx * ny; if (x == 0) { e = c; w = c + 2; } else if (x == nx - 1) { e = c - 2; w = c; } else { e = c - 1; w = c + 1; } if (y == 0) { n = c + 2 * nx; s = c; } else if (y == ny - 1) { n = c; s = c - 2 * nx; } else { n = c + nx; s = c - nx; } if (z == 0) { t = c + 2 * nx * ny; b = c; } else if (z == nz - 1) { t = c; b = c - 2 * nx * ny; } else { t = c + nx * ny; b = c - nx * ny; } // Let the gradient point from low to high concentration gradients_[3 * c + 0] = (c1_[w] - c1_[e]) * gd; gradients_[3 * c + 1] = (c1_[n] - c1_[s]) * gd; gradients_[3 * c + 2] = (c1_[t] - c1_[b]) * gd; } } } if (!init_gradient_) { init_gradient_ = true; } } /// Increase the concentration at specified position with specified amount virtual void ChangeConcentrationBy(const Double3& position, double amount) { auto idx = GetBoxIndex(position); ChangeConcentrationBy(idx, amount); } /// Increase the concentration at specified box with specified amount void ChangeConcentrationBy(size_t idx, double amount) { assert(idx < total_num_boxes_ && "Cell position is out of diffusion grid bounds"); c1_[idx] += amount; if (c1_[idx] > concentration_threshold_) { c1_[idx] = concentration_threshold_; } } /// Get the concentration at specified position double GetConcentration(const Double3& position) const { return c1_[GetBoxIndex(position)]; } /// Get the (normalized) gradient at specified position virtual void GetGradient(const Double3& position, Double3* gradient) const { auto idx = GetBoxIndex(position); assert(idx < total_num_boxes_ && "Cell position is out of diffusion grid bounds"); (*gradient)[0] = gradients_[3 * idx]; (*gradient)[1] = gradients_[3 * idx + 1]; (*gradient)[2] = gradients_[3 * idx + 2]; auto norm = std::sqrt((*gradient)[0] * (*gradient)[0] + (*gradient)[1] * (*gradient)[1] + (*gradient)[2] * (*gradient)[2]); if (norm > 1e-10) { (*gradient)[0] /= norm; (*gradient)[1] /= norm; (*gradient)[2] /= norm; } } std::array<uint32_t, 3> GetBoxCoordinates(const Double3& position) const { std::array<uint32_t, 3> box_coord; box_coord[0] = (floor(position[0]) - grid_dimensions_[0]) / box_length_; box_coord[1] = (floor(position[1]) - grid_dimensions_[2]) / box_length_; box_coord[2] = (floor(position[2]) - grid_dimensions_[4]) / box_length_; return box_coord; } size_t GetBoxIndex(const std::array<uint32_t, 3>& box_coord) const { size_t ret = box_coord[2] * num_boxes_axis_[0] * num_boxes_axis_[1] + box_coord[1] * num_boxes_axis_[0] + box_coord[0]; return ret; } /// Calculates the box index of the substance at specified position size_t GetBoxIndex(const Double3& position) const { auto box_coord = GetBoxCoordinates(position); return GetBoxIndex(box_coord); } void SetDiffusionSteps(int diffusion_step) { diffusion_step_ = diffusion_step; } void SetDecayConstant(double mu) { mu_ = mu; } void SetConcentrationThreshold(double t) { concentration_threshold_ = t; } double GetConcentrationThreshold() const { return concentration_threshold_; } const double* GetAllConcentrations() const { return c1_.data(); } const double* GetAllGradients() const { return gradients_.data(); } const std::array<size_t, 3>& GetNumBoxesArray() const { return num_boxes_axis_; } size_t GetNumBoxes() const { return total_num_boxes_; } double GetBoxLength() const { return box_length_; } int GetSubstanceId() const { return substance_; } const std::string& GetSubstanceName() const { return substance_name_; } double GetDecayConstant() const { return mu_; } const int32_t* GetDimensionsPtr() const { return grid_dimensions_.data(); } const std::array<int32_t, 6>& GetDimensions() const { return grid_dimensions_; } std::array<int32_t, 3> GetGridSize() const { std::array<int32_t, 3> ret; ret[0] = grid_dimensions_[1] - grid_dimensions_[0]; ret[1] = grid_dimensions_[3] - grid_dimensions_[2]; ret[2] = grid_dimensions_[5] - grid_dimensions_[4]; return ret; } const std::array<double, 7>& GetDiffusionCoefficients() const { return dc_; } bool IsInitialized() const { return initialized_; } int GetResolution() const { return resolution_; } double GetBoxVolume() const { return box_volume_; } template <typename F> void AddInitializer(F function) { initializers_.push_back(function); } // retrun true if substance concentration and gradient don't evolve over time bool IsFixedSubstance() { return (mu_ == 0 && dc_[1] == 0 && dc_[2] == 0 && dc_[3] == 0 && dc_[4] == 0 && dc_[5] == 0 && dc_[6] == 0); } private: /// The id of the substance of this grid int substance_ = 0; /// The name of the substance of this grid std::string substance_name_ = ""; /// The side length of each box double box_length_ = 0; /// the volume of each box double box_volume_ = 0; /// The array of concentration values ParallelResizeVector<double> c1_ = {}; /// An extra concentration data buffer for faster value updating ParallelResizeVector<double> c2_ = {}; /// Buffers for Runge Kutta ParallelResizeVector<double> r1_ = {}; /// k array for runge-kutta. std::array<double, 2> k_ = {}; /// The array of gradients (x, y, z) ParallelResizeVector<double> gradients_ = {}; /// The maximum concentration value that a box can have double concentration_threshold_ = 1e15; /// The diffusion coefficients [cc, cw, ce, cs, cn, cb, ct] std::array<double, 7> dc_ = {{0}}; /// The timestep resolution fhe diffusion grid // TODO(ahmad): this probably needs to scale with Param::simulation_timestep double dt_ = 1.0; /// The decay constant double mu_ = 0; /// The grid dimensions of the diffusion grid std::array<int32_t, 6> grid_dimensions_ = {{0}}; /// The number of boxes at each axis [x, y, z] std::array<size_t, 3> num_boxes_axis_ = {{0}}; /// The total number of boxes in the diffusion grid size_t total_num_boxes_ = 0; /// Flag to determine if this grid has been initialized bool initialized_ = false; /// The resolution of the diffusion grid int resolution_ = 0; /// Number of steps for RK diffusion grid; unsigned int diffusion_step_ = 1; /// If false, grid dimensions are even; if true, they are odd bool parity_ = false; /// A list of functions that initialize this diffusion grid /// ROOT currently doesn't support IO of std::function std::vector<std::function<double(double, double, double)>> initializers_ = {}; //! // turn to true after gradient initialization bool init_gradient_ = false; BDM_CLASS_DEF_NV(DiffusionGrid, 1); }; } // namespace bdm #endif // CORE_DIFFUSION_GRID_H_
omp_quiesce_overhead.c
// input number of thread #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <signal.h> #include <omp.h> //#include <omp_interop.h> #include <sys/timeb.h> #include <unistd.h> void *omp_parallel_foo(void *ptr); /**Important: make sure you use num_threads clause in parallel direction and set it to the * number of hardware cores, not the number of cores Linux gives or the default from OpenMP * * cat /proc/cpuinfo and check the processor id, core id and CPU model number so you can look up fron internet * Lennon is Xeon CPU E5-2683 v3 @ 2.00GHz, it has two CPU for total 28 cores, but support upto 56 threads * Paul is Xeon CPU E5-2695 v2 @ 2.40GHz, it has two CPU for total 24 cores, support upto 48 threads * Fornax Intel® Xeon® E5-2699 v3 2.3GHz, it has two CPU for total 36 cores, support upto 72 threads. * * Use -O0 optimization */ double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } void omp_quiesce_overhead(int nthreads); int main(int argc, char * argv[]) { int thr_num = 4; if (argc >= 2) thr_num = (atoi(argv[1])); omp_quiesce_overhead(thr_num); exit(0); } /** * TODO: how to make sure that an empty parallel do not get optimized out by the compiler */ void omp_quiesce_overhead(int nthreads) { int i; int NUM_ITERATIONS = 1000; double quiesce_ov = 0.0; double quiesce_start_ov = 0.0; double cost_all = read_timer(); for (i=0; i<NUM_ITERATIONS; i++) { //double temp = read_timer(); #pragma omp parallel num_threads(nthreads) { //int tid = omp_get_thread_num(); } double temp2 = read_timer(); omp_quiesce(); quiesce_ov += read_timer() - temp2; //quiesce_start_ov += read_timer() - temp; } cost_all = read_timer() - cost_all; // this is for not quiesce double parallel_overhead = read_timer(); for (i=0; i<NUM_ITERATIONS; i++) { #pragma omp parallel num_threads(nthreads) { //int tid = omp_get_thread_num(); } } parallel_overhead = read_timer() - parallel_overhead; printf("quiesce overhead : %f\n", quiesce_ov/NUM_ITERATIONS); printf("quiesce_start overhead: %f\n", (cost_all - parallel_overhead)/NUM_ITERATIONS); printf("Total cost: %f\n", cost_all/NUM_ITERATIONS); // while(1); return; }
parallel_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Denis Demidov // Philipp Bucher // #if !defined(KRATOS_PARALLEL_UTILITIES_H_INCLUDED) #define KRATOS_PARALLEL_UTILITIES_H_INCLUDED // System includes #include <iostream> #include <array> #include <vector> #include <tuple> #include <cmath> #include <limits> #include <future> #include <thread> // External includes #ifdef KRATOS_SMP_OPENMP #include <omp.h> #endif // Project includes #include "includes/define.h" #include "includes/global_variables.h" #include "utilities/reduction_utilities.h" namespace Kratos { ///@addtogroup KratosCore /// Shared memory parallelism related helper class /** Provides access to functionalities for shared memory parallelism * such as the number of threads in usa. */ class KRATOS_API(KRATOS_CORE) ParallelUtilities { public: ///@name Life Cycle ///@{ ///@} ///@name Operations ///@{ /** @brief Returns the current number of threads * @return number of threads */ static int GetNumThreads(); /** @brief Sets the current number of threads * @param NumThreads - the number of threads to be used */ static void SetNumThreads(const int NumThreads); /** @brief Returns the number of processors available to this device * This can include the multiple threads per processing unit * @return number of processors */ static int GetNumProcs(); ///@} private: ///@name Static Member Variables ///@{ static int* mspNumThreads; ///@} ///@name Private Operations ///@{ /// Default constructor. ParallelUtilities() = delete; /** @brief Initializes the number of threads to be used. * @return number of threads */ static int InitializeNumberOfThreads(); ///@} ///@name Private Access ///@{ static int& GetNumberOfThreads(); ///@} }; // Class ParallelUtilities //*********************************************************************************** //*********************************************************************************** //*********************************************************************************** /** @param TContainerType - the type of the container used in the loop (must provide random access iterators) * @param TIteratorType - type of iterator (by default as provided by the TContainerType) * @param TMaxThreads - maximum number of threads allowed in the partitioning. * must be known at compile time to avoid heap allocations in the partitioning */ template< class TContainerType, class TIteratorType=decltype(std::declval<TContainerType>().begin()), int TMaxThreads=Globals::MaxAllowedThreads > class BlockPartition { public: /** @param it_begin - iterator pointing at the beginning of the container * @param it_end - iterator pointing to the end of the container * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ BlockPartition(TIteratorType it_begin, TIteratorType it_end, int Nchunks = ParallelUtilities::GetNumThreads()) { KRATOS_ERROR_IF(Nchunks < 1) << "Number of chunks must be > 0 (and not " << Nchunks << ")" << std::endl; const std::ptrdiff_t size_container = it_end-it_begin; if (size_container == 0) { mNchunks = Nchunks; } else { // in case the container is smaller than the number of chunks mNchunks = std::min(static_cast<int>(size_container), Nchunks); } const std::ptrdiff_t block_partition_size = size_container / mNchunks; mBlockPartition[0] = it_begin; mBlockPartition[mNchunks] = it_end; for (int i=1; i<mNchunks; i++) { mBlockPartition[i] = mBlockPartition[i-1] + block_partition_size; } } /** @param rData - the continer to be iterated upon * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ template <class TData> BlockPartition(TData &&rData, int Nchunks = ParallelUtilities::GetNumThreads()) : BlockPartition(rData.begin(), rData.end(), Nchunks) {} virtual ~BlockPartition() = default; /** @brief simple iteration loop. f called on every entry in rData * @param f - must be a unary function accepting as input TContainerType::value_type& */ template <class TUnaryFunction> inline void for_each(TUnaryFunction&& f) { #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { f(*it); //note that we pass the value to the function, not the iterator } } } /** @brief loop allowing reductions. f called on every entry in rData * the function f needs to return the values to be used by the reducer * @param TReducer template parameter specifying the reduction operation to be done * @param f - must be a unary function accepting as input TContainerType::value_type& */ template <class TReducer, class TUnaryFunction> inline typename TReducer::value_type for_each(TUnaryFunction &&f) { TReducer global_reducer; #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { TReducer local_reducer; for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { local_reducer.LocalReduce(f(*it)); } global_reducer.ThreadSafeReduce(local_reducer); } return global_reducer.GetValue(); } /** @brief loop with thread local storage (TLS). f called on every entry in rData * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TThreadLocalStorage, class TFunction> inline void for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for(int i=0; i<mNchunks; ++i){ for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it){ f(*it, thread_local_storage); // note that we pass the value to the function, not the iterator } } } } /** @brief loop with thread local storage (TLS) allowing reductions. f called on every entry in rData * the function f needs to return the values to be used by the reducer * @param TReducer template parameter specifying the reduction operation to be done * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TReducer, class TThreadLocalStorage, class TFunction> inline typename TReducer::value_type for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); TReducer global_reducer; #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { TReducer local_reducer; for (auto it = mBlockPartition[i]; it != mBlockPartition[i+1]; ++it) { local_reducer.LocalReduce(f(*it, thread_local_storage)); } global_reducer.ThreadSafeReduce(local_reducer); } } return global_reducer.GetValue(); } private: int mNchunks; std::array<TIteratorType, TMaxThreads> mBlockPartition; }; /** @brief simplified version of the basic loop (without reduction) to enable template type deduction * @param v - containers to be looped upon * @param func - must be a unary function accepting as input TContainerType::value_type& */ template <class TContainerType, class TFunctionType> void block_for_each(TContainerType &&v, TFunctionType &&func) { BlockPartition<TContainerType>(v.begin(), v.end()).for_each(std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with reduction to enable template type deduction * @param v - containers to be looped upon * @param func - must be a unary function accepting as input TContainerType::value_type& */ template <class TReducer, class TContainerType, class TFunctionType> typename TReducer::value_type block_for_each(TContainerType &&v, TFunctionType &&func) { return BlockPartition<TContainerType>(v.begin(), v.end()).template for_each<TReducer>(std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with thread local storage (TLS) to enable template type deduction * @param v - containers to be looped upon * @param tls - thread local storage * @param func - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TContainerType, class TThreadLocalStorage, class TFunctionType> void block_for_each(TContainerType &&v, const TThreadLocalStorage& tls, TFunctionType &&func) { BlockPartition<TContainerType>(v.begin(), v.end()).for_each(tls, std::forward<TFunctionType>(func)); } /** @brief simplified version of the basic loop with reduction and thread local storage (TLS) to enable template type deduction * @param v - containers to be looped upon * @param tls - thread local storage * @param func - must be a function accepting as input TContainerType::value_type& and the thread local storage */ template <class TReducer, class TContainerType, class TThreadLocalStorage, class TFunctionType> typename TReducer::value_type block_for_each(TContainerType &&v, const TThreadLocalStorage& tls, TFunctionType &&func) { return BlockPartition<TContainerType>(v.begin(), v.end()).template for_each<TReducer>(tls, std::forward<TFunctionType>(func)); } //*********************************************************************************** //*********************************************************************************** //*********************************************************************************** /** @brief This class is useful for index iteration over containers * @param TIndexType type of index to be used in the loop * @param TMaxThreads - maximum number of threads allowed in the partitioning. * must be known at compile time to avoid heap allocations in the partitioning */ template<class TIndexType=std::size_t, int TMaxThreads=Globals::MaxAllowedThreads> class IndexPartition { public: /** @brief constructor using the size of the partition to be used * @param Size - the size of the partition * @param Nchunks - number of threads to be used in the loop (must be lower than TMaxThreads) */ IndexPartition(TIndexType Size, int Nchunks = ParallelUtilities::GetNumThreads()) { KRATOS_ERROR_IF(Nchunks < 1) << "Number of chunks must be > 0 (and not " << Nchunks << ")" << std::endl; if (Size == 0) { mNchunks = Nchunks; } else { // in case the container is smaller than the number of chunks mNchunks = std::min(static_cast<int>(Size), Nchunks); } const int block_partition_size = Size / mNchunks; mBlockPartition[0] = 0; mBlockPartition[mNchunks] = Size; for (int i=1; i<mNchunks; i++) { mBlockPartition[i] = mBlockPartition[i-1] + block_partition_size; } } virtual ~IndexPartition() = default; //NOT COMMENTING IN DOXYGEN - THIS SHOULD BE SORT OF HIDDEN UNTIL GIVEN PRIME TIME //pure c++11 version (can handle exceptions) template <class TUnaryFunction> inline void for_pure_c11(TUnaryFunction &&f) { std::vector< std::future<void> > runners(mNchunks); const auto& partition = mBlockPartition; for (int i=0; i<mNchunks; ++i) { runners[i] = std::async(std::launch::async, [&partition, i, &f]() { for (auto k = partition[i]; k < partition[i+1]; ++k) { f(k); } }); } //here we impose a syncronization and we check the exceptions for(int i=0; i<mNchunks; ++i) { try { runners[i].get(); } catch(Exception& e) { KRATOS_ERROR << std::endl << "THREAD number: " << i << " caught exception " << e.what() << std::endl; } catch(std::exception& e) { KRATOS_ERROR << std::endl << "THREAD number: " << i << " caught exception " << e.what() << std::endl; } catch(...) { KRATOS_ERROR << std::endl << "unknown error" << std::endl; } } } /** simple version of for_each (no reduction) to be called for each index in the partition * @param f - must be a unary function accepting as input IndexType */ template <class TUnaryFunction> inline void for_each(TUnaryFunction &&f) { #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { f(k); //note that we pass a reference to the value, not the iterator } } } /** version with reduction to be called for each index in the partition * function f is expected to return the values to be reduced * @param TReducer - template parameter specifying the type of reducer to be applied * @param f - must be a unary function accepting as input IndexType */ template <class TReducer, class TUnaryFunction> inline typename TReducer::value_type for_each(TUnaryFunction &&f) { TReducer global_reducer; #pragma omp parallel for for (int i=0; i<mNchunks; ++i) { TReducer local_reducer; for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { local_reducer.LocalReduce(f(k)); } global_reducer.ThreadSafeReduce(local_reducer); } return global_reducer.GetValue(); } /** @brief loop with thread local storage (TLS). f called on every entry in rData * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input IndexType and the thread local storage */ template <class TThreadLocalStorage, class TFunction> inline void for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { f(k, thread_local_storage); //note that we pass a reference to the value, not the iterator } } } } /** version with reduction and thread local storage (TLS) to be called for each index in the partition * function f is expected to return the values to be reduced * @param TReducer - template parameter specifying the type of reducer to be applied * @param TThreadLocalStorage template parameter specifying the thread local storage * @param f - must be a function accepting as input IndexType and the thread local storage */ template <class TReducer, class TThreadLocalStorage, class TFunction> inline typename TReducer::value_type for_each(const TThreadLocalStorage& rThreadLocalStoragePrototype, TFunction &&f) { static_assert(std::is_copy_constructible<TThreadLocalStorage>::value, "TThreadLocalStorage must be copy constructible!"); TReducer global_reducer; #pragma omp parallel { // copy the prototype to create the thread local storage TThreadLocalStorage thread_local_storage(rThreadLocalStoragePrototype); #pragma omp for for (int i=0; i<mNchunks; ++i) { TReducer local_reducer; for (auto k = mBlockPartition[i]; k < mBlockPartition[i+1]; ++k) { local_reducer.LocalReduce(f(k, thread_local_storage)); } global_reducer.ThreadSafeReduce(local_reducer); } } return global_reducer.GetValue(); } private: int mNchunks; std::array<TIndexType, TMaxThreads> mBlockPartition; }; } // namespace Kratos. #endif // KRATOS_PARALLEL_UTILITIES_H_INCLUDED defined
pr58392.c
/* PR tree-optimization/58392 */ /* { dg-do run } */ /* { dg-additional-options "-msse2" { target sse2_runtime } } */ /* { dg-additional-options "-mavx" { target avx_runtime } } */ extern void abort (void); int d[32 * 32]; __attribute__((noinline, noclone)) int foo (int a, int b) { int j, c = 0; #pragma omp parallel for reduction(+: c) for (j = 0; j < a; j += 32) { int l; #pragma omp simd reduction(+: c) for (l = 0; l < b; ++l) c += d[j + l]; } return c; } __attribute__((noinline, noclone)) int bar (int a) { int j, c = 0; #pragma omp parallel for simd reduction(+: c) for (j = 0; j < a; ++j) c += d[j]; return c; } __attribute__((noinline)) static int baz (int a) { int j, c = 0; #pragma omp simd reduction(+: c) for (j = 0; j < a; ++j) c += d[j]; return c; } int main () { int i; for (i = 0; i < 32 * 32; i++) d[i] = (i & 31); if (foo (32 * 32, 32) != (31 * 32 / 2) * 32) abort (); if (bar (32 * 32) != (31 * 32 / 2) * 32) abort (); if (baz (32 * 32) != (31 * 32 / 2) * 32) abort (); return 0; }
pooling_pack_x86.h
#include <emmintrin.h> #include <stdio.h> #include <assert.h> #include "pooling_param.h" #define POOL_GENERIC 0 #define POOL_K2S2 1 #define POOL_K3S2 2 #define POOL_K3S1 3 typedef void (*pooling_kernel_t)(const void* input, void* output, int inc, int inh, int inw, int outh, int outw, int, int, int, int, int, int, int pad_h1, int pad_w1, int); static inline float max(float a, float b) { if (a > b) return a; else return b; } static void avg_2x2s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } int loopw = (inw - 1) >> 1; int looph = (inh - 1) >> 1; int remain_w = inw - outw * 2; __m128 scalar_025 = _mm_set1_ps(0.25f); __m128 scalar_05 = _mm_set1_ps(0.5f); if (inw % 2 == 0) { remain_w = 1; } else { remain_w = 0; } const float* line0 = input; const float* line1; float* out_ptr = output; __m128 line00; __m128 line01; __m128 line10; __m128 line11; __m128 sum0; __m128 sum1; __m128 sum; line00 = _mm_loadu_ps(line0); if (is_caffe == 1) { line00 = _mm_mul_ps(line00, scalar_025); } _mm_storeu_ps(out_ptr, line00); line0 += 4; out_ptr += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum0 = _mm_add_ps(line00, line01); if (is_caffe == 0) { sum0 = _mm_mul_ps(sum0, scalar_05); } else { sum0 = _mm_mul_ps(sum0, scalar_025); } _mm_storeu_ps(out_ptr, sum0); out_ptr += 4; line0 += 8; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); if (is_caffe == 1) { line00 = _mm_mul_ps(line00, scalar_025); } _mm_storeu_ps(out_ptr, line00); out_ptr += 4; } line0 += remain_w * 4; line1 = line0 + inw * 4; for (int i = 0; i < looph; i++) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); sum = _mm_add_ps(line00, line10); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_05); } else { sum = _mm_mul_ps(sum, scalar_025); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; line0 += 4; line1 += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); sum0 = _mm_add_ps(line00, line01); sum1 = _mm_add_ps(line10, line11); sum = _mm_add_ps(sum0, sum1); sum = _mm_mul_ps(sum, scalar_025); _mm_storeu_ps(out_ptr, sum); out_ptr += 4; line0 += 8; line1 += 8; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); sum = _mm_add_ps(line00, line10); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_05); } else { sum = _mm_mul_ps(sum, scalar_025); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; } if (inh % 2 == 0) { line00 = _mm_loadu_ps(line0); if (is_caffe == 1) { line00 = _mm_mul_ps(line00, scalar_025); } _mm_storeu_ps(out_ptr, line00); out_ptr += 4; line0 += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum = _mm_add_ps(line00, line01); if (is_caffe == 0) { sum0 = _mm_mul_ps(sum0, scalar_05); } else { sum0 = _mm_mul_ps(sum0, scalar_025); } _mm_storeu_ps(out_ptr, sum); line0 += 8; out_ptr += 4; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); if (is_caffe == 1) { line00 = _mm_mul_ps(line00, scalar_025); } _mm_storeu_ps(out_ptr, line00); out_ptr += 4; } } } static void max_2x2s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } int loopw = (inw - 1) >> 1; int looph = (inh - 1) >> 1; int remain_w = inw - outw * 2; if (inw % 2 == 0) { remain_w = 1; } else { remain_w = 0; } const float* line0 = input; const float* line1; float* out_ptr = output; __m128 line00; __m128 line01; __m128 line10; __m128 line11; __m128 max0; __m128 max1; __m128 max; line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); line0 += 4; out_ptr += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max0 = _mm_max_ps(line00, line01); _mm_storeu_ps(out_ptr, max0); out_ptr += 4; line0 += 8; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); out_ptr += 4; } line0 += remain_w * 4; line1 = line0 + inw * 4; for (int i = 0; i < looph; i++) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); max = _mm_max_ps(line00, line10); _mm_storeu_ps(out_ptr, max); out_ptr += 4; line0 += 4; line1 += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max = _mm_max_ps(max0, max1); _mm_storeu_ps(out_ptr, max); out_ptr += 4; line0 += 8; line1 += 8; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); max = _mm_max_ps(line00, line10); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; } if (inh % 2 == 0) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); out_ptr += 4; line0 += 4; for (int i = 0; i < loopw; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max = _mm_max_ps(line00, line01); _mm_storeu_ps(out_ptr, max); line0 += 8; out_ptr += 4; } if (inw % 2 == 0) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); out_ptr += 4; } } } static void avg_2x2s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } int block_w = outw >> 2; int remain_w = inw - outw * 2; const float* line0 = input; const float* line1 = input + inw * 4; float* out_ptr = output; __m128 scalar_025 = _mm_set1_ps(0.25f); __m128 scalar_05 = _mm_set1_ps(0.5f); __m128 line00; __m128 line01; __m128 line10; __m128 line11; __m128 add0; __m128 add1; __m128 add; for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); add0 = _mm_add_ps(line00, line01); add1 = _mm_add_ps(line10, line11); add = _mm_add_ps(add0, add1); add = _mm_mul_ps(add, scalar_025); _mm_storeu_ps(out_ptr, add); line0 += 8; line1 += 8; out_ptr += 4; } if (pad_w1 > 0) { add = _mm_add_ps(line00, line10); add = _mm_mul_ps(add, scalar_05); _mm_storeu_ps(out_ptr, add); } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; } if (pad_h1 > 0) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); add0 = _mm_add_ps(line00, line01); add0 = _mm_mul_ps(add0, scalar_05); _mm_storeu_ps(out_ptr, add0); line0 += 8; out_ptr += 4; } if (pad_w1 > 0) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); } } } static void max_2x2s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { int in_hw = inw * inh; int out_hw = outh * outw; if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } int block_w = outw >> 2; int remain_w = inw - outw * 2; const float* line0 = input; const float* line1 = input + inw * 4; float* out_ptr = output; __m128 line00; __m128 line01; __m128 line10; __m128 line11; __m128 max0; __m128 max1; __m128 max; for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max = _mm_max_ps(max0, max1); _mm_storeu_ps(out_ptr, max); line0 += 8; line1 += 8; out_ptr += 4; } if (pad_w1 > 0) { max = _mm_max_ps(line00, line10); _mm_storeu_ps(out_ptr, max); } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; } if (pad_h1 > 0) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max0 = _mm_max_ps(line00, line01); _mm_storeu_ps(out_ptr, max0); line0 += 8; out_ptr += 4; } if (pad_w1 > 0) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); } } } static void max_3x3s1_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { int mid_h = inh - 2; int mid_w = inw - 2; const float* line1 = input; const float* line2 = input + inw * 4; float* out_ptr = output; __m128 line10 = _mm_loadu_ps(line1); __m128 line11 = _mm_loadu_ps(line1 + 4); __m128 line20 = _mm_loadu_ps(line2); __m128 line21 = _mm_loadu_ps(line2 + 4); __m128 max1 = _mm_max_ps(line10, line20); __m128 max2 = _mm_max_ps(line11, line21); __m128 max12 = _mm_max_ps(max1, max2); _mm_storeu_ps(out_ptr, max12); out_ptr += 4; // h begin center----[line1+=1]---------------------------------- // for (int j = 0; j < mid_w; j++) // { // float max1 = arm64_max(arm64_max(line1[0], line1[1]), line1[2]); // float max2 = arm64_max(arm64_max(line2[0], line2[1]), line2[2]); // *out_ptr = arm64_max(max2, max1); // out_ptr++; // line1 += 1; // line2 += 1; // } __m128 line12; __m128 line22; __m128 max; for (int j = 0; j < mid_w; j++) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max12 = _mm_max_ps(_mm_max_ps(line10, line20), _mm_max_ps(line11, line21)); line12 = _mm_loadu_ps(line1 + 8); line22 = _mm_loadu_ps(line2 + 8); max = _mm_max_ps(line12, line22); _mm_storeu_ps(out_ptr, _mm_max_ps(max12, max)); out_ptr += 4; line1 += 4; line2 += 4; } // h begin right----[line1+=2]----------------------------------- // *out_ptr = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line2[0], line2[1])); // out_ptr++; // line1 += 2; // line2 += 2; line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max12 = _mm_max_ps(_mm_max_ps(line10, line20), _mm_max_ps(line11, line21)); _mm_storeu_ps(out_ptr, max12); out_ptr += 4; line1 += 8; line2 += 8; // const float* line0 = input + c * in_hw; // for (int i = 0; i < mid_h; i++) // { // // left // float max0 = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line2[0], line2[1])); // *out_ptr = arm64_max(arm64_max(line0[0], line0[1]), max0); // out_ptr++; // // mid // for (int j = 0; j < mid_w; j++) // { // float max0 = arm64_max(arm64_max(line0[0], line0[1]), line0[2]); // float max1 = arm64_max(arm64_max(line1[0], line1[1]), line1[2]); // float max2 = arm64_max(arm64_max(line2[0], line2[1]), line2[2]); // *out_ptr = arm64_max(arm64_max(max0, max1), max2); // out_ptr++; // line0 += 1; // line1 += 1; // line2 += 1; // } // max0 = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line2[0], line2[1])); // *out_ptr = arm64_max(arm64_max(line0[0], line0[1]), max0); // out_ptr++; // line0 += 2; // line1 += 2; // line2 += 2; // } const float* line0 = input; __m128 max0; __m128 line00; __m128 line01; __m128 line02; for (int i = 0; i < mid_h; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); max0 = _mm_max_ps(line00, line01); max = _mm_max_ps(_mm_max_ps(max0, max1), max2); _mm_storeu_ps(out_ptr, max); out_ptr += 4; for (int j = 0; j < mid_w; j++) { /* code */ // for (int j = 0; j < mid_w; j++) // { // float max0 = arm64_max(arm64_max(line0[0], line0[1]), line0[2]); // float max1 = arm64_max(arm64_max(line1[0], line1[1]), line1[2]); // float max2 = arm64_max(arm64_max(line2[0], line2[1]), line2[2]); // *out_ptr = arm64_max(arm64_max(max0, max1), max2); // out_ptr++; // line0 += 1; // line1 += 1; // line2 += 1; // } // max0 = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line2[0], line2[1])); // *out_ptr = arm64_max(arm64_max(line0[0], line0[1]), max0); // out_ptr++; // line0 += 2; // line1 += 2; // line2 += 2; line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); max0 = _mm_max_ps(_mm_max_ps(line00, line01), line02); max1 = _mm_max_ps(_mm_max_ps(line10, line11), line12); max2 = _mm_max_ps(_mm_max_ps(line20, line21), line22); _mm_storeu_ps(out_ptr, _mm_max_ps(_mm_max_ps(max0, max1), max2)); out_ptr += 4; line0 += 4; line1 += 4; line2 += 4; } line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); _mm_storeu_ps(out_ptr, _mm_max_ps(_mm_max_ps(max0, max1), max2)); out_ptr += 4; line0 += 8; line1 += 8; line2 += 8; } // *out_ptr = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line0[0], line0[1])); // out_ptr++; // for (int j = 0; j < mid_w; j++) // { // float max0 = arm64_max(arm64_max(line0[0], line0[1]), line0[2]); // float max1 = arm64_max(arm64_max(line1[0], line1[1]), line1[2]); // *out_ptr = arm64_max(max0, max1); // out_ptr++; // line0 += 1; // line1 += 1; // } // *out_ptr = arm64_max(arm64_max(line1[0], line1[1]), arm64_max(line0[0], line0[1])); line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); _mm_storeu_ps(out_ptr, _mm_max_ps(max0, max1)); out_ptr += 4; for (int i = 0; i < mid_w; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line02, line12); _mm_storeu_ps(out_ptr, _mm_max_ps(_mm_max_ps(max0, max1), max2)); out_ptr += 4; line0 += 4; line1 += 4; } line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); _mm_storeu_ps(out_ptr, _mm_max_ps(max0, max1)); } static void max_3x3s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } const float* line0 = input; const float* line1 = input + inw * 4; const float* line2 = input + inw * 8; float* out_ptr = output; __m128 line00; __m128 line01; __m128 line02; __m128 line10; __m128 line11; __m128 line12; __m128 line20; __m128 line21; __m128 line22; __m128 max0; __m128 max1; __m128 max2; __m128 max; int remain_w = inw - 2 * outw; for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); max0 = _mm_max_ps(_mm_max_ps(line00, line01), line02); max1 = _mm_max_ps(_mm_max_ps(line10, line11), line12); max2 = _mm_max_ps(_mm_max_ps(line20, line21), line22); _mm_storeu_ps(out_ptr, _mm_max_ps(_mm_max_ps(max0, max1), max2)); line0 += 8; line1 += 8; line2 += 8; out_ptr += 4; } if (pad_w1 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); _mm_storeu_ps(out_ptr, _mm_max_ps(_mm_max_ps(max0, max1), max2)); out_ptr += 4; } line0 += (remain_w + inw) * 4; line1 += (remain_w + inw) * 4; line2 += (remain_w + inw) * 4; } if (pad_h1 == 1) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); max0 = _mm_max_ps(_mm_max_ps(line00, line01), line02); max1 = _mm_max_ps(_mm_max_ps(line10, line11), line12); _mm_storeu_ps(out_ptr, _mm_max_ps(max0, max1)); line0 += 8; line1 += 8; line2 += 8; out_ptr += 4; } if (pad_w1 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); _mm_storeu_ps(out_ptr, _mm_max_ps(max0, max1)); } } } static void avg_3x3s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { int loopw = (inw - 2) >> 1; int looph = outh - 1; if (is_caffe == 1 || inw % 2 == 1) { outw--; } if (is_caffe == 1 || inh % 2 == 1) outh--; int remain_w = inw - loopw * 2 + 1; if (is_caffe == 1) { remain_w = 1; } __m128 scalar_011 = _mm_set1_ps(0.11111111f); __m128 scalar_016 = _mm_set1_ps(0.16666667f); __m128 scalar_033 = _mm_set1_ps(0.3333333f); __m128 scalar_025 = _mm_set1_ps(0.25f); const float* line1 = input; const float* line2 = input + inw * 4; float* out_ptr = output; __m128 line10 = _mm_loadu_ps(line1); __m128 line11 = _mm_loadu_ps(line1 + 4); __m128 line20 = _mm_loadu_ps(line2); __m128 line21 = _mm_loadu_ps(line2 + 4); __m128 sum1 = _mm_add_ps(line10, line11); __m128 sum2 = _mm_add_ps(line20, line21); __m128 sum = _mm_add_ps(sum1, sum2); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_025); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); line1 += 4; line2 += 4; out_ptr += 4; __m128 line12; __m128 line22; for (int j = 0; j < loopw; j++) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); sum1 = _mm_add_ps(line10, _mm_add_ps(line11, line12)); sum2 = _mm_add_ps(line20, _mm_add_ps(line21, line22)); sum = _mm_add_ps(sum1, sum2); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_016); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); line1 += 8; line2 += 8; out_ptr += 4; } if (inw % 2 == 1) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); sum1 = _mm_add_ps(line10, line11); sum2 = _mm_add_ps(line20, line21); sum = _mm_add_ps(sum1, sum2); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_025); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { // line10 = _mm_loadu_ps(line1); // line20 = _mm_loadu_ps(line2); // sum = _mm_add_ps(line10, line20); // sum = _mm_mul_ps(sum, scalar_016); // _mm_storeu_ps(out_ptr, sum); // out_ptr += 4; } line1 += remain_w * 4; line2 += remain_w * 4; const float* line0 = line1; line1 = line2; line2 = line1 + inw * 4; __m128 line00; __m128 line01; __m128 line02; __m128 sum0; for (int i = 0; i < looph; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); sum0 = _mm_add_ps(line00, line01); sum1 = _mm_add_ps(line10, line11); sum2 = _mm_add_ps(line20, line21); sum = _mm_add_ps(_mm_add_ps(sum0, sum1), sum2); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_016); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); line0 += 4; line1 += 4; line2 += 4; out_ptr += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); sum0 = _mm_add_ps(line00, _mm_add_ps(line01, line02)); sum1 = _mm_add_ps(line10, _mm_add_ps(line11, line12)); sum2 = _mm_add_ps(line20, _mm_add_ps(line21, line22)); sum = _mm_add_ps(sum0, _mm_add_ps(sum1, sum2)); sum = _mm_mul_ps(sum, scalar_011); _mm_storeu_ps(out_ptr, sum); out_ptr += 4; line0 += 8; line1 += 8; line2 += 8; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); sum1 = _mm_add_ps(line10, line11); sum2 = _mm_add_ps(line20, line21); sum0 = _mm_add_ps(line00, line01); sum = _mm_add_ps(sum0, _mm_add_ps(sum1, sum2)); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_016); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { // line00 = _mm_loadu_ps(line0); // line10 = _mm_loadu_ps(line1); // line20 = _mm_loadu_ps(line2); // sum = _mm_add_ps(line00, _mm_add_ps(line10, line20)); // sum = _mm_mul_ps(sum, scalar_016); // _mm_storeu_ps(out_ptr, sum); // out_ptr += 4; } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; line2 += (inw + remain_w) * 4; } if (inh % 2 == 1) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum1 = _mm_add_ps(line10, line11); sum0 = _mm_add_ps(line00, line01); sum = _mm_add_ps(sum0, sum1); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_025); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; line0 += 4; line1 += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); sum0 = _mm_add_ps(line00, _mm_add_ps(line01, line02)); sum1 = _mm_add_ps(line10, _mm_add_ps(line11, line12)); sum = _mm_add_ps(sum0, sum1); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_016); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); line0 += 8; line1 += 8; out_ptr += 4; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); sum0 = _mm_add_ps(line00, line01); sum1 = _mm_add_ps(line10, line11); sum = _mm_add_ps(sum0, sum1); if (is_caffe == 0) { sum = _mm_mul_ps(sum, scalar_025); } else { sum = _mm_mul_ps(sum, scalar_011); } _mm_storeu_ps(out_ptr, sum); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { // line00 = _mm_loadu_ps(line0); // line10 = _mm_loadu_ps(line1); // sum = _mm_add_ps(line00, line10); // sum = _mm_mul_ps(sum, scalar_016); // _mm_storeu_ps(out_ptr, sum); // out_ptr += 4; } } else if (inh % 2 == 0 && is_caffe == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum = _mm_add_ps(line00, line01); sum = _mm_mul_ps(sum, scalar_016); _mm_storeu_ps(out_ptr, sum); line0 += 4; out_ptr += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); sum = _mm_add_ps(line00, _mm_add_ps(line01, line02)); sum = _mm_mul_ps(sum, scalar_016); _mm_storeu_ps(out_ptr, sum); line0 += 8; out_ptr += 4; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum = _mm_add_ps(line00, line01); sum = _mm_mul_ps(sum, scalar_016); _mm_storeu_ps(out_ptr, sum); } else if (inw % 2 == 0) { // sum = _mm_loadu_ps(line0); // sum = _mm_mul_ps(sum, scalar_025); // _mm_storeu_ps(out_ptr, sum); } } } static void max_3x3s2_p1(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (is_caffe == 1 || inw % 2 == 1) { outw--; } if (is_caffe == 1 || inh % 2 == 1) outh--; int loopw = outw - 1; int looph = outh - 1; int remain_w = inw - outw * 2 + 1; const float* line1 = input; const float* line2 = input + inw * 4; float* out_ptr = output; __m128 line10 = _mm_loadu_ps(line1); __m128 line11 = _mm_loadu_ps(line1 + 4); __m128 line20 = _mm_loadu_ps(line2); __m128 line21 = _mm_loadu_ps(line2 + 4); __m128 max1 = _mm_max_ps(line10, line11); __m128 max2 = _mm_max_ps(line20, line21); __m128 max = _mm_max_ps(max1, max2); _mm_storeu_ps(out_ptr, max); line1 += 4; line2 += 4; out_ptr += 4; __m128 line12; __m128 line22; for (int j = 0; j < loopw; j++) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); max1 = _mm_max_ps(line10, _mm_max_ps(line11, line12)); max2 = _mm_max_ps(line20, _mm_max_ps(line21, line22)); max = _mm_max_ps(max1, max2); _mm_storeu_ps(out_ptr, max); line1 += 8; line2 += 8; out_ptr += 4; } if (inw % 2 == 1) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); max = _mm_max_ps(max1, max2); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { line10 = _mm_loadu_ps(line1); line20 = _mm_loadu_ps(line2); _mm_storeu_ps(out_ptr, _mm_max_ps(line10, line20)); out_ptr += 4; } line1 += remain_w * 4; line2 += remain_w * 4; const float* line0 = line1; line1 = line2; line2 = line1 + inw * 4; __m128 line00; __m128 line01; __m128 line02; __m128 max0; for (int i = 0; i < looph; i++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); max = _mm_max_ps(_mm_max_ps(max0, max1), max2); _mm_storeu_ps(out_ptr, max); line0 += 4; line1 += 4; line2 += 4; out_ptr += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); max0 = _mm_max_ps(line00, _mm_max_ps(line01, line02)); max1 = _mm_max_ps(line10, _mm_max_ps(line11, line12)); max2 = _mm_max_ps(line20, _mm_max_ps(line21, line22)); max = _mm_max_ps(max0, _mm_max_ps(max1, max2)); _mm_storeu_ps(out_ptr, max); out_ptr += 4; line0 += 8; line1 += 8; line2 += 8; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); max1 = _mm_max_ps(line10, line11); max2 = _mm_max_ps(line20, line21); max0 = _mm_max_ps(line00, line01); max = _mm_max_ps(max0, _mm_max_ps(max1, max2)); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); line20 = _mm_loadu_ps(line2); max = _mm_max_ps(line00, _mm_max_ps(line10, line20)); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } line0 += (inw + remain_w) * 4; line1 += (inw + remain_w) * 4; line2 += (inw + remain_w) * 4; } if (inh % 2 == 1) { line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max1 = _mm_max_ps(line10, line11); max0 = _mm_max_ps(line00, line01); max = _mm_max_ps(max0, max1); _mm_storeu_ps(out_ptr, max); out_ptr += 4; line0 += 4; line1 += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); max0 = _mm_max_ps(line00, _mm_max_ps(line01, line02)); max1 = _mm_max_ps(line10, _mm_max_ps(line11, line12)); max = _mm_max_ps(max0, max1); _mm_storeu_ps(out_ptr, max); line0 += 8; line1 += 8; out_ptr += 4; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); max0 = _mm_max_ps(line00, line01); max1 = _mm_max_ps(line10, line11); max = _mm_max_ps(max0, max1); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } else if (inw % 2 == 0 && is_caffe == 1) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); max = _mm_max_ps(line00, line10); _mm_storeu_ps(out_ptr, max); out_ptr += 4; } } else if (inh % 2 == 0 && is_caffe == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max = _mm_max_ps(line00, line01); _mm_storeu_ps(out_ptr, max); line0 += 4; out_ptr += 4; for (int j = 0; j < loopw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); max = _mm_max_ps(line00, _mm_max_ps(line01, line02)); _mm_storeu_ps(out_ptr, max); line0 += 8; out_ptr += 4; } if (inw % 2 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); max = _mm_max_ps(line00, line01); _mm_storeu_ps(out_ptr, max); } else if (inw % 2 == 0) { max = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, max); } } } static void avg_3x3s2(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { if (pad_w1 > 0) { outw--; } if (pad_h1 > 0) { outh--; } const float* line0 = input; const float* line1 = input + inw * 4; const float* line2 = input + inw * 8; float* out_ptr = output; __m128 scalar_011 = _mm_set1_ps(0.11111111f); __m128 scalar_016 = _mm_set1_ps(0.16666667f); __m128 scalar_025 = _mm_set1_ps(0.25f); __m128 scalar_05 = _mm_set1_ps(0.5f); __m128 scalar_033 = _mm_set1_ps(0.33333333f); __m128 line00; __m128 line01; __m128 line02; __m128 line10; __m128 line11; __m128 line12; __m128 line20; __m128 line21; __m128 line22; __m128 sum0; __m128 sum1; __m128 sum2; __m128 sum; int remain_w = inw - 2 * outw; for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); line22 = _mm_loadu_ps(line2 + 8); sum0 = _mm_add_ps(_mm_add_ps(line00, line01), line02); sum1 = _mm_add_ps(_mm_add_ps(line10, line11), line12); sum2 = _mm_add_ps(_mm_add_ps(line20, line21), line22); sum = _mm_add_ps(_mm_add_ps(sum0, sum1), sum2); sum = _mm_mul_ps(sum, scalar_011); _mm_storeu_ps(out_ptr, sum); line0 += 8; line1 += 8; line2 += 8; out_ptr += 4; } if (pad_w1 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line20 = _mm_loadu_ps(line2); line21 = _mm_loadu_ps(line2 + 4); sum0 = _mm_add_ps(line00, line01); sum1 = _mm_add_ps(line10, line11); sum2 = _mm_add_ps(line20, line21); sum = _mm_add_ps(_mm_add_ps(sum0, sum1), sum2); sum = _mm_mul_ps(sum, scalar_016); _mm_storeu_ps(out_ptr, sum); out_ptr += 4; } line0 += (remain_w + inw) * 4; line1 += (remain_w + inw) * 4; line2 += (remain_w + inw) * 4; } if (pad_h1 == 1) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); line12 = _mm_loadu_ps(line1 + 8); sum0 = _mm_add_ps(_mm_add_ps(line00, line01), line02); sum1 = _mm_add_ps(_mm_add_ps(line10, line11), line12); sum = _mm_add_ps(sum0, sum1); sum = _mm_mul_ps(sum, scalar_016); _mm_storeu_ps(out_ptr, sum); line0 += 8; line1 += 8; out_ptr += 4; } if (pad_w1 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line10 = _mm_loadu_ps(line1); line11 = _mm_loadu_ps(line1 + 4); sum0 = _mm_add_ps(line00, line01); sum1 = _mm_add_ps(line10, line11); sum = _mm_add_ps(sum0, sum1); sum = _mm_mul_ps(sum, scalar_025); _mm_storeu_ps(out_ptr, sum); } else if (pad_w1 == 2) { line00 = _mm_loadu_ps(line0); line10 = _mm_loadu_ps(line1); sum = _mm_add_ps(line00, line10); sum = _mm_mul_ps(sum, scalar_05); _mm_storeu_ps(out_ptr, sum); } } else if (pad_h1 == 2) { for (int j = 0; j < outw; j++) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); line02 = _mm_loadu_ps(line0 + 8); sum0 = _mm_add_ps(_mm_add_ps(line00, line01), line02); sum0 = _mm_mul_ps(sum0, scalar_033); _mm_storeu_ps(out_ptr, sum0); line0 += 8; out_ptr += 4; } if (pad_w1 == 1) { line00 = _mm_loadu_ps(line0); line01 = _mm_loadu_ps(line0 + 4); sum0 = _mm_add_ps(line00, line01); sum0 = _mm_mul_ps(sum0, scalar_05); _mm_storeu_ps(out_ptr, sum0); } else if (pad_w1 == 2) { line00 = _mm_loadu_ps(line0); _mm_storeu_ps(out_ptr, line00); } } } static void avg_global(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { int in_hw = inw * inh; int block = in_hw >> 3; int tail = in_hw & ~7; for (int c = 0; c < inc; c++) { const float* line0 = input + c * in_hw; float* out_ptr = output + c; float sum = 0.f; for (int j = 0; j < block; j++) { __m128 p00 = _mm_loadu_ps(line0); __m128 p01 = _mm_loadu_ps(line0 + 4); p00 = _mm_add_ps(p00, p01); sum += (p00[0] + p00[1] + p00[2] + p00[3]); line0 += 8; } for (int j = tail; j < in_hw; j++) { sum += line0[0]; line0++; } *out_ptr = sum / in_hw; } } static void max_global(const float* input, float* output, int inc, int inh, int inw, int outh, int outw, int k_h, int k_w, int s_h, int s_w, int pad_h0, int pad_w0, int pad_h1, int pad_w1, int is_caffe) { int in_hw = inw * inh; int block = in_hw >> 3; int tail = in_hw & ~7; for (int c = 0; c < inc; c++) { const float* line0 = input + c * in_hw; float* out_ptr = output + c; __m128 p00 = _mm_loadu_ps(line0); __m128 res = p00; for (int j = 0; j < block; j++) { __m128 p00 = _mm_loadu_ps(line0); __m128 p01 = _mm_loadu_ps(line0 + 4); __m128 max0 = _mm_max_ps(p00, p01); res = _mm_max_ps(res, max0); line0 += 8; } float max_ = max(max(res[0], res[1]), max(res[2], res[3])); for (int j = tail; j < in_hw; j++) { max_ = max(max_, line0[0]); line0++; } *out_ptr = max_; } } int pooling_kernel_perf_prerun(struct ir_tensor* input, struct ir_tensor* out, struct pool_param* param) { int pool_size = POOL_GENERIC; /* global pooling */ if (param->global) { if (param->pool_method == POOL_AVG) param->funct = ( pooling_kernel_t )avg_global; else if (param->pool_method == POOL_MAX) param->funct = ( pooling_kernel_t )max_global; assert(param->funct != NULL); return 0; } /* general pooling */ if (param->stride_h == 2 && param->stride_w == 2) { if (param->kernel_h == 2 && param->kernel_w == 2) pool_size = POOL_K2S2; else if (param->kernel_h == 3 && param->kernel_w == 3) pool_size = POOL_K3S2; } else if (param->stride_h == 1 && param->stride_w == 1) { if (param->kernel_h == 3 && param->kernel_w == 3) pool_size = POOL_K3S1; } int pool_method; // 0:max 1:avg int kernel_h; int kernel_w; int stride_h; int stride_w; int pad_h0; int pad_h1; int pad_w0; int pad_w1; int global; // 0:general 1:global int caffe_flavor; /* general max pooling, k2s2, k2k2p1, k3s1p1, k3s2, k3s2p1 */ if (param->pool_method == POOL_MAX) { if ((param->pad_h0 == param->pad_w0) && (param->pad_h1 == param->pad_w1)) { if (param->pad_h0 == 0) { if (pool_size == POOL_K2S2) { param->funct = ( pooling_kernel_t )max_2x2s2; } else if (pool_size == POOL_K3S2) { param->funct = ( pooling_kernel_t )max_3x3s2; } } else if (param->pad_h0 == 1) { if (pool_size == POOL_K2S2) { param->funct = ( pooling_kernel_t )max_2x2s2_p1; } else if (pool_size == POOL_K3S2) { param->funct = ( pooling_kernel_t )max_3x3s2_p1; } else if (pool_size == POOL_K3S1) { param->funct = ( pooling_kernel_t )max_3x3s1_p1; } } } if (param->funct != NULL) return 0; else { fprintf(stderr, "perf general max pooling func not be find\n"); return -1; } } /* general avg pooling, k2s2, k2s2p1, k3s2, k3s2p1 */ if (param->pool_method == POOL_AVG) { if ((param->pad_h0 == param->pad_w0) && (param->pad_h1 == param->pad_w1)) { if (param->pad_h0 == 0 && param->pad_h1 == 0) { if (pool_size == POOL_K2S2) { param->funct = ( pooling_kernel_t )avg_2x2s2; } else if (pool_size == POOL_K3S2) { param->funct = ( pooling_kernel_t )avg_3x3s2; } } else if (param->pad_h0 == 1 && param->pad_h1 == 1) { if (pool_size == POOL_K2S2) { param->funct = ( pooling_kernel_t )avg_2x2s2_p1; } else if (pool_size == POOL_K3S2) { param->funct = ( pooling_kernel_t )avg_3x3s2_p1; } } } if (param->funct != NULL) return 0; else { fprintf(stderr, "perf general avg pooling func not be find\n"); return -1; } } fprintf(stderr, "perf pooling func not be find\n"); return -1; } #define PACK4 4 static void pack4(float* input, float* input_buffer, int in_h, int in_w) { for (size_t i = 0; i < in_h; i++) { for (int j = 0; j < in_w; j++) { for (int c = 0; c < PACK4; c++) { input_buffer[i * in_w * PACK4 + j * PACK4 + c] = input[c * in_w * in_h + i * in_w + j]; } } } } static void unpack4(float* output_buffer, float* output, int out_h, int out_w) { for (size_t i = 0; i < PACK4; i++) { for (size_t j = 0; j < out_h; j++) { for (size_t k = 0; k < out_w; k++) { output[i * out_h * out_w + j * out_w + k] = output_buffer[j * out_w * PACK4 + k * PACK4 + i]; } } } } int pooling_kernel_perf_run(struct ir_tensor* input, struct ir_tensor* output, struct pool_param* param, int num_thread) { // fprintf(stderr, "perf pooling_kernel_run\n"); int is_caffe = param->caffe_flavor; pooling_kernel_t kernel = (pooling_kernel_t)(param->funct); int batch = input->dims[0]; int c = input->dims[1]; int in_h = input->dims[2]; int in_w = input->dims[3]; int out_h = output->dims[2]; int out_w = output->dims[3]; int img_size = c * in_h * in_w; int feature_size = c * out_h * out_w; if (param->global) { for (int n = 0; n < batch; n++) { void* input_frame = input->data + n * img_size * input->elem_size; void* output_frame = output->data + n * feature_size * output->elem_size; #pragma omp parallel for num_threads(num_thread) for (int ch = 0; ch < c; ch++) { void* cur_input = input_frame + ch * in_h * in_w * input->elem_size; void* cur_output = output_frame + ch * out_h * out_w * output->elem_size; kernel(cur_input, cur_output, 1, in_h, in_w, out_h, out_w, param->kernel_h, param->kernel_w, param->stride_h, param->stride_w, param->pad_h0, param->pad_w0, param->pad_h1, param->pad_w1, is_caffe); } } } else { int packc4 = c >> 2; float* input_buffer = ( float* )calloc(sizeof(float), PACK4 * in_h * in_w); float* output_buffer = ( float* )calloc(sizeof(float), PACK4 * out_h * out_w); for (int n = 0; n < batch; n++) { for (int pck = 0; pck < packc4; pck++) { float* input_cur = ( float* )input->data + n * img_size + pck * PACK4 * in_h * in_w; float* output_cur = ( float* )output->data + n * feature_size + pck * PACK4 * out_h * out_w; pack4(input_cur, input_buffer, in_h, in_w); kernel(input_buffer, output_buffer, c, in_h, in_w, out_h, out_w, param->kernel_h, param->kernel_w, param->stride_h, param->stride_w, param->pad_h0, param->pad_w0, param->pad_h1, param->pad_w1, is_caffe); unpack4(output_buffer, output_cur, out_h, out_w); } } free(input_buffer); free(output_buffer); } return 0; }
data.h
/*! * Copyright (c) 2015 by Contributors * \file data.h * \brief The input data structure of xgboost. * \author Tianqi Chen */ #ifndef XGBOOST_DATA_H_ #define XGBOOST_DATA_H_ #include <dmlc/base.h> #include <dmlc/data.h> #include <rabit/rabit.h> #include <xgboost/base.h> #include <xgboost/span.h> #include <xgboost/host_device_vector.h> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <utility> #include <vector> namespace xgboost { // forward declare dmatrix. class DMatrix; /*! \brief data type accepted by xgboost interface */ enum class DataType : uint8_t { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4 }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of data fields in MetaInfo */ static constexpr uint64_t kNumField = 7; /*! \brief number of rows in the data */ uint64_t num_row_{0}; /*! \brief number of columns in the data */ uint64_t num_col_{0}; /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_group_t> group_ptr_; /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; /*! * \brief initialized margins, * if specified, xgboost will start from this init margin * can be used to specify initial prediction to boost from. */ HostDeviceVector<bst_float> base_margin_; /*! \brief default constructor */ MetaInfo() = default; MetaInfo& operator=(MetaInfo const& that) { this->num_row_ = that.num_row_; this->num_col_ = that.num_col_; this->num_nonzero_ = that.num_nonzero_; this->labels_.Resize(that.labels_.Size()); this->labels_.Copy(that.labels_); this->group_ptr_ = that.group_ptr_; this->weights_.Resize(that.weights_.Size()); this->weights_.Copy(that.weights_); this->base_margin_.Resize(that.base_margin_.Size()); this->base_margin_.Copy(that.base_margin_); return *this; } /*! * \brief Get weight of each instances. * \param i Instance index. * \return The weight. */ inline bst_float GetWeight(size_t i) const { return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f; } /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */ inline const std::vector<size_t>& LabelAbsSort() const { if (label_order_cache_.size() == labels_.Size()) { return label_order_cache_; } label_order_cache_.resize(labels_.Size()); std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0); const auto& l = labels_.HostVector(); XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(), [&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);}); return label_order_cache_; } /*! \brief clear all the information */ void Clear(); /*! * \brief Load the Meta info from binary stream. * \param fi The input stream */ void LoadBinary(dmlc::Stream* fi); /*! * \brief Save the Meta info to binary stream * \param fo The output stream. */ void SaveBinary(dmlc::Stream* fo) const; /*! * \brief Set information in the meta info. * \param key The key of the information. * \param dptr The data pointer of the source array. * \param dtype The type of the source data. * \param num Number of elements in the source array. */ void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num); /*! * \brief Set information in the meta info with array interface. * \param key The key of the information. * \param interface_str String representation of json format array interface. * * [ column_0, column_1, ... column_n ] * * Right now only 1 column is permitted. */ void SetInfo(const char* key, std::string const& interface_str); private: /*! \brief argsort of labels */ mutable std::vector<size_t> label_order_cache_; }; /*! \brief Element from a sparse vector */ struct Entry { /*! \brief feature index */ bst_feature_t index; /*! \brief feature value */ bst_float fvalue; /*! \brief default constructor */ Entry() = default; /*! * \brief constructor with index and value * \param index The feature or row index. * \param fvalue The feature value. */ XGBOOST_DEVICE Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {} /*! \brief reversely compare feature values */ inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; } inline bool operator==(const Entry& other) const { return (this->index == other.index && this->fvalue == other.fvalue); } }; /*! * \brief Parameters for constructing batches. */ struct BatchParam { /*! \brief The GPU device to use. */ int gpu_id; /*! \brief Maximum number of bins per feature for histograms. */ int max_bin; /*! \brief Number of rows in a GPU batch, used for finding quantiles on GPU. */ int gpu_batch_nrows; /*! \brief Page size for external memory mode. */ size_t gpu_page_size; inline bool operator!=(const BatchParam& other) const { return gpu_id != other.gpu_id || max_bin != other.max_bin || gpu_batch_nrows != other.gpu_batch_nrows || gpu_page_size != other.gpu_page_size; } }; /*! * \brief In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<bst_row_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid{}; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; /*! \brief get i-th row from the batch */ inline Inst operator[](size_t i) const { const auto& data_vec = data.HostVector(); const auto& offset_vec = offset.HostVector(); size_t size; // in distributed mode, some partitions may not get any instance for a feature. Therefore // we should set the size as zero if (rabit::IsDistributed() && i + 1 >= offset_vec.size()) { size = 0; } else { size = offset_vec[i + 1] - offset_vec[i]; } return {data_vec.data() + offset_vec[i], static_cast<Inst::index_type>(size)}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return Number of instances in the page. */ inline size_t Size() const { return offset.Size() == 0 ? 0 : offset.Size() - 1; } /*! \return estimation of memory cost of this page */ inline size_t MemCostBytes() const { return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry); } /*! \brief clear the page */ inline void Clear() { base_rowid = 0; auto& offset_vec = offset.HostVector(); offset_vec.clear(); offset_vec.push_back(0); data.HostVector().clear(); } /*! \brief Set the base row id for this page. */ inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; } SparsePage GetTranspose(int num_columns) const; void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); #pragma omp parallel for default(none) shared(ncol) schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) { std::sort( this->data.HostVector().begin() + this->offset.HostVector()[i], this->data.HostVector().begin() + this->offset.HostVector()[i + 1], Entry::CmpValue); } } } /*! * \brief Push row block into the page. * \param batch the row batch. */ void Push(const dmlc::RowBlock<uint32_t>& batch); /** * \brief Pushes external data batch onto this page * * \tparam AdapterBatchT * \param batch * \param missing * \param nthread * * \return The maximum number of columns encountered in this input batch. Useful when pushing many adapter batches to work out the total number of columns. */ template <typename AdapterBatchT> uint64_t Push(const AdapterBatchT& batch, float missing, int nthread); /*! * \brief Push a sparse page * \param batch the row page */ void Push(const SparsePage &batch); /*! * \brief Push a SparsePage stored in CSC format * \param batch The row batch to be pushed */ void PushCSC(const SparsePage& batch); }; class CSCPage: public SparsePage { public: CSCPage() : SparsePage() {} explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class SortedCSCPage : public SparsePage { public: SortedCSCPage() : SparsePage() {} explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class EllpackPageImpl; /*! * \brief A page stored in ELLPACK format. * * This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid * including CUDA-specific implementation details in the header. */ class EllpackPage { public: /*! * \brief Default constructor. * * This is used in the external memory case. An empty ELLPACK page is constructed with its content * set later by the reader. */ EllpackPage(); /*! * \brief Constructor from an existing DMatrix. * * This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix * in CSR format. */ explicit EllpackPage(DMatrix* dmat, const BatchParam& param); /*! \brief Destructor. */ ~EllpackPage(); /*! \return Number of instances in the page. */ size_t Size() const; /*! \brief Set the base row id for this page. */ void SetBaseRowId(size_t row_id); const EllpackPageImpl* Impl() const { return impl_.get(); } EllpackPageImpl* Impl() { return impl_.get(); } private: std::unique_ptr<EllpackPageImpl> impl_; }; template<typename T> class BatchIteratorImpl { public: virtual ~BatchIteratorImpl() = default; virtual T& operator*() = 0; virtual const T& operator*() const = 0; virtual void operator++() = 0; virtual bool AtEnd() const = 0; }; template<typename T> class BatchIterator { public: using iterator_category = std::forward_iterator_tag; explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); } void operator++() { CHECK(impl_ != nullptr); ++(*impl_); } T& operator*() { CHECK(impl_ != nullptr); return *(*impl_); } const T& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator& rhs) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } private: std::shared_ptr<BatchIteratorImpl<T>> impl_; }; template<typename T> class BatchSet { public: explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(begin_iter) {} BatchIterator<T> begin() { return begin_iter_; } BatchIterator<T> end() { return BatchIterator<T>(nullptr); } private: BatchIterator<T> begin_iter_; }; /*! * \brief This is data structure that user can pass to DMatrix::Create * to create a DMatrix for training, user can create this data structure * for customized Data Loading on single machine. * * On distributed setting, usually an customized dmlc::Parser is needed instead. */ template<typename T> class DataSource : public dmlc::DataIter<T> { public: /*! * \brief Meta information about the dataset * The subclass need to be able to load this correctly from data. */ MetaInfo info; }; /*! * \brief Internal data structured used by XGBoost during training. * There are two ways to create a customized DMatrix that reads in user defined-format. * * - Provide a dmlc::Parser and pass into the DMatrix::Create * - Alternatively, if data can be represented by an URL, define a new dmlc::Parser and register by * DMLC_REGISTER_DATA_PARSER; * - This works best for user defined data input source, such as data-base, filesystem. * - Provide a DataSource, that can be passed to DMatrix::Create * This can be used to re-use inmemory data structure into DMatrix. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /** * \brief Gets batches. Use range based for loop over BatchSet to access individual batches. */ template<typename T> BatchSet<T> GetBatches(const BatchParam& param = {}); // the following are column meta data, should be able to answer them fast. /*! \return Whether the data columns single column block. */ virtual bool SingleColBlock() const = 0; /*! \brief get column density */ virtual float GetColDensity(size_t cidx) = 0; /*! \brief virtual destructor */ virtual ~DMatrix() = default; /*! \brief Whether the matrix is dense. */ bool IsDense() const { return Info().num_nonzero_ == Info().num_row_ * Info().num_col_; } /*! * \brief Load DMatrix from URI. * \param uri The URI of input. * \param silent Whether print information during loading. * \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode. * \param file_format The format type of the file, used for dmlc::Parser::Create. * By default "auto" will be able to load in both local binary file. * \param page_size Page size for external memory. * \return The created DMatrix. */ static DMatrix* Load(const std::string& uri, bool silent, bool load_row_split, const std::string& file_format = "auto", size_t page_size = kPageSize); /** * \brief Creates a new DMatrix from an external data adapter. * * \tparam AdapterT Type of the adapter. * \param [in,out] adapter View onto an external data. * \param missing Values to count as missing. * \param nthread Number of threads for construction. * \param cache_prefix (Optional) The cache prefix for external memory. * \param page_size (Optional) Size of the page. * * \return a Created DMatrix. */ template <typename AdapterT> static DMatrix* Create(AdapterT* adapter, float missing, int nthread, const std::string& cache_prefix = "", size_t page_size = kPageSize); /*! \brief page size 32 MB */ static const size_t kPageSize = 32UL << 20UL; protected: virtual BatchSet<SparsePage> GetRowBatches() = 0; virtual BatchSet<CSCPage> GetColumnBatches() = 0; virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0; virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0; }; template<> inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) { return GetRowBatches(); } template<> inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) { return GetColumnBatches(); } template<> inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) { return GetSortedColumnBatches(); } template<> inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) { return GetEllpackBatches(param); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); } #endif // XGBOOST_DATA_H_
globalsolver.h
#ifndef GLOBALSOLVER_H #define GLOBALSOLVER_H #include "solver.h" #include <memory> #include <vector> template <class T> class GlobalSolver : public Solver<T> { public: GlobalSolver(int numberOfAgents, std::shared_ptr<Problem<T>> prob) : Solver<T>(prob) { if (numberOfAgents % 2 != 0) numberOfAgents += 1; this->numberOfAgents = numberOfAgents; switch (prob->getStrategy()) { case OptimizationStrategy::MINIMIZE: this->globalBestFitness = DBL_MAX; break; case OptimizationStrategy::MAXIMIZE: this->globalBestFitness = -DBL_MAX; std::cout << "global fitness initialized " << globalBestFitness << std::endl; break; } puts("Global solver instantiated"); } virtual void getOppositePoint(const std::vector<T> &variables, std::vector<T> &opposite) { #pragma omp critical if (typeid(T) != typeid(double)) { puts("You must override the getOppositePoint in the derived class"); exit(EXIT_FAILURE); } opposite = std::vector<T>(variables.size()); for (size_t i = 0; i < this->problem->getDimension(); i++) opposite[i] = this->getOppositeVariable(i, variables[i]); } virtual T getOppositeVariable(const int indexVar, const double currentValue) { if (typeid(T) == typeid(double)) { return this->problem->getLb()[indexVar] + this->problem->getUb()[indexVar] - currentValue; } else { puts("You must override the getOppositeVariable in the derived class"); exit(EXIT_FAILURE); } } protected: int numberOfAgents; std::vector<double> globalBest; double globalBestFitness; double timeLastImprovement; std::shared_ptr<Solution<T>> bestSolution; bool oppositeLearning; double getAmountTimeSinceLastImprovement() { return utils::getCurrentTime() - timeLastImprovement; } bool updateGlobalBest(const std::vector<double> &individual, double fitness, bool printUpdate) { switch (this->problem->getStrategy()) { case OptimizationStrategy::MINIMIZE: if (fitness < globalBestFitness) { globalBest = std::vector<double>(individual); globalBestFitness = fitness; timeLastImprovement = utils::getCurrentTime(); if (printUpdate) utils::printValueAndTime(fitness, utils::getCurrentTime()); return true; } break; case OptimizationStrategy::MAXIMIZE: if (fitness > globalBestFitness) { globalBest = std::vector<double>(individual); globalBestFitness = fitness; timeLastImprovement = utils::getCurrentTime(); if (printUpdate) utils::printValueAndTime(fitness, utils::getCurrentTime()); return true; } break; } return false; } bool updateGlobalBest(const std::vector<double> &individual, double fitness, bool printUpdate, std::shared_ptr<Solution<T>> solution) { switch (this->problem->getStrategy()) { case OptimizationStrategy::MINIMIZE: if (fitness < globalBestFitness) { globalBest = std::vector<double>(individual); globalBestFitness = fitness; timeLastImprovement = utils::getCurrentTime(); bestSolution = solution; if (printUpdate) utils::printValueAndTime(fitness, utils::getCurrentTime()); return true; } break; case OptimizationStrategy::MAXIMIZE: if (fitness > globalBestFitness) { globalBest = std::vector<double>(individual); globalBestFitness = fitness; timeLastImprovement = utils::getCurrentTime(); bestSolution = solution; if (printUpdate) utils::printValueAndTime(fitness, utils::getCurrentTime()); return true; } break; } return false; } }; #endif // GLOBALSOLVER_H
ctl_scroll.c
/********************************************************************[libaroma]* * Copyright (C) 2011-2015 Ahmad Amarullah (http://amarullz.com/) * * 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. *______________________________________________________________________________ * * Filename : ctl_scroll.c * Description : scroll control * * + This is part of libaroma, an embedded ui toolkit. * + 12/02/15 - Author(s): Ahmad Amarullah * */ #ifndef __libaroma_ctl_scroll_c__ #define __libaroma_ctl_scroll_c__ #include <aroma_internal.h> #include "../ui/ui_internal.h" /* HANDLER */ dword _libaroma_ctl_scroll_msg(LIBAROMA_CONTROLP, LIBAROMA_MSGP); void _libaroma_ctl_scroll_draw (LIBAROMA_CONTROLP, LIBAROMA_CANVASP); void _libaroma_ctl_scroll_destroy(LIBAROMA_CONTROLP); byte _libaroma_ctl_scroll_thread(LIBAROMA_CONTROLP); static LIBAROMA_CONTROL_HANDLER _libaroma_ctl_scroll_handler={ message:_libaroma_ctl_scroll_msg, draw:_libaroma_ctl_scroll_draw, focus:NULL, destroy:_libaroma_ctl_scroll_destroy, thread:_libaroma_ctl_scroll_thread }; /* * SCROLL CONTROL BEHAVIOUR CONFIGURATIONS * */ /* max cache height size */ #define _LIBAROMA_CTL_SCROLL_MAX_CACHE (libaroma_fb()->h * 10) /* size of touch handle */ #define _LIBAROMA_CTL_SCROLL_HANDLE_DP 36 /* wait ms before it send down event to client */ #define _LIBAROMA_CTL_SCROLL_TOUCH_CLIENT_WAIT 120 /* minimal touch y-move in dp if client request touch message */ #define _LIBAROMA_CTL_SCROLL_MIN_ALOWSCROLL_DP 24 /* minimal touch y-move in dp if client doesn't request touch message */ #define _LIBAROMA_CTL_SCROLL_MIN_ALOWSCROLL_DP_NOITEM 5 /* #define LIBAROMA_CTL_SCROLL_WITH_MAX_CACHE 1 #define LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD 1 */ /* * Structure : __LIBAROMA_CTL_SCROLL * Typedef : _LIBAROMA_CTL_SCROLL, * _LIBAROMA_CTL_SCROLLP * Descriptions: button control internal structure */ typedef struct __LIBAROMA_CTL_SCROLL _LIBAROMA_CTL_SCROLL; typedef struct __LIBAROMA_CTL_SCROLL * _LIBAROMA_CTL_SCROLLP; struct __LIBAROMA_CTL_SCROLL{ /* drawing & canvas */ LIBAROMA_CANVASP client_canvas; word color_bg; byte flags; /* threads */ byte active; #ifdef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD LIBAROMA_THREAD cache_thread; #endif LIBAROMA_THREAD calc_thread; /* scrolling values */ int request_new_height; int scroll_y; int client_h; int max_scroll_y; int request_scroll_y; long scroll_tick; int scroll_state; /* cache values */ byte cache_state; byte move_state; int cache_y; int draw_y; int synced_y; long scroll_handle_time; /* touch event */ byte touched; byte handle_touched; byte allow_scroll; int touch_x; int touch_y; int touch_scroll_y; /* client touch event */ long client_touch_start; byte client_touched; /* overshoot */ byte ovs_bounce; long ovs_start; float ovs_state; float ovs_ustate; long ovs_ustart; int ovs_x; int ovs_y; /* fling items */ int bounce_velocity; int velocity; LIBAROMA_FLING fling; /* client data */ LIBAROMA_CTL_SCROLL_CLIENT client; LIBAROMA_MUTEX mutex; LIBAROMA_MUTEX fmutex; LIBAROMA_MUTEX blitmutex; LIBAROMA_COND_MUTEX cmutex; LIBAROMA_COND ccond; /* minscroll handler */ LIBAROMA_CTL_SCROLL_MINSCROLL_HANDLER minscroll_cb; int minscroll_y; }; /* * Function : _libaroma_ctl_scroll_client_msg * Return Value: dword * Descriptions: send client message */ dword _libaroma_ctl_scroll_client_msg( LIBAROMA_CONTROLP ctl, byte message, int x, int y ){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client.handler->message){ LIBAROMA_MSG msgc; libaroma_wm_compose( &msgc, LIBAROMA_CTL_SCROLL_MSG, NULL, message, 0 ); return me->client.handler->message( ctl, &me->client, &msgc, x, y ); } return 0; } /* End of _libaroma_ctl_scroll_client_msg */ /* * Function : _libaroma_ctl_scroll_updatecache * Return Value: byte * Descriptions: update cache drawing */ byte _libaroma_ctl_scroll_updatecache(LIBAROMA_CONTROLP ctl, int move_sz){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client_canvas==NULL){ return 0; } libaroma_mutex_lock(me->fmutex); int move_value=0; int cvhsz = (me->client_canvas->h / 2); if (move_sz<0){ /* draw top */ move_value = 0-cvhsz; if (move_value>move_sz){ move_value=move_sz; } if (me->draw_y+move_value<0){ move_value=0-me->draw_y; } } else if (move_sz>0){ /* draw bottom */ move_value = cvhsz; if (move_value<move_sz){ move_value=move_sz; } if (me->draw_y+move_value>me->max_scroll_y){ move_value=me->max_scroll_y-me->draw_y; } if (move_value<0){ move_value=0; } } if ((me->cache_state==10)||(me->cache_state==11)){ me->cache_state=0; int client_y=me->draw_y; /* force redraw all */ if (me->client.handler->draw!=NULL){ me->client.handler->draw( ctl, &me->client, me->client_canvas, 0,client_y,me->client_canvas->w,me->client_canvas->h ); } else{ libaroma_canvas_setcolor(me->client_canvas,me->color_bg,0xff); } me->cache_y=0; me->synced_y=-1; libaroma_mutex_unlock(me->fmutex); return 1; } me->cache_state=0; if (move_value!=0){ byte is_top = (move_value<0)?1:0; int cache_h = abs(move_value); int cache_y = me->cache_y+move_value; int client_y= me->draw_y+(is_top?move_value:me->client_canvas->h); if (cache_y<0){ cache_y = me->client_canvas->h + cache_y; } else if (cache_y>=me->client_canvas->h){ cache_y = cache_y-me->client_canvas->h; } /* redrawing client */ LIBAROMA_CANVASP redraw_canvas; int top_y=is_top?cache_y:cache_y-cache_h; int top_h=cache_h; int bottom_h=0; if (top_y<0){ top_h = abs(top_y); bottom_h = cache_h - top_h; top_y = me->client_canvas->h-top_h; } else if (top_y+top_h>me->client_canvas->h){ top_h = me->client_canvas->h - top_y; bottom_h = cache_h - top_h; } /* top section */ if (top_h>0){ redraw_canvas = libaroma_canvas_area( me->client_canvas, 0, top_y, me->client_canvas->w, top_h ); if (me->client.handler->draw){ me->client.handler->draw( ctl, &me->client, redraw_canvas, 0, client_y, redraw_canvas->w, redraw_canvas->h ); } else{ libaroma_canvas_setcolor(redraw_canvas,me->color_bg,0xff); } libaroma_canvas_free(redraw_canvas); } /* bottom section */ if (bottom_h>0){ redraw_canvas = libaroma_canvas_area( me->client_canvas, 0, 0, me->client_canvas->w, bottom_h ); if (me->client.handler->draw){ me->client.handler->draw( ctl, &me->client, redraw_canvas, 0, client_y+top_h, redraw_canvas->w, redraw_canvas->h ); } else{ libaroma_canvas_setcolor(redraw_canvas,me->color_bg,0xff); } libaroma_canvas_free(redraw_canvas); } /* update info */ me->cache_y=cache_y; me->draw_y+=move_value; me->synced_y=-1; libaroma_mutex_unlock(me->fmutex); return 1; } libaroma_mutex_unlock(me->fmutex); return 0; } /* End of _libaroma_ctl_scroll_updatecache */ /* * Function : _libaroma_ctl_scroll_check_update * Return Value: byte * Descriptions: check for cache update */ #ifdef LIBAROMA_CTL_SCROLL_WITH_MAX_CACHE byte _libaroma_ctl_scroll_check_update(LIBAROMA_CONTROLP ctl){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if ((me->client.handler)&&(me->client_canvas!=NULL)){ if ((me->cache_state)&&(me->cache_state!=10)){ int cvhsz = (me->client_canvas->h / 4); int draw_top = me->draw_y; int draw_bottom = draw_top+me->client_canvas->h; if (me->scroll_y<draw_top+me->cache_y){ _libaroma_ctl_scroll_updatecache(ctl,-cvhsz); return 1; } else if (me->scroll_y>draw_bottom+me->cache_y){ _libaroma_ctl_scroll_updatecache(ctl,cvhsz); return 1; } else if (me->move_state==1){ if ((me->scroll_y<draw_top+cvhsz)&&(draw_top>0)){ _libaroma_ctl_scroll_updatecache(ctl,-cvhsz); return 1; } } else if (me->move_state==2){ if ((me->scroll_y>draw_bottom-cvhsz)&&(draw_bottom<me->client_h)){ _libaroma_ctl_scroll_updatecache(ctl,cvhsz); return 1; } } } } return 0; } /* End of _libaroma_ctl_scroll_check_update */ #endif /* * Function : _libaroma_ctl_scroll_cache_thread * Return Value: static void * * Descriptions: background cache updater */ #ifdef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD static void * _libaroma_ctl_scroll_cache_thread(void * cookie){ LIBAROMA_CONTROLP ctl = (LIBAROMA_CONTROLP) cookie; /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); ALOGV("Start scroll updater thread"); while (me->active){ /* update new height */ if (me->client.handler){ if (me->request_new_height!=-1){ libaroma_ctl_scroll_set_height(ctl,me->request_new_height); libaroma_mutex_lock(me->fmutex); me->request_new_height=-1; libaroma_mutex_unlock(me->fmutex); } if (me->cache_state==10){ _libaroma_ctl_scroll_updatecache(ctl, 0); } #ifdef LIBAROMA_CTL_SCROLL_WITH_MAX_CACHE else if (me->client_canvas!=NULL){ if ((me->client_h>me->client_canvas->h)&&(me->request_new_height==-1)){ _libaroma_ctl_scroll_check_update(ctl); } } #endif } libaroma_sleep(1); } ALOGV("End scroll updater thread"); return NULL; } /* End of _libaroma_ctl_scroll_cache_thread */ #endif /* * Function : _libaroma_ctl_scroll_calc_thread * Return Value: static void * * Descriptions: background calculation updater */ static void * _libaroma_ctl_scroll_calc_thread(void * cookie){ LIBAROMA_CONTROLP ctl = (LIBAROMA_CONTROLP) cookie; /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); ALOGI("Start scroll calculation thread"); byte need_drawing = 0; while (me->active){ libaroma_cond_lock(&me->cmutex); libaroma_cond_wait(&me->ccond, &me->cmutex); libaroma_cond_unlock(&me->cmutex); if (!me->active){ break; } if (me->client.handler){ /* run client thread */ libaroma_mutex_lock(me->mutex); if ((me->client_touch_start!=0)&& (libaroma_tick()-me->client_touch_start> _LIBAROMA_CTL_SCROLL_TOUCH_CLIENT_WAIT)){ me->client_touch_start=0; /* send touch down message to client */ if (me->client.handler->message){ int client_x = me->touch_x; int client_y = me->touch_y + me->scroll_y; if (_libaroma_ctl_scroll_client_msg( ctl,LIBAROMA_CTL_SCROLL_MSG_TOUCH_DOWN, client_x, client_y )==LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW){ need_drawing=1; } me->client_touched=1; } } libaroma_mutex_unlock(me->mutex); /* client thread */ if (me->client.handler->thread!=NULL){ if (me->client.handler->thread(ctl,&me->client)){ need_drawing=1; } } /* drawing handler */ if (need_drawing){ me->synced_y=-1; need_drawing=0; } } } ALOGI("End scroll calculation thread"); return NULL; } /* End of _libaroma_ctl_scroll_calc_thread */ /* * Function : _libaroma_ctl_scroll_thread * Return Value: byte * Descriptions: control thread callback */ byte _libaroma_ctl_scroll_thread(LIBAROMA_CONTROLP ctl) { /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); byte need_drawing=0; if (me->client.handler){ libaroma_cond_lock(&me->cmutex); libaroma_cond_signal(&me->ccond); libaroma_cond_unlock(&me->cmutex); if (!me->active){ return 0; } #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel sections { #pragma omp section { #endif /* overshoot */ if (me->ovs_ustart>1){ float nowstate= libaroma_control_state(me->ovs_ustart, me->ovs_bounce==2?1000:400); if (nowstate<1){ if (nowstate!=me->ovs_ustate){ me->ovs_ustate=nowstate; need_drawing=1; } } if ((nowstate>=1)&&(me->ovs_ustate<1)){ me->ovs_state=0; me->ovs_start=0; me->ovs_ustart=0; me->ovs_ustate=0; need_drawing=1; } } else if ((me->ovs_start>0)||(me->ovs_state)){ float nowstate= libaroma_control_state(me->ovs_start,(me->ovs_bounce==1)?800:1600); if (nowstate<1){ if (nowstate!=me->ovs_state){ me->ovs_state=nowstate; need_drawing=1; } } if ((me->ovs_state<1)&&((nowstate>=1)|| ((nowstate>=0.2)&&(me->ovs_ustart==1)&&(me->ovs_state<1))) ){ me->ovs_state=0.5; me->ovs_ustart=libaroma_tick(); me->ovs_ustate=0; if (!me->ovs_bounce){ me->ovs_bounce=2; } need_drawing=1; } } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif /* fling handler */ if ((me->velocity!=0)&&(!me->touched)){ /* onfling */ me->velocity=(me->velocity*246)>>8; if ((abs(me->velocity)<256)||(me->touched)) { /* ended */ me->velocity = 0; need_drawing=1; } else{ /* still on fling */ int scroll_y = (me->velocity>>8) + me->scroll_y; if (scroll_y>=me->max_scroll_y){ scroll_y=me->max_scroll_y; if (me->scroll_y!=scroll_y){ me->bounce_velocity=MAX(-libaroma_dp(3840), MIN(libaroma_dp(3840),(me->velocity*153)>>8)); me->ovs_bounce=1; me->ovs_state=0; me->ovs_y=0; me->ovs_y=MIN(ctl->w*0.4,me->bounce_velocity>>4); me->ovs_ustate=0; me->ovs_ustart=1; me->ovs_start=libaroma_tick()-16; } me->velocity = 0; need_drawing=1; } if (scroll_y<=0){ scroll_y=0; if (me->scroll_y!=scroll_y){ me->bounce_velocity=MAX(-libaroma_dp(3840), MIN(libaroma_dp(3840),(me->velocity*153)>>8)); me->ovs_bounce=1; me->ovs_state=0; me->ovs_y=0; me->ovs_y=MAX(0-ctl->w*0.4,me->bounce_velocity>>4); me->ovs_ustate=0; me->ovs_ustart=1; me->ovs_start=libaroma_tick()-16; } me->velocity = 0; need_drawing=1; } if (scroll_y!=me->scroll_y){ libaroma_ctl_scroll_set_pos(ctl, scroll_y); } } } else if (me->request_scroll_y!=-1){ /* direct request */ if (me->request_scroll_y!=me->scroll_y){ int move_sz = ((me->request_scroll_y-me->scroll_y)*64)>>8; if (abs(move_sz)<2){ if (move_sz<0){ move_sz=-1; } else{ move_sz=1; } } int target_sz = me->scroll_y+move_sz; if (target_sz==me->request_scroll_y){ target_sz=me->request_scroll_y; me->request_scroll_y=-1; } libaroma_ctl_scroll_set_pos(ctl,target_sz); } } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif /* bounce handler */ if (me->bounce_velocity!=0){ /* bounce */ me->bounce_velocity=(me->bounce_velocity*153)>>8; if (abs(me->bounce_velocity)<256){ me->bounce_velocity=0; } need_drawing=1; } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif /* scroll indicator handler */ if (me->scroll_tick!=0){ /* scroll indicator */ if (!(me->flags&LIBAROMA_CTL_SCROLL_NO_INDICATOR)){ long diff= libaroma_tick()-me->scroll_tick; if ((diff>1000)&&(me->scroll_state>0)){ int nowstate=round(256.0*(1.0-libaroma_control_state( me->scroll_tick+1000,400))); if (nowstate!=me->scroll_state){ me->scroll_state=nowstate; need_drawing=1; } if (me->scroll_state<=0){ me->scroll_state=0; me->scroll_tick=0; me->scroll_handle_time=0; } } else if ((diff<500)&&(me->scroll_state<256)){ if (!me->scroll_handle_time){ me->scroll_handle_time=me->scroll_tick; } int nowstate=round(256.0* libaroma_control_state(me->scroll_handle_time,400)); if (nowstate!=me->scroll_state){ me->scroll_state=nowstate; need_drawing=1; } if (me->scroll_state>=256){ me->scroll_state=256; } } } else{ me->scroll_tick=0; } } #ifdef LIBAROMA_CONFIG_OPENMP } } #endif if (need_drawing){ me->synced_y=-1; } if (me->request_new_height!=-1){ #ifndef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD libaroma_ctl_scroll_set_height(ctl,me->request_new_height); libaroma_mutex_lock(me->fmutex); me->request_new_height=-1; libaroma_mutex_unlock(me->fmutex); #else return 0; #endif } #ifndef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD if (me->cache_state==10){ _libaroma_ctl_scroll_updatecache(ctl, 0); } #endif if (me->synced_y!=me->scroll_y){ return 1; } } return 0; } /* End of _libaroma_ctl_scroll_thread */ /* * Function : _libaroma_ctl_scroll_draw * Return Value: void * Descriptions: draw callback */ void _libaroma_ctl_scroll_draw( LIBAROMA_CONTROLP ctl, LIBAROMA_CANVASP c){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, ); if (me->client.handler){ if (!me->active){ libaroma_mutex_lock(me->mutex); if (me->request_new_height!=-1){ int nrq=me->request_new_height; libaroma_mutex_unlock(me->mutex); libaroma_ctl_scroll_set_height(ctl,nrq); libaroma_mutex_lock(me->mutex); me->request_new_height=-1; libaroma_mutex_unlock(me->mutex); } else{ libaroma_mutex_unlock(me->mutex); } if (me->cache_state==10){ _libaroma_ctl_scroll_updatecache(ctl, 0); } } if (me->client_canvas!=NULL){ libaroma_mutex_lock(me->mutex); int scroll_y = me->scroll_y; int draw_y = (scroll_y-me->draw_y+me->cache_y)%me->client_canvas->h; int draw_h = ctl->h; if (me->client_canvas->h<=ctl->h){ /* no scroll */ if ((me->minscroll_cb)&&(me->minscroll_y)){ LIBAROMA_CANVASP mscv=libaroma_canvas(c->w,me->minscroll_y); if (mscv){ libaroma_draw(mscv,me->client_canvas,0,0,0); me->minscroll_cb(ctl, mscv, me->scroll_y); libaroma_canvas_free(mscv); } } libaroma_canvas_setcolor(c,me->color_bg,0xff); libaroma_draw_ex( c, me->client_canvas, 0,0, 0,me->minscroll_y, me->client_canvas->w, me->client_canvas->h-me->minscroll_y, 0,0xff); me->synced_y=me->scroll_y; } else{ if ((me->minscroll_cb)&&(me->minscroll_y)){ int draw_yv = ((scroll_y-me->minscroll_y)-me->draw_y+me->cache_y) %me->client_canvas->h; LIBAROMA_CANVASP mscv=libaroma_canvas(c->w,me->minscroll_y); if (mscv){ libaroma_draw_ex( mscv,me->client_canvas, 0,0, 0,draw_yv, mscv->w,mscv->h, 0,0xff ); me->minscroll_cb(ctl, mscv, me->scroll_y); libaroma_canvas_free(mscv); } } LIBAROMA_CANVASP tc=c; int bvel=me->bounce_velocity; if (bvel!=0){ libaroma_canvas_setcolor(tc,me->color_bg,0xff); c=libaroma_canvas(tc->w,tc->h); } if (draw_y<0){ draw_y=me->client_canvas->h+draw_y; } if (draw_y+draw_h>me->client_canvas->h){ int top_h = (me->client_canvas->h - draw_y); int bottom_h = draw_h - top_h; int bottom_y = 0; if (top_h<1){ bottom_h+=top_h; bottom_y=abs(top_h); } #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel sections { #pragma omp section { #endif if (top_h>0){ if (!libaroma_draw_ex( c,me->client_canvas, 0,0, 0,draw_y, c->w,top_h, 0,0xff )){ ALOGV("Error top_h: %i,%i",draw_y,draw_h); } } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif if (bottom_h>0){ if (!libaroma_draw_ex( c,me->client_canvas, 0,top_h, 0,bottom_y, c->w,bottom_h, 0,0xff )){ ALOGV("Error bottom_h: %i,%i - %i", bottom_y,bottom_h,c->h); } } #ifdef LIBAROMA_CONFIG_OPENMP } } #endif me->synced_y=me->scroll_y; } else if ((draw_y<me->client_canvas->h)&&(draw_y>=0)){ if (!libaroma_draw_ex( c,me->client_canvas, 0,0, 0,draw_y, c->w,draw_h, 0,0xff )){ ALOGV("Error draw_h: %i,%i",draw_y,draw_h); } me->synced_y=me->scroll_y; } if (bvel!=0){ int y_i = (int) bvel>>8; libaroma_draw_ex(tc,c,0,0,0,y_i,tc->w,tc->h,0,0xff); libaroma_canvas_free(c); c=tc; } } libaroma_mutex_unlock(me->mutex); #ifdef LIBAROMA_CONFIG_OPENMP #pragma omp parallel sections { #pragma omp section { #endif if (me->active){ if ((!(me->flags&LIBAROMA_CTL_SCROLL_NO_INDICATOR))&& (me->max_scroll_y>me->minscroll_y)){ if ((me->scroll_state>0)||(me->handle_touched)){ int hdl_w,hdl_r,ctl_y,ctl_h; byte handle_opa=180; byte is_dark = libaroma_color_isdark(me->color_bg); word indicator_color = is_dark?RGB(cccccc):RGB(666666); int vss=(me->handle_touched)?256:me->scroll_state; if (me->flags&LIBAROMA_CTL_SCROLL_WITH_HANDLE){ hdl_w = libaroma_dp(5); hdl_r = hdl_w*2; if (!me->handle_touched){ hdl_r=(hdl_r * me->scroll_state) >> 8; } /* track */ ctl_y = libaroma_dp(18); ctl_h = ctl->h - (ctl_y*2); libaroma_draw_rect( c, ctl->w-(hdl_r+libaroma_dp(3)), ctl_y, libaroma_dp(1), ctl_h, libaroma_alpha(me->color_bg,indicator_color,(80*vss)>>8), 0xff ); if (me->handle_touched){ handle_opa=0xff; indicator_color=libaroma_colorget(ctl,NULL)->primary; } else{ handle_opa=220; } } else{ ctl_y = libaroma_dp(2); hdl_w = ctl_y*2; hdl_r = libaroma_dp(5); ctl_h = ctl->h - hdl_w; handle_opa = 120; } int hdl_ch= (ctl->h * ctl_h)/me->client_h; int hdl_h = MAX(hdl_ch,libaroma_dp(36)); hdl_ch = hdl_h-hdl_ch; int hdl_y = ((scroll_y * (ctl_h-hdl_ch))/me->client_h)+ctl_y; libaroma_draw_rect( c, ctl->w-(hdl_r+hdl_w), hdl_y, hdl_w, hdl_h, libaroma_alpha(me->color_bg,indicator_color, (handle_opa*vss)>>8), 0xff ); } } } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif /* vertical border */ if (me->flags&LIBAROMA_CTL_SCROLL_WITH_VBORDER){ if (me->max_scroll_y>me->minscroll_y){ word divcolor = libaroma_color_isdark(me->color_bg)?RGB(cccccc):RGB(666666); divcolor=libaroma_alpha(me->color_bg,divcolor,50); if (scroll_y>me->minscroll_y){ libaroma_draw_rect( c, 0, 0, c->w, libaroma_dp(1), divcolor, 0xff ); } if (scroll_y<me->max_scroll_y){ libaroma_draw_rect( c, 0, c->h-libaroma_dp(1), c->w, libaroma_dp(1), divcolor, 0xff ); } } } #ifdef LIBAROMA_CONFIG_OPENMP } #pragma omp section { #endif /* shadow */ if (me->flags&LIBAROMA_CTL_SCROLL_WITH_SHADOW){ libaroma_gradient_ex1(c, 0, 0, ctl->w, libaroma_dp(5),0,0,0,0,80,0,2); } #ifdef LIBAROMA_CONFIG_OPENMP } } #endif /* overshoot draw */ if ((me->max_scroll_y>me->minscroll_y)&&(me->ovs_state>0)&&(me->ovs_state<1)){ int max_ovsz = MIN(c->h/4,libaroma_dp(100)); int overshoot_sz = MIN(abs(me->ovs_y)/3,max_ovsz); if (overshoot_sz>0){ float opa = 0; if (me->ovs_state<0.25){ opa = libaroma_cubic_bezier_easein(me->ovs_state*4); } else{ opa = 1; } if (me->ovs_ustate>0){ opa*=1-libaroma_cubic_bezier_swiftout(me->ovs_ustate); } opa = MAX(0,MIN(1,opa)); if (me->ovs_ustate>0){ overshoot_sz = overshoot_sz * opa; } else{ overshoot_sz = overshoot_sz * MIN(1,opa*2); } float opacity=((float) overshoot_sz) / max_ovsz; overshoot_sz = MIN(MIN(overshoot_sz,c->h/5),libaroma_dp(80)); if (overshoot_sz>1){ LIBAROMA_CANVASP ovshot = libaroma_canvas_ex( c->w, overshoot_sz, 1); libaroma_canvas_setcolor(ovshot, libaroma_colorget(ctl,NULL)->primary,0); int vw = c->w>>2; if (me->ovs_x<0){ me->ovs_x=0; } else if (me->ovs_x>ctl->w){ me->ovs_x=ctl->w; } int vx = me->ovs_x>>2; int ovw= overshoot_sz>>1; int x1 = 0-(vw-vx); int x2 = x1+c->w+vw; if (me->ovs_y<0){ LIBAROMA_PATHP path=libaroma_path(x1,0); libaroma_path_curve( path, overshoot_sz, x1+ovw, overshoot_sz, x2-ovw, overshoot_sz, x2, 0 ); libaroma_path_draw(ovshot, path, 0, 0x60*opacity, 1, 0.33); libaroma_path_free(path); libaroma_draw(c,ovshot,0,0,1); } else{ LIBAROMA_PATHP path=libaroma_path(x1,overshoot_sz-1); libaroma_path_curve( path, overshoot_sz, x1+ovw, 0, x2-ovw, 0, x2,overshoot_sz-1 ); libaroma_path_draw(ovshot, path, 0, 0x60*opacity, 1, 0.33); libaroma_path_free(path); libaroma_draw(c,ovshot,0,c->h-overshoot_sz,1); } libaroma_canvas_free(ovshot); } } } } else{ if ((me->minscroll_cb)&&(me->minscroll_y)){ LIBAROMA_CANVASP mscv=libaroma_canvas(c->w,me->minscroll_y); if (mscv){ libaroma_canvas_setcolor(mscv,me->color_bg,0xff); me->minscroll_cb(ctl, mscv, me->scroll_y); libaroma_canvas_free(mscv); } } libaroma_canvas_setcolor(c,me->color_bg,0xff); } } else{ if ((me->minscroll_cb)&&(me->minscroll_y)){ LIBAROMA_CANVASP mscv=libaroma_canvas(c->w,me->minscroll_y); if (mscv){ libaroma_canvas_setcolor(mscv,me->color_bg,0xff); me->minscroll_cb(ctl, mscv, me->scroll_y); libaroma_canvas_free(mscv); } } libaroma_canvas_setcolor(c,me->color_bg,0xff); } } /* End of _libaroma_ctl_scroll_draw */ /* * Function : _libaroma_ctl_scroll_touch_handler * Return Value: dword * Descriptions: touch message handler */ dword _libaroma_ctl_scroll_touch_handler( LIBAROMA_CONTROLP ctl, LIBAROMA_MSGP msg,int x, int y, byte state){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); switch(state){ case LIBAROMA_HID_EV_STATE_DOWN:{ ALOGT("scroll_message - touch down: %i, %i",x, y); byte is_have_velocity=( (abs(me->velocity)> libaroma_dp(2)*255 )|| me->bounce_velocity)?1:0; byte is_direct_handle = 0; if (me->flags&LIBAROMA_CTL_SCROLL_WITH_HANDLE){ me->handle_touched= (x>ctl->w-libaroma_dp(_LIBAROMA_CTL_SCROLL_HANDLE_DP))?1:0; is_direct_handle = ((me->handle_touched)&&(me->scroll_state)&&(me->max_scroll_y>0))?1:0; } else{ me->handle_touched=0; } /* set fling value */ me->bounce_velocity=0; me->velocity=0; me->allow_scroll=1; me->touched=1; /* check client message */ libaroma_mutex_lock(me->mutex); me->client_touch_start=0; me->client_touched=0; if ((!is_have_velocity)&&(!is_direct_handle)&& (me->client.handler->message)){ int client_x = x; int client_y = y + me->scroll_y; if (_libaroma_ctl_scroll_client_msg( ctl,LIBAROMA_CTL_SCROLL_MSG_ISNEED_TOUCH, client_x, client_y )==LIBAROMA_CTL_SCROLL_MSG_HANDLED){ me->client_touch_start=msg->sent; /*libaroma_tick();*/ me->allow_scroll=2; } } libaroma_mutex_unlock(me->mutex); if (is_direct_handle){ me->allow_scroll=1; int ctl_h = ctl->h-libaroma_dp(36); int sarea = ctl_h - ((ctl->h * ctl_h) / me->client_h); int scr_y = y-(ctl->h/2)+(sarea/2); int req_y = (scr_y * me->max_scroll_y) / sarea; libaroma_ctl_scroll_request_pos(ctl,req_y); } else if (me->flags&LIBAROMA_CTL_SCROLL_WITH_HANDLE){ me->request_scroll_y=-1; } libaroma_fling_down(&me->fling, y); /* save touch value */ me->touch_x=x; me->touch_y=y; me->touch_scroll_y = me->scroll_y; me->ovs_x=x; } break; case LIBAROMA_HID_EV_STATE_MOVE: case LIBAROMA_HID_EV_STATE_UP:{ ALOGT("scroll_message - touch move: %i, %i",x, y); me->ovs_x=x; me->bounce_velocity=0; byte is_first_allowed = 0; if (me->allow_scroll==2){ libaroma_mutex_lock(me->mutex); int move_sz = me->touch_y - y; int client_message_param = LIBAROMA_CTL_SCROLL_MSG_TOUCH_MOVE; int scrdp=libaroma_dp( me->client_touched? _LIBAROMA_CTL_SCROLL_MIN_ALOWSCROLL_DP: _LIBAROMA_CTL_SCROLL_MIN_ALOWSCROLL_DP_NOITEM ); if (abs(move_sz)>=scrdp){ is_first_allowed = 1; me->allow_scroll=1; me->client_touch_start=0; client_message_param = LIBAROMA_CTL_SCROLL_MSG_TOUCH_CANCEL; } /* send client message */ if ((me->client_touched)&&(me->client.handler->message)){ int client_x = x; int client_y = y + me->scroll_y; if (_libaroma_ctl_scroll_client_msg( ctl,client_message_param, client_x, client_y )==LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW){ me->synced_y=-1; } if (client_message_param==LIBAROMA_CTL_SCROLL_MSG_TOUCH_CANCEL){ me->client_touched=0; } } libaroma_mutex_unlock(me->mutex); } /* scrolling move handler */ if ((me->allow_scroll==1)&&(me->touch_y!=y)){ int move_sz = me->touch_y - y; if (!me->handle_touched){ if (me->scroll_y+move_sz<me->minscroll_y){ if (!me->ovs_start){ me->ovs_start=msg->sent; /*libaroma_tick();*/ me->ovs_bounce=0; me->ovs_state=0; me->ovs_ustate=0; me->ovs_ustart=0; me->ovs_y=0; } me->ovs_y+=move_sz; } else if (me->scroll_y+move_sz>me->max_scroll_y){ if (!me->ovs_start){ me->ovs_start=msg->sent; /*libaroma_tick();*/ me->ovs_bounce=0; me->ovs_state=0; me->ovs_ustate=0; me->ovs_ustart=0; me->ovs_y=0; } me->ovs_y+=move_sz; } else if (!me->ovs_ustart){ me->ovs_ustate=0; me->ovs_ustart=1; me->ovs_bounce=3; } /* normal scroll */ if (is_first_allowed){ libaroma_ctl_scroll_request_pos(ctl, me->touch_scroll_y+move_sz); } else{ me->request_scroll_y=-1; libaroma_ctl_scroll_set_pos(ctl, me->touch_scroll_y+move_sz); } me->touch_scroll_y = me->scroll_y; /* set history */ libaroma_fling_move(&me->fling, y); } else if (me->max_scroll_y>0){ int ctl_h = ctl->h-libaroma_dp(36); int sarea = ctl_h - ((ctl->h * ctl_h) / me->client_h); int scr_y = y-(ctl->h/2)+(sarea/2); int req_y = (scr_y * me->max_scroll_y) / sarea; libaroma_ctl_scroll_request_pos(ctl,req_y); } me->touch_y=y; } if (state==LIBAROMA_HID_EV_STATE_UP){ ALOGT("scroll_message - touch up: %i, %i",x, y); me->bounce_velocity=0; if (!me->handle_touched){ if (me->allow_scroll){ me->velocity=(libaroma_fling_up(&me->fling, y)* libaroma_px(18))/libaroma_dp(4); if (me->velocity){ me->touched=0; } } } else if (me->allow_scroll==1){ if (!(me->flags&LIBAROMA_CTL_SCROLL_NO_INDICATOR)){ me->scroll_tick = msg->sent; /*libaroma_tick();*/ me->scroll_state=256; me->synced_y=-1; } } /* clear item touch if initialized */ libaroma_mutex_lock(me->mutex); if ((me->client_touch_start||me->client_touched)&& (me->client.handler->message)){ int client_x = x; int client_y = y + me->scroll_y; if (me->client_touch_start){ if (_libaroma_ctl_scroll_client_msg( ctl,LIBAROMA_CTL_SCROLL_MSG_TOUCH_DOWN, client_x, client_y )==LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW){ me->synced_y=-1; } } if (_libaroma_ctl_scroll_client_msg( ctl,LIBAROMA_CTL_SCROLL_MSG_TOUCH_UP, client_x, client_y )==LIBAROMA_CTL_SCROLL_MSG_NEED_DRAW){ me->synced_y=-1; } } me->client_touch_start=0; me->client_touched=0; libaroma_mutex_unlock(me->mutex); /* reset */ me->handle_touched=0; me->allow_scroll=0; me->touched=0; me->touch_x=0; me->touch_y=0; me->ovs_x=x; if (!me->ovs_ustart){ me->ovs_ustate=0; me->ovs_ustart=1; me->ovs_bounce=3; } } } break; } return 0; } /* End of _libaroma_ctl_scroll_touch_handler */ /* * Function : libaroma_ctl_scroll_isactive * Return Value: byte * Descriptions: check if control is active */ byte libaroma_ctl_scroll_isactive(LIBAROMA_CONTROLP ctl){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); return me->active; } /* End of libaroma_ctl_scroll_isactive */ /* * Function : _libaroma_ctl_scroll_msg * Return Value: byte * Descriptions: message callback */ dword _libaroma_ctl_scroll_msg( LIBAROMA_CONTROLP ctl, LIBAROMA_MSGP msg){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); switch(msg->msg){ case LIBAROMA_MSG_TOUCH: { /* touch handler */ int x = msg->x; int y = msg->y; libaroma_window_calculate_pos(NULL,ctl,&x,&y); return _libaroma_ctl_scroll_touch_handler( ctl,msg,x,y,msg->state ); } break; case LIBAROMA_MSG_WIN_ACTIVE: { /* start updater thread*/ me->active=1; me->client_touch_start=0; me->client_touched=0; me->synced_y = -1; /* start cache thread */ #ifdef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD libaroma_thread_create( &me->cache_thread, _libaroma_ctl_scroll_cache_thread, (voidp) ctl); #endif libaroma_thread_create( &me->calc_thread, _libaroma_ctl_scroll_calc_thread, (voidp) ctl); } break; case LIBAROMA_MSG_WIN_INACTIVE: { /* stop updater thread */ me->active=0; libaroma_sleep(30); libaroma_cond_lock(&me->cmutex); libaroma_cond_signal(&me->ccond); libaroma_cond_unlock(&me->cmutex); libaroma_mutex_lock(me->mutex); libaroma_thread_join(me->calc_thread); #ifdef LIBAROMA_CTL_SCROLL_WITH_CACHE_THREAD libaroma_thread_join(me->cache_thread); me->cache_thread=0; #endif me->calc_thread=0; me->client_touch_start=0; me->client_touched=0; me->synced_y = -1; libaroma_mutex_unlock(me->mutex); } break; } return 0; } /* End of _libaroma_ctl_scroll_msg */ /* * Function : _libaroma_ctl_scroll_destroy * Return Value: void * Descriptions: destroy callback */ void _libaroma_ctl_scroll_destroy( LIBAROMA_CONTROLP ctl){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, ); /* destroy client */ if (me->client.handler->destroy!=NULL){ me->client.handler->destroy(ctl,&me->client); } if (me->client_canvas!=NULL){ libaroma_canvas_free(me->client_canvas); me->client_canvas=NULL; } libaroma_cond_free(&me->ccond, &me->cmutex); libaroma_mutex_free(me->blitmutex); libaroma_mutex_free(me->fmutex); libaroma_mutex_free(me->mutex); free(me); } /* End of _libaroma_ctl_scroll_destroy */ /* * Function : libaroma_ctl_scroll * Return Value: LIBAROMA_CONTROLP * Descriptions: create scroll control */ LIBAROMA_CONTROLP libaroma_ctl_scroll( LIBAROMA_WINDOWP win, word id, int x, int y, int w, int h, word bg_color, byte flags ){ /* init internal data */ _LIBAROMA_CTL_SCROLLP me = (_LIBAROMA_CTL_SCROLLP) calloc(sizeof(_LIBAROMA_CTL_SCROLL),1); if (!me){ ALOGW("libaroma_ctl_scroll alloc scroll memory failed"); return NULL; } libaroma_mutex_init(me->blitmutex); /* blit drawing mutex */ libaroma_mutex_init(me->fmutex); /* cache drawing mutex */ libaroma_mutex_init(me->mutex); /* control drawing mutex */ libaroma_cond_init(&me->ccond, &me->cmutex); /* set internal data */ me->flags = flags; me->color_bg = bg_color; me->request_new_height=-1; me->request_scroll_y=-1; me->synced_y = -1; /* init control */ LIBAROMA_CONTROLP ctl = libaroma_control_new( id, x, y, w, h, libaroma_dp(32),libaroma_dp(32), /* min size */ me, &_libaroma_ctl_scroll_handler, win ); if (!ctl){ free(me); } return ctl; } /* End of libaroma_ctl_scroll */ /* * Function : libaroma_ctl_scroll_request_height * Return Value: byte * Descriptions: request height */ byte libaroma_ctl_scroll_request_height(LIBAROMA_CONTROLP ctl, int h){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); libaroma_mutex_lock(me->fmutex); me->request_new_height=h; libaroma_mutex_unlock(me->fmutex); return 1; } /* End of libaroma_ctl_scroll_request_height */ /* * Function : libaroma_ctl_scroll_get_scroll * Return Value: int * Descriptions: get scroll position */ int libaroma_ctl_scroll_get_scroll(LIBAROMA_CONTROLP ctl, int * scroll_h){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (scroll_h!=NULL){ *scroll_h=me->max_scroll_y; } return me->scroll_y; } /* End of libaroma_ctl_scroll_get_scroll */ /* * Function : libaroma_ctl_scroll_get_height * Return Value: int * Descriptions: get scroll height */ int libaroma_ctl_scroll_get_height(LIBAROMA_CONTROLP ctl){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); int ret=me->client_h; libaroma_mutex_lock(me->fmutex); if (me->request_new_height!=-1){ ret=me->request_new_height; } libaroma_mutex_unlock(me->fmutex); return ret; } /* End of libaroma_ctl_scroll_get_height */ /* * Function : libaroma_ctl_scroll_set_height * Return Value: byte * Descriptions: set scroll height */ byte libaroma_ctl_scroll_set_height(LIBAROMA_CONTROLP ctl, int h){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client_h==h){ return 0; } libaroma_mutex_lock(me->blitmutex); libaroma_mutex_lock(me->fmutex); me->max_scroll_y = h-ctl->h; if (me->max_scroll_y<me->minscroll_y){ me->max_scroll_y=me->minscroll_y; } if (h<1){ if (me->client_canvas!=NULL){ me->client_h = h; libaroma_mutex_lock(me->mutex); libaroma_canvas_free(me->client_canvas); me->client_canvas=NULL; libaroma_mutex_unlock(me->mutex); } } else{ /* max 3x control height */ int valid_height = h; #ifdef LIBAROMA_CTL_SCROLL_WITH_MAX_CACHE if (valid_height>_LIBAROMA_CTL_SCROLL_MAX_CACHE){ valid_height=_LIBAROMA_CTL_SCROLL_MAX_CACHE; } #endif LIBAROMA_CANVASP c=me->client_canvas; if (me->client_canvas){ if (valid_height!=c->h){ int ns = c->l * valid_height; if (ns>c->s){ libaroma_mutex_lock(me->mutex); c->data=realloc(c->data,ns*2); libaroma_mutex_unlock(me->mutex); c->s=ns; c->h=valid_height; me->client_h = h; } else{ me->client_h = h; c->s=ns; c->h=valid_height; libaroma_mutex_lock(me->mutex); c->data=realloc(c->data,ns*2); libaroma_mutex_unlock(me->mutex); } } else{ me->client_h = h; } } else{ libaroma_mutex_lock(me->mutex); c = libaroma_canvas(ctl->w,valid_height); libaroma_canvas_setcolor(c,me->color_bg,0xff); me->client_canvas = c; libaroma_mutex_unlock(me->mutex); me->client_h = h; } } me->synced_y=-1; libaroma_mutex_unlock(me->fmutex); libaroma_mutex_unlock(me->blitmutex); libaroma_ctl_scroll_set_pos(ctl,me->scroll_y); me->cache_state = 10; /* force recalculate */ return 1; } /* End of libaroma_ctl_scroll_set_height */ /* * Function : libaroma_ctl_scroll_set_pos * Return Value: byte * Descriptions: set scroll position - directly */ byte libaroma_ctl_scroll_set_pos(LIBAROMA_CONTROLP ctl, int scroll_y){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); int req_scroll_y = scroll_y; if (req_scroll_y>me->max_scroll_y){ req_scroll_y = me->max_scroll_y; } if (req_scroll_y<me->minscroll_y){ req_scroll_y=me->minscroll_y; } if (me->scroll_y!=req_scroll_y){ me->move_state=(req_scroll_y<me->scroll_y)?1:2; me->scroll_y=req_scroll_y; if (!me->cache_state){ me->cache_state=1; } if (!(me->flags&LIBAROMA_CTL_SCROLL_NO_INDICATOR)){ me->scroll_tick = libaroma_tick(); } } return 1; } /* End of libaroma_ctl_scroll_set_pos */ /* * Function : libaroma_ctl_scroll_request_pos * Return Value: byte * Descriptions: request to change scroll position - nicely */ byte libaroma_ctl_scroll_request_pos(LIBAROMA_CONTROLP ctl, int req_y){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (req_y>me->max_scroll_y){ me->request_scroll_y=me->max_scroll_y; } else if (req_y<me->minscroll_y){ me->request_scroll_y=me->minscroll_y; } else{ me->request_scroll_y=req_y; } return 1; } /* End of libaroma_ctl_scroll_request_pos */ /* * Function : libaroma_ctl_scroll_get_bg_color * Return Value: byte * Descriptions: request to change scroll position - nicely */ word libaroma_ctl_scroll_get_bg_color(LIBAROMA_CONTROLP ctl){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); return me->color_bg; } /* End of libaroma_ctl_scroll_get_bg_color */ /* * Function : libaroma_ctl_scroll_set_client * Return Value: byte * Descriptions: set client handler */ byte libaroma_ctl_scroll_set_client( LIBAROMA_CONTROLP ctl, voidp internal, LIBAROMA_CTL_SCROLL_CLIENT_HANDLERP handler ){ if (handler==NULL){ return 0; } /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client.handler){ if (me->client.handler->destroy!=NULL){ me->client.handler->destroy(ctl,&me->client); } } me->client.handler=handler; me->client.internal=internal; me->synced_y=-1; me->cache_state = 10; /* force recalculate */ return 1; } /* End of libaroma_ctl_scroll_set_client */ /* * Function : libaroma_ctl_scroll_get_client * Return Value: LIBAROMA_CTL_SCROLL_CLIENTP * Descriptions: get scroll client data */ LIBAROMA_CTL_SCROLL_CLIENTP libaroma_ctl_scroll_get_client( LIBAROMA_CONTROLP ctl){ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, NULL ); if (!me->client.handler){ return NULL; } return &me->client; } /* End of libaroma_ctl_scroll_get_client */ /* * Function : libaroma_ctl_scroll_is_visible * Return Value: byte * Descriptions: is this area visible? */ byte libaroma_ctl_scroll_is_visible( LIBAROMA_CONTROLP ctl, int y, int h ){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client_canvas==NULL){ return 0; } if (!me->active){ return 0; } int draw_t=me->draw_y; int draw_b=draw_t+me->client_canvas->h; int bottom = y+h; if ((bottom>draw_t)&&(y<draw_b)){ return 1; } return 0; } /* End of libaroma_ctl_scroll_is_visible */ /* * Function : libaroma_ctl_scroll_blit * Return Value: byte * Descriptions: blit canvas into client canvas */ byte libaroma_ctl_scroll_blit( LIBAROMA_CONTROLP ctl, LIBAROMA_CANVASP canvas, int x, int y, int w, int h, byte erase ){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (me->client_canvas==NULL){ return 0; } if (!me->active){ return 0; } if (x<0){ x=0; } if ((w<1)||(x+w>me->client_canvas->w)){ w=me->client_canvas->w-x; } int bottom = y+h; int draw_t = me->draw_y; int draw_b = draw_t+me->client_canvas->h; if ((bottom>draw_t)&&(y<draw_b)){ int dy = (y-draw_t+me->cache_y)%me->client_canvas->h; int split_h = (dy+h)-me->client_canvas->h; byte is_split=((dy+h>me->client_canvas->h)&&(me->cache_y)&&(split_h>0)); libaroma_mutex_lock(me->blitmutex); if (erase){ libaroma_draw_rect( me->client_canvas, x, dy, w, h, me->color_bg, 0xff ); if (is_split){ libaroma_draw_rect( me->client_canvas, x, 0, w, split_h, me->color_bg, 0xff ); } } libaroma_draw_ex( me->client_canvas, canvas, x, dy, 0, 0, w, h, 1, 0xff ); if (is_split){ libaroma_draw_ex( me->client_canvas, canvas, x, 0, 0, h-split_h, w, split_h, 1, 0xff ); } libaroma_mutex_unlock(me->blitmutex); return 1; } return 0; } /* End of libaroma_ctl_scroll_blit */ /* * Function : libaroma_ctl_scroll_set_min_scroll * Return Value: byte * Descriptions: set minimal scroll y */ byte libaroma_ctl_scroll_set_min_scroll( LIBAROMA_CONTROLP ctl, LIBAROMA_CTL_SCROLL_MINSCROLL_HANDLER cb, int y ){ /* internal check */ _LIBAROMA_CTL_CHECK( _libaroma_ctl_scroll_handler, _LIBAROMA_CTL_SCROLLP, 0 ); if (y<0){ return 0; } libaroma_mutex_lock(me->fmutex); me->minscroll_cb=cb; me->minscroll_y=y; me->synced_y=-1; libaroma_mutex_unlock(me->fmutex); return 1; } #endif /* __libaroma_ctl_scroll_c__ */
test74.c
int main() { int x ; #pragma omp parallel #pragma omp task final(x > 1) x = x + 1; }
3d7pt.c
/* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 24; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = alpha * (A[t%2][i][j][k]) + beta * (A[t%2][i - 1][j][k] + A[t%2][i][j - 1][k] + A[t%2][i][j][k - 1] + A[t%2][i + 1][j][k] + A[t%2][i][j + 1][k] + A[t%2][i][j][k + 1]); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
main.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <hdf5.h> #if defined(_OPENMP) #include <omp.h> #endif #include "allvars.h" #include "proto.h" MyIDType *IdSnapTable; MyIDType *tmpptr; int *int_tmpptr; long int *long_int_tmpptr; long long int *long_long_int_tmpptr; void get_TotNumPart(void); int main(int argc, char **argv) { if(argc != 3) { printf("\n usage: L-BaseTree <parameterfile> <outputnum>\n"); printf(" <parameterfile> see readparmeterfile.c\n"); printf(" <outputnum> snapshot number\n\n"); exit(1); } read_parameter_file(argv[1]); SnapshotNum = atoi(argv[2]); #if defined(_OPENMP) printf("OMP: max-threads=%d\n", omp_get_max_threads()); fflush(stdout); #endif /*==========================================================================*/ printf("allocating group catalogues...\n"); fflush(stdout); allocate_group_catalogue(SnapshotNum, &CatA, 1); allocate_group_catalogue(SnapshotNum, &CatB, 2); printf("populating group catalogues...\n"); fflush(stdout); load_group_catalogue(SnapshotNum, &CatA, 1); load_group_catalogue(SnapshotNum, &CatB, 2); /*==========================================================================*/ /*==========================================================================*/ printf("allocating subhalo catalogues...\n"); fflush(stdout); allocate_subhalo_catalogue(SnapshotNum, &CatA, 1); allocate_subhalo_catalogue(SnapshotNum, &CatB, 2); printf("populating subhalo catalogues...\n"); fflush(stdout); load_subhalo_catalogue(SnapshotNum, &CatA, 1); load_subhalo_catalogue(SnapshotNum, &CatB, 2); /*==========================================================================*/ /*==========================================================================*/ printf("reading/sorting IDs...\n"); fflush(stdout); get_id_translation_table(); /* Load IdSnapTable: sorted array of length N_dm with minimum (first) value of Min(ID_dm) and a maximum (last) value of Max(ID_dm) */ printf("reassigning ids ...\n"); fflush(stdout); reassign_ids(CatA.TotNids, CatA.IdList); reassign_ids(CatB.TotNids, CatB.IdList); myfree(IdSnapTable); printf("done.\n"); fflush(stdout); /*==========================================================================*/ /*==========================================================================*/ /* set cat->IdToHalo[i] such that each particle can reference the Halo that it is a part of */ printf("preparing ID-to-halo tables...\n"); fflush(stdout); prepare_index_list(&CatA); printf("index A done.\n"); fflush(stdout); prepare_index_list(&CatB); printf("index B done.\n"); fflush(stdout); /*==========================================================================*/ /*==========================================================================*/ /* get descendants */ printf("determine_descendants...\n"); fflush(stdout); determine_descendants(&CatA, &CatB); printf("desc AB done.\n"); fflush(stdout); determine_descendants(&CatB, &CatA); printf("desc BA done.\n"); fflush(stdout); printf("descendants done.\n"); fflush(stdout); /*==========================================================================*/ /*==========================================================================*/ printf("Doing Backward decision ...\n"); decide_backwards(&CatA, &CatB); printf("Backward decision for AB done.\n"); fflush(stdout); /*==========================================================================*/ printf("saving descendants...\n"); fflush(stdout); save_decendant_list(); printf("saving done.\n"); fflush(stdout); /*==========================================================================*/ delete_id_translation_table(); return 0; } void decide_backwards(struct halo_catalogue *catA, struct halo_catalogue *catB) { int i, j; for(i = 0; i < catA->TotNsubhalos; i++) { j = catA->Descendant[i].HaloIndex; if (j > -1) if (catB->Descendant[j].HaloIndex != i) catA->Descendant[i].HaloIndex = -1; } fflush(stdout); } struct cand_data { int haloindex; float weight; }; void determine_descendants(struct halo_catalogue *catA, struct halo_catalogue *catB) { int i, j, ndiff, ncand, haloB, prev, maxlen; MyIDType id; float weightmax; int halomax; struct cand_data *candlist, *difflist; maxlen = 0; for(i = 0; i < catA->TotNsubhalos; i++) if(catA->SubLen[i] > maxlen) maxlen = catA->SubLen[i]; #if defined(_OPENMP) #pragma omp parallel private(candlist, difflist, ncand, i, j, id, haloB, ndiff, prev, weightmax, halomax) #endif { candlist = mymalloc(maxlen * sizeof(struct cand_data)); difflist = mymalloc(maxlen * sizeof(struct cand_data)); #if defined(_OPENMP) #pragma omp for schedule(dynamic) nowait #endif for(i = 0; i < catA->TotNsubhalos; i++) // for each subhalo in Snapshot A ... { ncand = 0; for(j = 0; j < catA->SubLen[i]; j++) // ... and for each particle in each subhalo { id = catA->IdList[catA->SubOffset[i] + j]; // ... identify the particle's ID if(id >= 0 && id < TotNumPart) // ... (and as long as it's in the accetable range) { haloB = catB->IdToHalo[id]; // ... identify the halo that contains this particle in snapshot B if(haloB >= 0) // all particles are in haloes (they have -1), but if it is in a halo... { candlist[ncand].haloindex = haloB; // ... set the haloindex accordingly candlist[ncand].weight = 1.0 / pow(j + 1, ALPHA); // ... and set the weighting based on how bound it was ncand++; } } else { char buf[100]; long_to_str(buf, id); printf("bummer! i=%d id=%s TotumPart=%d\n", i, buf, (int)TotNumPart); exit(4); } } qsort(candlist, ncand, sizeof(struct cand_data), sort_candlist); for(j = 0, ndiff = 0, prev = -1; j < ncand; j++) { if(candlist[j].haloindex != prev) { ndiff++; difflist[ndiff - 1].haloindex = candlist[j].haloindex; difflist[ndiff - 1].weight = 0; } difflist[ndiff - 1].weight += candlist[j].weight; prev = candlist[j].haloindex; } weightmax = 0; halomax = -1; for(j = 0; j < ndiff; j++) { if(difflist[j].weight > weightmax) { weightmax = difflist[j].weight; halomax = difflist[j].haloindex; } } if(ndiff > 0 && halomax >= 0) { catA->Descendant[i].HaloIndex = halomax; } else { catA->Descendant[i].HaloIndex= -1; } } myfree(candlist); myfree(difflist); } } int sort_twoids_id(const void *a, const void *b) { if(((struct twoids *) a)->id < ((struct twoids *) b)->id) return -1; if(((struct twoids *) a)->id > ((struct twoids *) b)->id) return +1; return 0; } int sort_twoids_ord(const void *a, const void *b) { if(((struct twoids *) a)->ord < ((struct twoids *) b)->ord) return -1; if(((struct twoids *) a)->ord > ((struct twoids *) b)->ord) return +1; return 0; } int sort_candlist(const void *a, const void *b) { if(((struct cand_data *) a)->haloindex < ((struct cand_data *) b)->haloindex) return -1; if(((struct cand_data *) a)->haloindex > ((struct cand_data *) b)->haloindex) return +1; return 0; } int sort_IDType(const void *a, const void *b) { if(*((MyIDType *) a) < *((MyIDType *) b)) return -1; if(*((MyIDType *) a) > *((MyIDType *) b)) return +1; return 0; } void prepare_index_list(struct halo_catalogue *cat) { MyIDType id; signed long long ii; int i, j; cat->IdToHalo = mymalloc(sizeof(int) * TotNumPart); #if defined(_OPENMP) #pragma omp parallel for #endif for(ii = 0; ii < TotNumPart; ii++) // start by assigning all particles to no halo cat->IdToHalo[ii] = -1; #if defined(_OPENMP) #pragma omp parallel for private(j,id) #endif for(i = 0; i < cat->TotNsubhalos; i++) // loop over all subhalos for(j = 0; j < cat->SubLen[i]; j++) // loop over all particles in each subhalo { id = cat->IdList[cat->SubOffset[i] + j]; // id from the subhalo list if(id >= 0 && id < TotNumPart) cat->IdToHalo[id] = i; else { char buf[100]; long_to_str(buf, id); printf("bummer! i=%d j=%d id=%s id=%d TotNumPart=%d)\n", i, j, buf, (int)id, (int)TotNumPart); exit(1); } } } void allocate_group_catalogue(int num, struct halo_catalogue *cat, int which) { int nids, nFiles, nsubhalos, ngroups; char buf[1000]; if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, 0); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, 0); read_basic_subfind_header_hdf5(buf, 0, cat, &nFiles , &nids , &nsubhalos, &ngroups); int jjj; cat->GroupNsubs = mymalloc(sizeof(MyIDType) * cat->TotNgroups); cat->GroupLen = mymalloc(sizeof(MyIDType) * cat->TotNgroups); cat->GroupOffset = mymalloc(sizeof(MyIDType) * cat->TotNgroups); cat->GroupLenType = mymalloc(6 * sizeof(MyIDType *)); cat->GroupOffsetType = mymalloc(6 * sizeof(MyIDType *)); cat->SubhaloLenType = mymalloc(6 * sizeof(MyIDType *)); cat->Group = mymalloc(sizeof(struct group_data) * cat->TotNgroups); for(jjj=0 ; jjj< 6; jjj++) { cat->GroupLenType[jjj] = mymalloc(cat->TotNgroups * sizeof(MyIDType)); cat->GroupOffsetType[jjj] = mymalloc(cat->TotNgroups * sizeof(MyIDType)); } for(jjj=0; jjj< cat->TotNgroups; jjj++) cat->Group[jjj].count = 0; } void load_group_catalogue(int num, struct halo_catalogue *cat, int which) { int i=0, nids, nFiles, nsubhalos, ngroups, groupcount; char buf[1000]; if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, i); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, i); read_basic_subfind_header_hdf5(buf, i, cat, &nFiles , &nids , &nsubhalos, &ngroups); groupcount = 0; printf("starting the group loading loop\n"); fflush(stdout); for(i = 0, nFiles = 1; i < nFiles; i++) { if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, i); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, i); if(i == 1) printf(" ... to ... \n"); if(i == 0 || i == nFiles-1) printf("Loading : %s\n",buf); read_basic_subfind_header_hdf5(buf, i, cat, &nFiles , &nids , &nsubhalos, &ngroups); if(ngroups > 0) read_subfind_group_hdf5(buf, i, cat, ngroups, groupcount); groupcount += ngroups; } for(i=0 ; i < cat->TotNgroups ; i++) cat->Group[i].count = 0; printf("finished the group loading loop\n"); fflush(stdout); } void allocate_subhalo_catalogue(int num, struct halo_catalogue *cat, int which) { int nids, nFiles, nsubhalos, ngroups; char buf[1000]; if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, 0); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, 0); read_basic_subfind_header_hdf5(buf, 0, cat, &nFiles , &nids , &nsubhalos, &ngroups); int iii,jjj, i; cat->SubLen = mymalloc(sizeof(int) * cat->TotNsubhalos); cat->SubParentHalo = mymalloc(sizeof(int) * cat->TotNsubhalos); cat->SubOffset = mymalloc(sizeof(MyIDType) * cat->TotNsubhalos); cat->Descendant = mymalloc(sizeof(struct descendant_data) * cat->TotNsubhalos); cat->SubhaloGrNr = mymalloc(sizeof(MyIDType) * cat->TotNsubhalos); cat->SubhaloLen = mymalloc(sizeof(MyIDType) * cat->TotNsubhalos); cat->SubhaloLenType = mymalloc(6 * sizeof(MyIDType *)); for (i=0; i < cat->TotNsubhalos; i++) cat->Descendant[i].HaloIndex=-1; for(jjj=0 ; jjj< 6; jjj++) cat->SubhaloLenType[jjj] = mymalloc(cat->TotNsubhalos * sizeof(MyIDType)); for(iii=0 ; iii < cat->TotNgroups ; iii++) if(cat->GroupNsubs[iii] > 0) cat->Group[iii].Subhalo = mymalloc(sizeof(struct subhalo_data) * cat->GroupNsubs[iii]); } void load_subhalo_catalogue(int num, struct halo_catalogue *cat, int which) { int i=0, nids, nFiles, nsubhalos, subcount, ngroups; char buf[1000]; MyIDType * local_id_array, ndm = 0 , Nskip = 0; if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, i); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, i); read_basic_subfind_header_hdf5(buf, i, cat, &nFiles , &nids , &nsubhalos, &ngroups); subcount = 0; printf("starting the subhalo loading loop\n"); fflush(stdout); for(i = 0, nFiles = 1; i < nFiles; i++) { if (which==1) sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir1, num, num, i); else sprintf(buf, "%s/groups_%03d/fof_subhalo_tab_%03d.%d.hdf5", OutputDir2, num, num, i); if(i == 1) printf(" ... to ... \n"); if(i == 0 || i == nFiles-1) printf("Loading : %s\n",buf); read_basic_subfind_header_hdf5(buf, i, cat, &nFiles , &nids , &nsubhalos, &ngroups); if(nsubhalos > 0) read_subfind_subhalo_hdf5(buf, i, cat, nsubhalos, subcount); subcount += nsubhalos; } long_to_str(buf, cat->TotNids); printf("finished the subhalo loading loop\n"); fflush(stdout); int iii,jjj,j; long int subfind_dm_ids=0; for(i=0 ; i < cat->TotNsubhalos ; i++) { cat->Group[cat->SubhaloGrNr[i]].Subhalo[cat->Group[cat->SubhaloGrNr[i]].count].SubhaloLen = cat->SubhaloLen[i]; for(j=0 ; j < 6 ; j++) cat->Group[cat->SubhaloGrNr[i]].Subhalo[cat->Group[cat->SubhaloGrNr[i]].count].SubhaloLenType[j] = cat->SubhaloLenType[j][i]; cat->Group[cat->SubhaloGrNr[i]].count = cat->Group[cat->SubhaloGrNr[i]].count + 1; } for(iii = 0; iii < cat->TotNgroups; iii++) // for each group for(jjj = 0; jjj < cat->Group[iii].count ; jjj++) // and each subhalo within the group subfind_dm_ids += cat->Group[iii].Subhalo[jjj].SubhaloLenType[1]; cat->TotNids = subfind_dm_ids; cat->IdList = mymalloc( subfind_dm_ids * sizeof(MyIDType)); i = 0; if (which==1) sprintf(buf, "%s/snapdir_%03d/%s_%03d.%d.hdf5", OutputDir1, num,SnapshotFileBase1, num, i); // change 1 else sprintf(buf, "%s/snapdir_%03d/%s_%03d.%d.hdf5", OutputDir2, num,SnapshotFileBase2, num, i); // change 1 read_snap_header_attributes_in_hdf5(buf); ndm = header.npartTotal[1]+ ((long long) header.npartTotalHighWord[1] << 32); local_id_array = mymalloc(ndm * sizeof(MyIDType)); for(i = 0; i < nFiles; i++) { if (which==1) sprintf(buf, "%s/snapdir_%03d/%s_%03d.%d.hdf5", OutputDir1, num, SnapshotFileBase1, num, i); else sprintf(buf, "%s/snapdir_%03d/%s_%03d.%d.hdf5", OutputDir2, num, SnapshotFileBase2, num, i); if(i == 0 || i == nFiles-1) printf(" and : %s\n",buf); read_snap_header_attributes_in_hdf5(buf); read_particle_ids_in_hdf5(buf, 1, local_id_array, Nskip); // loads all dm particle ids Nskip += header.npart[1]; } int k; MyIDType local_idcount=0, local_galaxycount=0; i = j = k = 0; printf("starting the assignment loop\n"); fflush(stdout); MyIDType cumulative_subhalo_offset = 0, local_offset = 0; for(i = 0; i < cat->TotNgroups; i++) // for each group { cat->GroupOffset[i] = cumulative_subhalo_offset; local_offset = 0; for(j = 0; j < cat->Group[i].count ; j++) // and each subhalo within the group { for(k = 0; k < cat->Group[i].Subhalo[j].SubhaloLenType[1] ; k++) // and each DM particle within the subhalo { cat->IdList[local_idcount] = local_id_array[cat->GroupOffsetType[1][i] + local_offset + k ]; // can't trust this group offset local_idcount++; #ifdef VERBOSE #ifdef LONGIDS if (i < 2 && j < 2 && k < 2) { printf("cat->GroupOffsetType[1][i] = %lu, local_offset = %d, k = %d, local_id_array[%lu] = %llu\n", cat->GroupOffsetType[1][i], local_offset, k, cat->GroupOffsetType[1][i] + local_offset + k , local_id_array[cat->GroupOffsetType[1][i] + local_offset + k ]); printf("Group %d, Subhalo %d, Particle %d, ID = %llu\n",i,j,k,local_id_array[cat->GroupOffsetType[1][i] + local_offset + k ]); } #else if (i < 10 && j < 10 && k < 10) printf("Group %d, Subhalo %d, Particle %d, ID = %d\n",i,j,k,local_id_array[cat->GroupOffsetType[1][i] + local_offset + k ]); #endif #endif } cat->SubOffset[local_galaxycount] = cumulative_subhalo_offset; cat->SubLen[local_galaxycount] = cat->Group[i].Subhalo[j].SubhaloLenType[1]; cumulative_subhalo_offset += cat->Group[i].Subhalo[j].SubhaloLenType[1]; local_offset += cat->Group[i].Subhalo[j].SubhaloLenType[1]; local_galaxycount++; } #ifdef VERBOSE if(i < 10) { printf("First ID of Group %d can be indexed as:\n",i); printf(" local_id_array[cat->GroupOffsetType[1][%d]] = %llu where cat->GroupOffsetType[1][%d] = %llu\n", i,local_id_array[cat->GroupOffsetType[1][i]],i,cat->GroupOffsetType[1][i]); printf(" cat->IdList[cat->GroupOffset[%d]] = %llu where cat->GroupOffset[%d] = %llu\n\n", i,cat->IdList[cat->GroupOffset[i]], i, cat->GroupOffset[i]); } #endif } printf("finishing the assignment loop\n"); fflush(stdout); myfree(local_id_array); } void save_decendant_list(void) { int i, *data; char buf[1000]; //count matches int NSubhaloMatches = 0, checkcount; for (i = 0; i < CatA.TotNsubhalos; i++) if (CatA.Descendant[i].HaloIndex != -1) NSubhaloMatches++; sprintf(buf, "%s/subhalo_match_%03d.hdf5", MatchOutputDir, SnapshotNum); hsize_t dims[1]; hid_t hdf5_datatype=0, hdf5_dataspace_in_file, hdf5_dataset, hdf5_dataspace_memory; hid_t file = H5Fcreate(buf, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); hid_t hdf5_dataspace = H5Screate(H5S_SCALAR); hid_t hdf5_attribute = H5Acreate(file, "NSubhaloMatches", H5T_NATIVE_INT, hdf5_dataspace, H5P_DEFAULT); H5Awrite(hdf5_attribute, H5T_NATIVE_INT, &NSubhaloMatches); H5Aclose(hdf5_attribute); hid_t atype = H5Tcopy(H5T_C_S1); H5Tset_size(atype, strlen(OutputDir1)); hdf5_attribute = H5Acreate(file, "SubhaloPathFrom", atype, hdf5_dataspace, H5P_DEFAULT); H5Awrite(hdf5_attribute, atype, &OutputDir1); H5Aclose(hdf5_attribute); H5Tset_size(atype, strlen(OutputDir2)); hdf5_attribute = H5Acreate(file, "SubhaloPathTo", atype, hdf5_dataspace, H5P_DEFAULT); H5Awrite(hdf5_attribute, atype, &OutputDir2); H5Aclose(hdf5_attribute); H5Tclose(atype); H5Sclose(hdf5_dataspace); data = mymalloc(sizeof(int) * NSubhaloMatches); checkcount = 0; dims[0] = NSubhaloMatches; hdf5_dataspace_in_file = H5Screate_simple(1, dims, NULL); hdf5_dataspace_memory = H5Screate_simple(1, dims, NULL); hdf5_datatype = H5Tcopy(H5T_NATIVE_INT); hdf5_dataset = H5Dcreate(file, "SubhaloIndexFrom", hdf5_datatype, hdf5_dataspace_in_file, H5P_DEFAULT); for (checkcount = 0, i = 0; i < CatA.TotNsubhalos; i++) if (CatA.Descendant[i].HaloIndex != -1) { data[checkcount++] = i; } if (checkcount != NSubhaloMatches) { printf("BAD\n"); exit(-1); } H5Dwrite(hdf5_dataset, hdf5_datatype, hdf5_dataspace_memory, hdf5_dataspace_in_file, H5P_DEFAULT, data); H5Sclose(hdf5_dataspace_memory); H5Dclose(hdf5_dataset); H5Sclose(hdf5_dataspace_in_file); H5Tclose(hdf5_datatype); dims[0] = NSubhaloMatches; hdf5_dataspace_in_file = H5Screate_simple(1, dims, NULL); hdf5_dataspace_memory = H5Screate_simple(1, dims, NULL); hdf5_datatype = H5Tcopy(H5T_NATIVE_INT); hdf5_dataset = H5Dcreate(file, "SubhaloIndexTo", hdf5_datatype, hdf5_dataspace_in_file, H5P_DEFAULT); for (checkcount = 0, i = 0; i < CatA.TotNsubhalos; i++) if (CatA.Descendant[i].HaloIndex != -1) { data[checkcount++] = CatA.Descendant[i].HaloIndex; } if (checkcount != NSubhaloMatches) { printf("BAD\n"); exit(-1); } H5Dwrite(hdf5_dataset, hdf5_datatype, hdf5_dataspace_memory, hdf5_dataspace_in_file, H5P_DEFAULT, data); H5Sclose(hdf5_dataspace_memory); H5Dclose(hdf5_dataset); H5Sclose(hdf5_dataspace_in_file); H5Tclose(hdf5_datatype); H5Fclose(file); myfree(data); } void delete_id_translation_table(void) { char buf[1000]; sprintf(buf, "%s/sorted_id_table_%03d.hdf5", MatchOutputDir, SnapshotNum); unlink(buf); } void get_id_translation_table(void) { FILE *fd; char buf[1000], buf2[1000], bufA[100], bufB[100]; int filenr, numfiles; MyIDType i, minID, maxID, Nskip = 0; printf("reading IDs from last snapshot\n"); fflush(stdout); sprintf(buf, "%s/sorted_id_table_%03d.hdf5", MatchOutputDir, SnapshotNum); if((fd = fopen(buf, "r"))) { fclose(fd); printf("ok, I'm reading '%s'\n", buf); fflush(stdout); read_num_part_table_hdf5(buf, &TotNumPart ); IdSnapTable = mymalloc(TotNumPart * sizeof(MyIDType)); read_id_translation_table_hdf5(buf, TotNumPart, IdSnapTable ); printf("TotNumPart = %llu \n",TotNumPart); fflush(stdout); printf("finished reading sorted id table!\n"); fflush(stdout); } else { numfiles = 1; for(filenr = 0; filenr < numfiles; filenr++) { if(filenr == 0) printf("Starting to read...\n"); sprintf(buf, "%s/%s_%03d.hdf5", OutputDir1, SnapshotFileBase1, SnapshotNum); sprintf(buf2, "%s/snapdir_%03d/%s_%03d.%d.hdf5", OutputDir1, SnapshotNum, SnapshotFileBase1, SnapshotNum, filenr); printf(" %s\n",buf2); read_snap_header_attributes_in_hdf5(buf2); if(filenr == 0) { numfiles = header.num_files; TotNumPart = //header.npartTotal[0] + (((long long) header.npartTotalHighWord[0]) << (long long) 32) + header.npartTotal[1] + (((long long) header.npartTotalHighWord[1]) << (long long) 32); //header.npartTotal[4] + (((long long) header.npartTotalHighWord[4]) << (long long) 32); long_to_str(bufA, TotNumPart); #ifdef VERBOSE printf("Allocating IdSnapTable...\n"); printf(" header.npartTotal[0] = %d\n",header.npartTotal[0]); printf(" header.npartTotal[1] = %d\n",header.npartTotal[1]); printf(" header.npartTotal[4] = %d\n",header.npartTotal[4]); printf(" TotNumPart = %llu\n\n",TotNumPart); #endif IdSnapTable = mymalloc(TotNumPart * sizeof(MyIDType)); } int parttype; parttype = 1; read_particle_ids_in_hdf5(buf2, parttype , IdSnapTable , Nskip); Nskip += header.npart[parttype]; #ifdef VERBOSE if(filenr == 0) { printf("\n\n Check that ids are being loaded properly...\n"); printf(" First 10 DM particle ids in %s are:\n"); int id_check; for(id_check=0 ; id_check < 10 ; id_check ++) #ifdef LONGIDS printf(" ID[%d] = %llu\n",id_check,IdSnapTable[id_check+Nskip - header.npart[0]]); #else printf(" ID[%d] = %d\n",id_check,IdSnapTable[id_check+Nskip - header.npart[0]]); #endif // LONGIDS } #endif // VERBOSE } printf("TotNumPart=%s\n", bufA); printf("IDs read.\n"); fflush(stdout); for(i = 1, minID = maxID = IdSnapTable[0]; i < TotNumPart; i++) { if(minID > IdSnapTable[i]) minID = IdSnapTable[i]; if(maxID < IdSnapTable[i]) maxID = IdSnapTable[i]; } long_to_str(bufA, minID); long_to_str(bufB, maxID); printf("min-ID=%s max-ID=%s\n", bufA, bufB); printf("sorting IDs\n"); fflush(stdout); qsort(IdSnapTable, Nskip, sizeof(MyIDType), sort_IDType); printf("sorting done\n"); fflush(stdout); printf("writing sorted id table...\n"); fflush(stdout); write_id_translation_table_hdf5(IdSnapTable, TotNumPart); } } void reassign_ids(MyIDType N, MyIDType * ids) { long long i, j, offset, NN; #if defined(_OPENMP) int tid; int nthreads; #endif struct twoids *TwoIDs; printf("reassign IDs...\n"); fflush(stdout); #if defined(_OPENMP) #pragma omp parallel private(tid, nthreads, offset, NN, i, j, TwoIDs) shared(IdSnapTable) #endif { #if defined(_OPENMP) tid = omp_get_thread_num(); nthreads = omp_get_max_threads(); offset = tid * (N / nthreads); NN = (N / nthreads); if(nthreads > 1 && tid == (nthreads - 1)) { NN = N - offset; } #else NN = N; offset = 0; #endif TwoIDs = mymalloc(NN * sizeof(struct twoids)); for(i = 0; i < NN; i++) // load all ids into the TwoID array { TwoIDs[i].id = ids[i + offset]; // the ids at each location TwoIDs[i].ord = i; // the index at each location } qsort(TwoIDs, NN, sizeof(struct twoids), sort_twoids_id); // sort them by id! -> Min id first /* now assign */ j = 0; for(i = 0; i < NN; i++) { while(IdSnapTable[j] < TwoIDs[i].id && j < (TotNumPart - 1)) // this breaks when IdSnapTable[j] == TwoIDs[i].id j++; if(IdSnapTable[j] != TwoIDs[i].id) // if this occurs, should imply that { // - j reached TotNumPart without finding a match... printf("ID mismatch found?\n"); // -> this means there is a particle in the subfind catalog not in the snapshot (IdSnapTable) printf("IdSnapTable[%llu] = %llu TwoIDs[%llu].id = %llu TotNumPart = %llu \n",j,IdSnapTable[j], i,TwoIDs[i].id, TotNumPart); exit(1); } else TwoIDs[i].id = j; // THIS IS THE KEY POINT -- THE NEW ID IS THE INDEX IN IdSnapTable!!! min=0; max=N_dm } /* sort back */ qsort(TwoIDs, NN, sizeof(struct twoids), sort_twoids_ord); // Sort them by orig order -> old first entry is again first for(i = 0; i < NN; i++) ids[i + offset] = TwoIDs[i].id; // repackage them back into the origional array myfree(TwoIDs); } printf("done\n"); fflush(stdout); } void long_to_str(char *s, long long n) { if(n >= 1000000000) sprintf(s, "%d%09d", (int) (n / 1000000000), (int) (n % 1000000000)); else sprintf(s, "%d", (int) n); }
tri_template.c
//------------------------------------------------------------------------------ // tri_template: count triangles in a graph, outer-product method //------------------------------------------------------------------------------ // Compute the # of triangles in a graph, C<A>=A*A in GraphBLAS notation, then // ntri=sum(C). Or, in MATLAB notation, ntri = sum (sum ((A*A).*A)). C=A*A is // computed using an outer-product matrix multiplication. C is not computed // explicitly, but its entries are summed up in the scalar ntri. // A is a binary matrix stored in compressed sparse column form. Its values // are not stored. If A(i,j) is in the pattern, its value is assumed to be 1. // The pattern of column j is in Ai [Ap [j]..Ap[j+1]]. Row indices in the // matrix A must be sorted. Ap[0]=0, and Ap [n] = total number of entries in // the matrix. Ap is of size n+1. // When this function is called, A is a triangular matrix (with no diagonal // entries, or a symmetric permutation of such a triangular matrix. However, // this function works on any matrix. It just computes sum(sum((A*A).*A) in // MATLAB notation, or C<A>=A*A where A is binary, followed by reduce(C), to // scalar. // So it can be used with C<L>=L*L or C<U>=U*U, and ntri is the number of // triangles. It can also be used as C<A>=A*A where A is symmetric, in // which case the # of triangles is ntri/6 (Burkhardt's method). // This file creates eight methods via compile-time definitions: // // BIT: if defined, Mark is a bit vector of size n. Otherwise it is a // bool array of size n. This can help cut workspace if many // threads are used since each thread needs its own Mark array. // PARALLEL: if defined, then OpenMP is used // LOGSEARCH: if binary search is used to reduce the work // Compare this code with tri_simple.c. That code is a simple version of this // algorithm, with the bare essential features. #ifdef BIT #define MARK_TYPE uint8_t #define MARK_SIZE (1 + n/8) #define SET_MARK(i) { Index t=(i) ; Mark [t/8] |= (1 << (t%8)) ; } #define CLEAR_MARK(i) { Mark [(i)/8] = 0 ; } #define COUNT_MARK(i) { Index t=(i) ; if (Mark [t/8] & (1 << t%8)) ntri++ ; } #else #define MARK_TYPE bool #define MARK_SIZE n #define SET_MARK(i) { Mark [i] = 1 ; } #define CLEAR_MARK(i) { Mark [i] = 0 ; } #define COUNT_MARK(i) { ntri += Mark [i] ; } #endif #ifdef LOGSEARCH #ifdef PARALLEL #ifdef BIT #define TRI_FUNCTION tri_logbit_parallel #else #define TRI_FUNCTION tri_logmark_parallel #endif #else #ifdef BIT #define TRI_FUNCTION tri_logbit #else #define TRI_FUNCTION tri_logmark #endif #endif #else #ifdef PARALLEL #ifdef BIT #define TRI_FUNCTION tri_bit_parallel #else #define TRI_FUNCTION tri_mark_parallel #endif #else #ifdef BIT #define TRI_FUNCTION tri_bit #else #define TRI_FUNCTION tri_mark #endif #endif #endif //------------------------------------------------------------------------------ // tri_* function: count the triangles in a graph //------------------------------------------------------------------------------ int64_t TRI_FUNCTION // # of triangles, or -1 if out of memory ( const int64_t *restrict Ap, // column pointers, size n+1 const Index *restrict Ai, // row indices, size nz = Ap [n] const Index n // A is n-by-n #ifdef PARALLEL , const int threads // # of threads , const Index chunk // scheduler chunk size #endif ) { int64_t ntri = 0 ; // # of triangles bool ok = true ; // false if any thread ran out of memory //-------------------------------------------------------------------------- // check if sequential version of same algorithm should be used //-------------------------------------------------------------------------- #ifdef PARALLEL if (n < chunk || threads < 2) { #ifdef LOGSEARCH #ifdef BIT return (tri_logbit (Ap, Ai, n)) ; #else return (tri_logmark (Ap, Ai, n)) ; #endif #else #ifdef BIT return (tri_bit (Ap, Ai, n)) ; #else return (tri_mark (Ap, Ai, n)) ; #endif #endif } #endif //-------------------------------------------------------------------------- // parallel and sequential triangle counting, outer-product method //-------------------------------------------------------------------------- #ifdef PARALLEL #pragma omp parallel num_threads(threads) reduction(+:ntri) reduction(&&:ok) #endif { //---------------------------------------------------------------------- // get workspace //---------------------------------------------------------------------- // each thread needs its own private workspace, Mark [0..n-1] = 0 MARK_TYPE *restrict Mark = calloc (MARK_SIZE, sizeof (MARK_TYPE)) ; if (Mark == NULL) { ok = false ; } else { //------------------------------------------------------------------ // count triangles in each column C(:,j) //------------------------------------------------------------------ #ifdef PARALLEL #pragma omp for schedule(dynamic,chunk) #endif for (Index j = 0 ; j < n ; j++) { //-------------------------------------------------------------- // get column j of A //-------------------------------------------------------------- // A(:,j) has row indices in range jlo..jhi Index jlo, jhi ; if (!tri_lohi (Ap, Ai, j, &jlo, &jhi)) continue ; bool marked = false ; #ifdef LOGSEARCH Index ljnz = jhi - jlo + 1 ; #endif //-------------------------------------------------------------- // compute sum(C(:,j)) where C=(A*A(:,j))*.(A(:,j)) //-------------------------------------------------------------- for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { //---------------------------------------------------------- // A(k,j) is present, compute C(:,j) += A(:,j)*A(k,j) //---------------------------------------------------------- const Index k = Ai [p] ; // A(:,k) has row indices in range klo..khi Index klo, khi ; if (!tri_lohi (Ap, Ai, k, &klo, &khi)) continue ; // skip if A(:,j) and A(:,k) do not overlap if (khi < jlo || klo > jhi) continue ; //---------------------------------------------------------- // binary search if A(:,k) has many nonzeros //---------------------------------------------------------- #ifdef LOGSEARCH // find the intersection between the mask, A(:,j), // and the column A(:,k) Index lknz = khi - klo + 1 ; if (512 * ljnz < lknz) // (4 * ljnz * log2 (lknz) < lknz) { //------------------------------------------------------ // A (:,j) is very sparse compared with A (:,k) ; //------------------------------------------------------ // Do not use the Mark array at all, but use binary // search instead. time is O(ljnz * log (lknz)) int64_t pleft = Ap [k] ; for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { // find i in A (:,k) Index i = Ai [p] ; // binary search of Ai [pleft ... pright] for i int64_t pright = Ap [k+1] - 1 ; while (pleft < pright) { int64_t pmiddle = (pleft + pright) / 2 ; if (i > Ai [pmiddle]) { // if in the list, it appears in // [pmiddle+1..pright] pleft = pmiddle + 1 ; } else { // if in the list, it appears in // [pleft..pmiddle] pright = pmiddle ; } } if (pleft == pright && Ai [pleft] == i) { // found it: A(i,k) and A (k,j) both nonzero // C(i,j) += A (i,k) * A (k,j) ntri++ ; } } continue ; } #endif //---------------------------------------------------------- // linear search //---------------------------------------------------------- if (!marked) { // scatter A(:,j) into Mark for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { // Mark [Ai [p]] = 1 ; SET_MARK (Ai [p]) ; } marked = true ; } for (int64_t pa = Ap [k] ; pa < Ap [k+1] ; pa++) { // C(i,j) += A (i,k) * A (k,j) COUNT_MARK (Ai [pa]) ; } } //-------------------------------------------------------------- // clear the Mark array //-------------------------------------------------------------- if (marked) { for (int64_t p = Ap [j] ; p < Ap [j+1] ; p++) { // Mark [Ai [p]] = 0 ; CLEAR_MARK (Ai [p]) ; } } } //------------------------------------------------------------------ // free workspace //------------------------------------------------------------------ free (Mark) ; } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- return (ok ? ntri : -1) ; } #undef BIT #undef PARALLEL #undef MARK_TYPE #undef MARK_SIZE #undef SET_MARK #undef CLEAR_MARK #undef COUNT_MARK #undef TRI_FUNCTION #undef LOGSEARCH
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 32; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(0,ceild(3*t1-3*t2-2,4)),ceild(3*t1-6,8)),ceild(24*t2-Nz-19,32));t3<=min(min(min(floord(4*Nt+Ny-9,32),floord(12*t1+Ny+15,32)),floord(24*t2+Ny+11,32)),floord(24*t1-24*t2+Nz+Ny+13,32));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-14,16)),ceild(3*t1-30,32)),ceild(24*t2-Nz-115,128)),ceild(32*t3-Ny-115,128));t4<=min(min(min(min(floord(4*Nt+Nx-9,128),floord(12*t1+Nx+15,128)),floord(24*t2+Nx+11,128)),floord(32*t3+Nx+19,128)),floord(24*t1-24*t2+Nz+Nx+13,128));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(128*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),8*t3+6),32*t4+30);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(128*t4,4*t5+4); ubv=min(128*t4+127,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
transposed_spmv.h
/* * Copyright 2014-2015 The University of Queensland * http://www.uq.edu.au * * 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. */ #pragma once #include <thrust/functional.h> #include <cusp/detail/functional.h> #ifndef DIA_CHUNKSIZE #define DIA_CHUNKSIZE 1024 #endif namespace cusp { namespace detail { namespace host { ///////////////////////// // DIA transposed SpMV // ///////////////////////// template <typename Matrix, typename Vector1, typename Vector2, typename UnaryFunction, typename BinaryFunction1, typename BinaryFunction2> void transposed_spmv_dia(const Matrix& A, const Vector1& x, Vector2& y, UnaryFunction initialize, BinaryFunction1 combine, BinaryFunction2 reduce) { typedef typename Matrix::index_type IndexType; //typedef typename Vector2::value_type ValueType; const size_t num_diagonals = A.values.num_cols; #pragma omp parallel for for (size_t ch = 0; ch < A.num_cols; ch += DIA_CHUNKSIZE) { // initialize chunk for (size_t row = ch; row < std::min(ch+DIA_CHUNKSIZE,A.num_cols); row++) { y[row] = initialize(y[row]); } // for each diagonal for (size_t d = 0; d < num_diagonals; d++) { for (IndexType row=ch; row<std::min(ch+DIA_CHUNKSIZE,A.num_cols); row++) { const IndexType col = row - A.diagonal_offsets[d]; if (col >= 0 && col < A.num_rows) { y[row] = reduce(y[row], combine(A.values(col, d), x[col])); } } } } } template <typename Matrix, typename Vector1, typename Vector2> void transposed_spmv_dia(const Matrix& A, const Vector1& x, Vector2& y) { typedef typename Vector2::value_type ValueType; transposed_spmv_dia(A, x, y, cusp::detail::zero_function<ValueType>(), thrust::multiplies<ValueType>(), thrust::plus<ValueType>()); } template <typename Matrix, typename Vector1, typename Vector2, typename UnaryFunction, typename BinaryFunction1, typename BinaryFunction2> void transposed_spmv_cds(const Matrix& A, const Vector1& x, Vector2& y, UnaryFunction initialize, BinaryFunction1 combine, BinaryFunction2 reduce) { typedef typename Matrix::index_type IndexType; typedef typename Vector2::value_type ValueType; const IndexType num_diagonals = A.diagonal_offsets.size(); const IndexType block_size = (IndexType)A.block_size; const IndexType num_cols = (IndexType)A.num_cols; // make chunksize a multiple of block_size const IndexType chunksize = block_size*(DIA_CHUNKSIZE/block_size); // optimisation for special case if (block_size == 2) { #pragma omp parallel for for (IndexType ch = 0; ch < num_cols; ch += chunksize) { for (IndexType row = ch; row < std::min(ch+chunksize,num_cols); row+=2) { ValueType sum1 = initialize(y[row]); ValueType sum2 = initialize(y[row+1]); // for each diagonal block for (IndexType d = 0; d < num_diagonals; d++) { const IndexType col = row - A.diagonal_offsets[d]*2; if (col >= 0 && col < A.num_rows) { sum1 = reduce(sum1, combine(A.values(col, 2*d), x[col])); sum2 = reduce(sum2, combine(A.values(col, 2*d+1),x[col])); sum1 = reduce(sum1, combine(A.values(col+1, 2*d), x[col+1])); sum2 = reduce(sum2, combine(A.values(col+1, 2*d+1),x[col+1])); } } y[row] = sum1; y[row+1] = sum2; } } } else { // block_size!=2 #pragma omp parallel for for (IndexType ch = 0; ch < num_cols; ch += chunksize) { for (IndexType row = ch; row < std::min(ch+chunksize,num_cols); row++) { y[row] = initialize(y[row]); // for each diagonal block for (IndexType d = 0; d < num_diagonals; d++) { const IndexType k = A.diagonal_offsets[d]*block_size; const IndexType col = block_size*(row/block_size) - k; if (col >= 0 && col <= A.num_rows-block_size) { // for each column in block for (IndexType i = 0; i < block_size; i++) { const ValueType& Aij = A.values(col+i, d*block_size+row%block_size); const ValueType& xj = x[col + i]; y[row] = reduce(y[row], combine(Aij, xj)); } } } // diagonals } // rows } // chunks } // block_size } template <typename Matrix, typename Vector1, typename Vector2> void transposed_spmv_cds(const Matrix& A, const Vector1& x, Vector2& y) { typedef typename Vector2::value_type ValueType; if (A.block_size == 1) { transposed_spmv_dia(A, x, y, cusp::detail::zero_function<ValueType>(), thrust::multiplies<ValueType>(), thrust::plus<ValueType>()); } else { transposed_spmv_cds(A, x, y, cusp::detail::zero_function<ValueType>(), thrust::multiplies<ValueType>(), thrust::plus<ValueType>()); } } } // end namespace host } // end namespace detail } // end namespace cusp
calcium_sparks_old.c
#include <math.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "mpi.h" #include "hdf5.h" #include <sys/stat.h> //#define DEBUG_TEST #define DB_PF 0 #define MAX_LINE_LENGTH 80 //#define __PAPI__ #ifdef __PAPI__ #include <papi.h> #endif typedef int(*CONDCF)(int a, int b); #define H5T_DATA_TYPE H5T_NATIVE_SHORT typedef short int hdf5_data_type; #define H5_DATA_LIMIT_0 -32768 // Data type specific #define H5_DATA_LIMIT_1 32767 // Data type specific #define H5_DATA_SIZE H5_DATA_LIMIT_1 - H5_DATA_LIMIT_0 // Data type specific double timing(); void *mpi_malloc ( int id, int bytes); /* IN - Bytes to allocate */ inline double my_random(); double my_min(double* ar, int len); double my_max(double* ar, int len); void stern(double t, double* y0, double* y1, double Ca); void stern_discrete(double dt, int* y0, int* y1, double Ca); void laplace3D (int nx0, int ny0, int nz0, double* C0, int nx1, int ny1, int nz1, double* C1, double alpha);//, int num_threads) void reaction3D (int nx0, int ny0, int nz0, double* Ca, int nx1, int ny1, int nz1, double* buff, double B_tot, double k_on, double k_off, double dt);//, int num_threads) void serca3D (int nx0, int ny0, int nz0, double* Ca_i, int nx1, int ny1, int nz1, double* Ca_SR, double dt, double gamma, double fudge);//, int num_threads) void update_ryr(int h_scale,int nx0, int ny0, int nz0, double* Ca_i, double* Ca_SR, double* Ca_CSQN, double* C10, double* C12, double* C13, double* C14, double k_on_CSQN, double k_off_CSQN, double CSQN_tot, double gamma, double K, double dt, int ryr_len, int* i0_ryr, int* i1_ryr, int* i2_ryr, int csqn_len, int* i0_csqn, int* i1_csqn, int* i2_csqn, int cleft_len, int* i0_cleft, int* i1_cleft, int* i2_cleft,int* cleft_nb, int* states0, int* states1); void store2Dmatrixfile_double_1D(char* outfile, double* ar, int rows, int cols, int x_strid); void store2Dmatrixfile_double_bin(char* outfile, double* ar, int rows, int cols, int x_strid); void transfer_hdf5_data(hdf5_data_type* h5_data, double* ar0, double* ar1, double scale_value, hsize_t* chunk_dims); void store2Dmatrixfile_int_1D(char* outfile, int* ar, int rows, int cols); //int less(int a, int b); //int giant(int a, int b); //int* loadRyRindexfile_int(char* infile, CONDFN cf, int cond); int* loadRyRindexfile_int(char* infile, int* count); int idxinrank(int nx, int ny, int nz, int i0, int i1, int i2, int rank, MPI_Comm comm3d); int idxbl2rank(int nx, int ny, int nz, int i0, int i1, int i2, int* coords, MPI_Comm comm3d); int load_indices_serial(int nx, int ny, int nz, int h, int** i0_ryr, int** i1_ryr, int** i2_ryr, int* ryr_len, int** i0_csqn, int** i1_csqn, int** i2_csqn, int* csqn_len, int** i0_cleft, int** i1_cleft, int** i2_cleft, int** cleft_nb, int* cleft_len, int x_slice_mid,int x_slice_width, int x_slice_num, int use_failing); int IsTrueCleft(int coord_y, int coord_z, int size_y, int size_z, int *i1_csqn, int *i2_csqn, int* y_index, int csqn_len); void BinarySort_two(int* pData, int* vData, int Count); void dichotomy_two(int* pData,int* vData, int left,int right); int distr_ryr_csqn_state(int h, int size_x, int size_y, int size_z, int nx, int ny, int nz, int** i0_ryr, int** i1_ryr, int** i2_ryr, int* ryr_len, int** i0_csqn, int** i1_csqn, int** i2_csqn, int* csqn_len, int** i0_cleft, int** i1_cleft, int** i2_cleft,int** cleft_nb, int* cleft_len, int** states0, int** states1, int x_slice_mid,int x_slice_width, int x_slice_num, MPI_Comm comm3d, MPI_Comm, int use_failing); void readparam(int* iconf, double* conf); void updateBound(double* C00, double* C01, double* C02, double* C03, double* C04, int C_flag, int nx0, int ny0, int nz0, double* yz_sbuf0,double* yz_rbuf0, double* xz_sbuf0,double* xz_rbuf0, double* xy_sbuf0,double* xy_rbuf0, double* yz_sbuf1,double* yz_rbuf1, double* xz_sbuf1,double* xz_rbuf1, double* xy_sbuf1,double* xy_rbuf1, int* neighbor, MPI_Status* ar_status, MPI_Request* ar_send_req, MPI_Request* ar_recv_req, MPI_Comm comm,MPI_Comm comm3d); void putin_sendbuffer_yz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void putin_sendbuffer_xz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void putin_sendbuffer_xy(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void getout_recvbuffer_yz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void getout_recvbuffer_xz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void getout_recvbuffer_xy(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len); void compute_pde_ode(int nx0, int ny0, int nz0, double dt,double gamma, double fudge, double* alpha, double* B_tot, double* k_on, double* k_off, double** C0, double** C1, int div_y); #define NUM_SAVE_SPECIES 5 int save_species[NUM_SAVE_SPECIES] = {0,1,4,5,6}; char* species_names[7] = {"Cai", "CaSR", "CaCMDN", "CaATP", "CaFluo", "CaTRPN", "CaCSQN"}; int main(int argc, char **argv) { int i,j,k; #ifdef __PAPI__ // int Events[] = { PAPI_L1_DCA, PAPI_L1_DCM }; // int Events[] = {PAPI_L3_TCM, PAPI_L3_TCA, PAPI_L2_TCM,PAPI_L2_TCA}; int Events[] = {PAPI_DP_OPS,PAPI_L3_TCM}; int NUM_EVENTS = sizeof(Events)/sizeof(Events[0]); long long res_papi[NUM_EVENTS]; char EventName[128]; int num_hwcntrs = 0; int EventSet = PAPI_NULL; int retval; retval = PAPI_library_init( PAPI_VER_CURRENT ); retval = PAPI_create_eventset( &EventSet ); if (PAPI_add_events( EventSet, Events, NUM_EVENTS) != PAPI_OK){ printf("PAPI_add_events failed\n"); } for (i=0; i<NUM_EVENTS; i++){ res_papi[i] = 0; } #endif double time_main=0.0; double time_comm=0.0; double time_conc=0.0; double time_ryr=0.0; double time_io=0.0; int save_data=0; int use_rand_seed=1; int use_failing=0; int idx; int h_scale=1; int h=30; int div_y=1; int save_binary_file=0; int save_hdf5=0; double T=1.0; double DT=0.05; // plotting time step int TimeStep=2; int size_x, size_y, size_z, my_id, x_domains, y_domains, z_domains; int iconf[12]; double conf[2]; /* MPI variables */ int nproc, ndims; MPI_Comm comm, comm3d; int dims[3]; int periods[3]; int reorganisation = 0; MPI_Datatype matrix_type_oyz, matrix_type_oxz, matrix_type_oxy; int ZN=0, ZP=1, YN=2, YP=3, XN=4, XP=5; int NeighBor[6]; hid_t h5_file_id; hdf5_data_type* h5_data; MPI_Init(&argc, &argv); comm = MPI_COMM_WORLD; MPI_Comm_size(comm, &nproc); MPI_Comm_rank(comm, &my_id); MPI_Info info = MPI_INFO_NULL; if (my_id==0) { readparam(iconf, conf); } MPI_Bcast(iconf, 12, MPI_INT, 0, comm); MPI_Bcast(conf, 2, MPI_DOUBLE, 0, comm); h = iconf[0]; size_x = iconf[1]; size_y = iconf[2]; size_z = iconf[3]; x_domains = iconf[4]; y_domains = iconf[5]; z_domains = iconf[6]; save_data = iconf[7]; use_failing = iconf[8]; save_binary_file = iconf[9]; // Save Ca in binary file instead of ascii file save_hdf5 = iconf[10]; // Save data in hdf5 file format div_y = iconf[11]; // Block size on y direction for cache T = conf[0]; DT = conf[1]; h_scale=30/h; if(use_rand_seed) srand(my_id); char hdf5_dataset_name[200]; char hdf5_group_name[200]; char h5_basename[200]; char outdirname[200]; if(save_hdf5) { sprintf(h5_basename, "output_%d_%d_%d_%d_%d", h, size_x, size_y, size_z, use_failing); } else if(save_binary_file) { sprintf(outdirname, "output_%d_%d_%d_%d_%d_bin", h, size_x, size_y, size_z, use_failing); } else { sprintf(outdirname, "output_%d_%d_%d_%d_%d", h, size_x, size_y, size_z, use_failing); } if(!my_id) { if(save_data && !save_hdf5){ if(access(outdirname,0)) { if (mkdir(outdirname, 0755)==-1) { printf("make directory failed\n"); } else { printf("make directory: %s\n", outdirname); } } else { printf("directory %s existed\n",outdirname); } } } MPI_Barrier(comm); if((my_id==0) && (nproc!=(x_domains*y_domains*z_domains))) { printf("Number of processes not equal to Number of subdomains\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if((my_id==0)&&(size_x%x_domains!=0)) { printf("Number of x_domains is not divisible in scale\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if((my_id==0)&&(size_y%y_domains!=0)) { printf("Number of y_domains is not divisible in scale\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if((my_id==0)&&(size_z%z_domains!=0)) { printf("Number of z_domains is not divisible in scale\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if(((size_y/y_domains)%div_y)!=0){ div_y=1; if(my_id==0){ printf("Warning: div_y is not divisible on each node, so set div_y=1 for default \n"); } } /* Create 3D cartesian grid */ periods[0] = 0; periods[1] = 0; periods[2] = 0; ndims = 3; dims[0]=z_domains; dims[1]=y_domains; dims[2]=x_domains; MPI_Cart_create(comm, ndims, dims, periods, reorganisation, &comm3d); /* MPI variables */ MPI_Status ar_status[6]; MPI_Request ar_send_req[6]; MPI_Request ar_recv_req[6]; int coord[3]; int dim[3]; int period[3]; int mid_coord_x=0; int in_midx_slice=0; int x_slice_num; int x_slice_width; int x_slice_mid; MPI_Cart_get(comm3d, 3, dim, period, coord); x_slice_num=(int)(ceil((double)(size_x*h)/2100.0)); if((size_x%x_slice_num)!=0) { printf("x dimension can not be divided by %d\n", x_slice_num); MPI_Abort(comm,5); } x_slice_width=size_x/x_slice_num; x_slice_mid=(x_slice_width+1)/2; for(i=0;i<x_slice_num;i++) { if(((x_slice_width*i+x_slice_mid)>=(coord[2]*size_x/x_domains))&& ((x_slice_width*i+x_slice_mid)<((coord[2]+1)*size_x/x_domains))){ if(in_midx_slice==1){ printf("dont put two x_slice in a x partition\n"); MPI_Abort(comm,5); } in_midx_slice=1; mid_coord_x=(x_slice_width*i+x_slice_mid)-(coord[2]*size_x/x_domains)+1;//+1 for ghost bound //check x partition thickness, so far, for simplify, dont cut a csqn and no-flux into two x-partitions if((mid_coord_x)<(h_scale+3)||(size_x/x_domains-mid_coord_x)<(h_scale+3)){ printf("x partition is too thine for CSQN and cleft extend \n"); MPI_Abort(comm,5); } } } //printf("Rank: %d, coord: [%d, %d, %d]\n", my_id, coord[0], coord[1], coord[2]); /* Identify process neighbors */ NeighBor[0] = MPI_PROC_NULL; NeighBor[1] = MPI_PROC_NULL; NeighBor[2] = MPI_PROC_NULL; NeighBor[3] = MPI_PROC_NULL; NeighBor[4] = MPI_PROC_NULL; NeighBor[5] = MPI_PROC_NULL; /* Left/West and right/Est neigbors Z direction*/ MPI_Cart_shift(comm3d,0,1,&NeighBor[ZN],&NeighBor[ZP]); /* Bottom/South and Upper/North neigbors Y direction*/ MPI_Cart_shift(comm3d,1,1,&NeighBor[YN],&NeighBor[YP]); /* Zdown/South and Zup/North neigbors X direction*/ MPI_Cart_shift(comm3d,2,1,&NeighBor[XN],&NeighBor[XP]); //-------------------------------------------------------------------- int nx=(size_x/x_domains); int ny=(size_y/y_domains); int nz=(size_z/z_domains); int nx0, ny0, nz0; int nx1, ny1, nz1; nx0=nx+2; ny0=ny+2; nz0=nz+2; nx1=nx+2; ny1=ny+2; nz1=nz+2; int len; len=nx0*ny0*nz0; /* Create matrix data types to communicate */ MPI_Type_vector(ny, nz, nz0, MPI_DOUBLE, &matrix_type_oyz); MPI_Type_commit(&matrix_type_oyz); /* Create matrix data type to communicate on vertical Oxz plan */ MPI_Type_vector(nx, nz, ny0*nz0, MPI_DOUBLE, &matrix_type_oxz); MPI_Type_commit(&matrix_type_oxz); /* Create matrix data type to communicate on vertical Oxy plan */ MPI_Datatype matrix_type_liney; MPI_Type_vector(ny, 1, nz0, MPI_DOUBLE, &matrix_type_liney); MPI_Type_commit(&matrix_type_liney); // MPI_Type_vector(nx*ny, 1, nz0, MPI_DOUBLE, &matrix_type_oxy); MPI_Type_hvector(nx, 1, ny0*nz0*sizeof(double), matrix_type_liney, &matrix_type_oxy); MPI_Type_commit(&matrix_type_oxy); if(!my_id) printf("Simulation Begin!\n"); //Define where the RyRs are: int* i0_ryr; int* i1_ryr; int* i2_ryr; int* i0_csqn; int* i1_csqn; int* i2_csqn; int* i0_cleft; int* i1_cleft; int* i2_cleft; int* cleft_nb; int ryr_len; int csqn_len; int cleft_len; int* states0; int* states1; h_scale=distr_ryr_csqn_state( h, size_x, size_y, size_z, nx, ny, nz, &i0_ryr, &i1_ryr, &i2_ryr, &ryr_len, &i0_csqn, &i1_csqn, &i2_csqn, &csqn_len, &i0_cleft, &i1_cleft, &i2_cleft, &cleft_nb,&cleft_len, &states0, &states1, x_slice_mid,x_slice_width, x_slice_num, comm3d, comm, use_failing); // store2Dmatrixfile_int_1D("i0.txt",i0,n_ryr,1); // store2Dmatrixfile_int_1D("i1.txt",i1,n_ryr,1); // store2Dmatrixfile_int_1D("i2.txt",i2,n_ryr,1); double Vfraction; //first set the numbers of RyR in a CaRU; //All CaRU placed mid-sarcomere Vfraction=(30.0/h)*(30.0/h)*(30.0/h); // scaling of RyR when changing dx // Set constants and dt based on these: double D_i=250e3; // 220e3 double D_SR=73e3; // 73.3e3; double D_ATP=140e3; double D_CMDN=22e3; double D_Fluo=42e3; double dt=(1./6)*h*h/D_i; double alpha_i = dt*D_i/(h*h); double Ca0 = 140e-3; double CaSR0 = 1.3e3; double* Ca_i; Ca_i=(double*)malloc(len*sizeof(double)); for ( i = 0; i < len; i += 1 ) { Ca_i[i]=Ca0; } double alpha_SR = dt*D_SR/(h*h); double* Ca_SR; Ca_SR=(double*)malloc(len*sizeof(double)); for ( i = 0; i < len; i += 1 ) { Ca_SR[i]=CaSR0; } double k_on_CMDN = 34e-3; double k_off_CMDN = 238e-3; double CMDN_tot = 24; double alpha_CMDN = dt*D_CMDN/(h*h); double k_on_ATP = 255e-3; double k_off_ATP = 45; double ATP_tot = 455; double alpha_ATP = dt*D_ATP/(h*h); double k_on_Fluo = 110e-3; double k_off_Fluo = 110e-3; double Fluo_tot = 25; // 25; double alpha_Fluo = dt*D_Fluo/(h*h); double k_on_TRPN = 32.7e-3; double k_off_TRPN = 19.6e-3; // 26.16e-3; double TRPN_tot = 70; // 50; double k_on_CSQN = 102e-3; double k_off_CSQN = 65; double CSQN_tot = 30e3; double alpha[7]; double k_on[7]; double k_off[7]; double B_tot[7]; alpha[0]=alpha_i; alpha[1]=alpha_SR; alpha[2]=alpha_CMDN; alpha[3]=alpha_ATP; alpha[4]=alpha_Fluo; alpha[5]=0; alpha[6]=0; k_on[0]=0 ; k_on[1]= 0; k_on[2]= k_on_CMDN; k_on[3]=k_on_ATP ; k_on[4]=k_on_Fluo ; k_on[5]=k_on_TRPN; k_on[6]=k_on_CSQN; k_off[0]=0 ; k_off[1]= 0; k_off[2]=k_off_CMDN; k_off[3]=k_off_ATP; k_off[4]=k_off_Fluo; k_off[5]=k_off_TRPN; k_off[6]=k_off_CSQN; B_tot[0]=0 ; B_tot[1]= 0; B_tot[2]=CMDN_tot ; B_tot[3]=ATP_tot ; B_tot[4]=Fluo_tot ; B_tot[5]=TRPN_tot; B_tot[6]=CSQN_tot; // Calculate steady state IC for the buffers based on Ca_i ... double Ca_CMDN0=B_tot[2]*Ca0/(Ca0+k_off[2]/k_on[2]); double Ca_ATP0 =B_tot[3]*Ca0/(Ca0+k_off[3]/k_on[3]); double Ca_Fluo0=B_tot[4]*Ca0/(Ca0+k_off[4]/k_on[4]); double Ca_TRPN0=B_tot[5]*Ca0/(Ca0+k_off[5]/k_on[5]); // and Ca_SR: double Ca_CSQN0 = CSQN_tot*Ca_SR[0]/(Ca_SR[0] + k_off_CSQN/k_on_CSQN); double init_values[7] = {Ca0, CaSR0, Ca_CMDN0, Ca_ATP0, Ca_Fluo0, Ca_TRPN0, Ca_CSQN0}; //printf("%f %f %f %f %f \n ", Ca_ATP0, Ca_CMDN0, Ca_Fluo0, Ca_TRPN0, Ca_CSQN0); if(my_id==0) printf("cubiod_c: h:%d size_x:%d size_y:%d size_z:%d dt:%f, T:%f, TimeStep:%d, DT:%f outfilenum:%d, x_slice_num:%d, use_failing:%d, div_y:%d, save_binary:%d \n", h, size_x, size_y, size_z,dt,T, (int)(T/dt),DT,(int)(T/DT)*save_data,x_slice_num,use_failing, div_y,save_binary_file); // Allocate the data structure for the solution double *Ca_ATP ; double *Ca_CMDN ; double *Ca_Fluo ; double *Ca_TRPN ; double *Ca_CSQN ; Ca_ATP =(double*)malloc(len*sizeof(double)); Ca_CMDN=(double*)malloc(len*sizeof(double)); Ca_Fluo=(double*)malloc(len*sizeof(double)); Ca_TRPN=(double*)malloc(len*sizeof(double)); Ca_CSQN=(double*)malloc(len*sizeof(double)); for ( i = 0; i < len; i += 1 ) { Ca_ATP[i] = Ca_ATP0; Ca_CMDN[i] = Ca_CMDN0; Ca_Fluo[i] = Ca_Fluo0; Ca_TRPN[i] = Ca_TRPN0; Ca_CSQN[i] = Ca_CSQN0; } double* C0[7]; double* C1[7]; double* C_temp; C0[0]=(double*)malloc(len*sizeof(double)); C1[0]=Ca_i; memcpy(C0[0],C1[0],len*sizeof(double)); C0[1]=(double*)malloc(len*sizeof(double)); C1[1]=Ca_SR; memcpy(C0[1],C1[1],len*sizeof(double)); C0[2]=(double*)malloc(len*sizeof(double)); C1[2]=Ca_CMDN; memcpy(C0[2],C1[2],len*sizeof(double)); C0[3]=(double*)malloc(len*sizeof(double)); C1[3]=Ca_ATP; memcpy(C0[3],C1[3],len*sizeof(double)); C0[4]=(double*)malloc(len*sizeof(double)); C1[4]=Ca_Fluo; memcpy(C0[4],C1[4],len*sizeof(double)); C0[5]=(double*)malloc(len*sizeof(double)); C1[5]=Ca_TRPN; memcpy(C0[5],C1[5],len*sizeof(double)); C0[6]=(double*)malloc(len*sizeof(double)); C1[6]=Ca_CSQN; memcpy(C0[6],C1[6],len*sizeof(double)); //Ca = [[Ca_i.copy(), Ca_i ], // [Ca_SR.copy(), Ca_SR ], // [Ca_CMDN.copy(), Ca_CMDN], // [Ca_ATP.copy(), Ca_ATP ], // [Ca_Fluo.copy(), Ca_Fluo], // [Ca_TRPN, Ca_TRPN], // [Ca_CSQN, Ca_CSQN]] double gamma = 0.02; // SR volume fraction int cai=0; int sri=1; // int cmdni=2; // int atpi=3; // int fluoi=4; // int trpni=5; int csqni=6; double fraction[7]={1,1,1,1,1,1,1}; fraction[1]=gamma; fraction[6]=gamma; // Ryr conductance: double k_s = (Vfraction)*150/2; // 1/ms, based on 0.5pA of Ca2+ into (30nm)^3. double K = exp(-k_s*dt*(1+1/gamma)); // factor need in the integration below if(my_id==0){ printf("dt = dt: %e\n", dt); printf("k_s = (Vfraction)*150/2: %e\n", k_s); printf("K = exp(-k_s*dt*(1+1/gamma)): %e\n", K); } double t=0; int counter=0; // int mean[7]; time_main-=timing(); FILE *fpdata; char meanfile[200]; if (save_hdf5) sprintf(meanfile,"%s_mean.txt", h5_basename); else sprintf(meanfile,"%s/mean.txt", outdirname); if(!my_id){ if(save_data){ if ((fpdata=fopen(meanfile, "w"))==NULL) { printf("failed open output file "); printf("%s", meanfile); printf(" ! \n "); exit(0); } } } // H5 Setup if (save_hdf5) { char h5_data_file[200]; // Set up file access property list with parallel I/O access // property list identifier hid_t plist_id = H5Pcreate(H5P_FILE_ACCESS); H5Pset_fapl_mpio(plist_id, comm, info); sprintf(h5_data_file, "%s.h5", h5_basename); // Create a new file collectively and release property list identifier. h5_file_id = H5Fcreate(h5_data_file, H5F_ACC_TRUNC, H5P_DEFAULT, plist_id); H5Pclose(plist_id); const int data_rank = 2; hsize_t dimsf[2] = {size_y, size_z}; /* dataset dimensions */ hsize_t chunk_dims[2] = {ny, nz}; /* chunk dimensions */ // Offset into dataset based on the MPI coord from MPI_Cart_get hsize_t h5_offset[2] = {coord[1]*nz, coord[0]*ny}; hsize_t h5_count[2] = {1, 1}; hsize_t data_size=ny*nz; h5_data = (hdf5_data_type*)malloc(data_size*sizeof(hdf5_data_type)); if (!my_id) { printf("Total data size per species: %zu, %zu\n", dimsf[0], dimsf[1]); printf("Total data size per chunk per species: %zu, %zu\n", chunk_dims[0], chunk_dims[1]); } printf("rank %d | h5 offset [%zu, %zu]\n", my_id, h5_offset[0], h5_offset[1]); // Create data space for the datatype limits hsize_t dims = 1; hid_t attr_space = H5Screate_simple(1, &dims, NULL); // Create a time attribute hid_t limit_id = H5Acreate(h5_file_id, "data_type_size", H5T_NATIVE_DOUBLE, attr_space, H5P_DEFAULT, H5P_DEFAULT); // Write the attribute data double data_type_size = (double)H5_DATA_SIZE; herr_t status = H5Awrite(limit_id, H5T_NATIVE_DOUBLE, &data_type_size); // Cleanup H5Aclose(limit_id); H5Sclose(attr_space); // Save hard coded data ranges for (i=0; i<NUM_SAVE_SPECIES; i++) { // Get species int species = save_species[i]; // Create data scale attribute sprintf(hdf5_dataset_name, "%s_scale", species_names[species]); // Create data space for the species scale attribute hsize_t dims = 1; hid_t attr_space = H5Screate_simple(1, &dims, NULL); // Create a time attribute hid_t scale_id = H5Acreate(h5_file_id, hdf5_dataset_name, H5T_NATIVE_DOUBLE, attr_space, H5P_DEFAULT, H5P_DEFAULT); // Write the attribute data herr_t status = H5Awrite(scale_id, H5T_NATIVE_DOUBLE, &init_values[species]); // Cleanup H5Aclose(scale_id); H5Sclose(attr_space); // Create init value attribute sprintf(hdf5_dataset_name, "%s_init", species_names[species]); // Create data space for the species init attribute dims = 1; attr_space = H5Screate_simple(1, &dims, NULL); // Create a time attribute hid_t init_id = H5Acreate(h5_file_id, hdf5_dataset_name, H5T_NATIVE_DOUBLE, attr_space, H5P_DEFAULT, H5P_DEFAULT); // Write the attribute data status = H5Awrite(init_id, H5T_NATIVE_DOUBLE, &init_values[species]); // Cleanup H5Aclose(init_id); H5Sclose(attr_space); } } double* yz_sbuf0; double* yz_rbuf0; double* xz_sbuf0; double* xz_rbuf0; double* xy_sbuf0; double* xy_rbuf0; double* yz_sbuf1; double* yz_rbuf1; double* xz_sbuf1; double* xz_rbuf1; double* xy_sbuf1; double* xy_rbuf1; yz_sbuf0=(double*)mpi_malloc(my_id,5*ny*nz*sizeof(double)); xz_sbuf0=(double*)mpi_malloc(my_id,5*nx*nz*sizeof(double)); xy_sbuf0=(double*)mpi_malloc(my_id,5*nx*ny*sizeof(double)); yz_sbuf1=(double*)mpi_malloc(my_id,5*ny*nz*sizeof(double)); xz_sbuf1=(double*)mpi_malloc(my_id,5*nx*nz*sizeof(double)); xy_sbuf1=(double*)mpi_malloc(my_id,5*nx*ny*sizeof(double)); yz_rbuf0=(double*)mpi_malloc(my_id,5*ny*nz*sizeof(double)); xz_rbuf0=(double*)mpi_malloc(my_id,5*nx*nz*sizeof(double)); xy_rbuf0=(double*)mpi_malloc(my_id,5*nx*ny*sizeof(double)); yz_rbuf1=(double*)mpi_malloc(my_id,5*ny*nz*sizeof(double)); xz_rbuf1=(double*)mpi_malloc(my_id,5*nx*nz*sizeof(double)); xy_rbuf1=(double*)mpi_malloc(my_id,5*nx*ny*sizeof(double)); #ifdef __PAPI__ if ( PAPI_start( EventSet ) != PAPI_OK){ printf("PAPI_read_counters failed\n"); } #endif //settime //T=1000*dt; //for ( T = 0; T < TimeStep; T += 1 ) int t_counter=0; while(t<T) //while(0) { t+=dt; t_counter++; time_comm-=timing(); updateBound(C0[0], C0[1], C0[2], C0[3], C0[4], t_counter, nx0, ny0, nz0, yz_sbuf0,yz_rbuf0, xz_sbuf0,xz_rbuf0, xy_sbuf0,xy_rbuf0, yz_sbuf1,yz_rbuf1, xz_sbuf1,xz_rbuf1, xy_sbuf1,xy_rbuf1, NeighBor, ar_status,ar_send_req,ar_recv_req, comm, comm3d); time_comm+=timing(); // Diffusion update time_conc-=timing(); // Change to use a faster computing function compute_pde_ode(nx0, ny0, nz0, dt, gamma, 1e-4, alpha, B_tot, k_on, k_off, C0, C1, div_y); // for ( i = 0; i < 5; i += 1 ) { // laplace3D(nx0,ny0,nz0,C0[i],nx1,ny1,nz1,C1[i],alpha[i]); // } // for ( i = 2; i < 6; i += 1 ) { // reaction3D(nx1,ny1,nz1,C1[cai],nx1,ny1,nz1,C1[i],B_tot[i],k_on[i],k_off[i],dt); // } // serca3D(nx1,ny1,nz1, C1[cai],nx1,ny1,nz1, C1[sri], dt, gamma, 1.0); time_conc+=timing(); // Update at RyRs, one at the time time_ryr-=timing(); update_ryr(h_scale, nx0, ny0, nz0, C1[cai], C1[sri], C1[csqni], C1[0],C1[2],C1[3],C1[4], k_on_CSQN, k_off_CSQN,CSQN_tot, gamma, K, dt, ryr_len, i0_ryr, i1_ryr, i2_ryr, csqn_len, i0_csqn, i1_csqn, i2_csqn, cleft_len, i0_cleft, i1_cleft, i2_cleft,cleft_nb, states0, states1); time_ryr+=timing(); double sum_c_i_root[7]; double sum_c_i[7]; double cai_min; double cai_min_root=0.0; double cai_max; double cai_max_root=1.0; double sm; double ca[8]; char caoutfile[100]; if ((fmod(t,DT)<dt)||(t==dt)){ time_io-=timing(); for(idx=0; idx<7; idx++){ sum_c_i[idx]=0.0; for ( i = 1; i <= nx; i += 1 ) for ( j = 1; j <= ny; j += 1 ) for ( k = 1; k <= nz; k += 1 ) sum_c_i[idx]+=C1[idx][i*ny0*nz0+j*nz0+k]; } cai_min=my_min(C1[cai],len); cai_max=my_max(C1[cai],len); /* reduce operation comm*/ MPI_Reduce(&sum_c_i[0], &sum_c_i_root[0], 7, MPI_DOUBLE, MPI_SUM, 0, comm); MPI_Reduce(&cai_min, &cai_min_root, 1, MPI_DOUBLE, MPI_MIN, 0, comm); MPI_Reduce(&cai_max, &cai_max_root, 1, MPI_DOUBLE, MPI_MAX, 0, comm); if(!my_id){ sm = 0; ca[0] = t; if(save_data) fprintf(fpdata,"%f ", ca[0]); for(idx=0; idx<7; idx++){ sm += fraction[idx]*sum_c_i_root[idx]; ca[idx+1] = sum_c_i_root[idx]/((double)nx*x_domains*(double)ny*y_domains*(double)nz*z_domains); if(DB_PF){ printf("ca[%d]: %f , sum : %f, nx ny nz: %d %d %d \n",idx+1, ca[idx+1], sum_c_i_root[idx],nx*x_domains,ny*y_domains,nz*z_domains); } if(save_data) fprintf(fpdata,"%f ", ca[idx+1]); } if(save_data) fprintf(fpdata,"\n "); printf("%3d, %.3f, %3.2f, %7.2f, %3.2f, %4.2f, %.2f \n", counter, t, ca[1], ca[2], cai_min_root, cai_max_root, sm); } if(save_data && in_midx_slice) { // If saving in hdf5 if (save_hdf5) { hsize_t dimsf[2] = {size_y, size_z}; /* dataset dimensions */ hsize_t chunk_dims[2] = {ny, nz}; /* chunk dimensions */ hsize_t h5_offset[2] = {coord[1]*nz, coord[0]*ny}; hsize_t h5_count[2] = {1, 1}; // Create group name sprintf(hdf5_group_name, "/data_%d", counter); hid_t group_id = H5Gcreate(h5_file_id, hdf5_group_name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); // Create data space for the time attribute hsize_t dims = 1; hid_t attr_space = H5Screate_simple(1, &dims, NULL); // Create a time attribute hid_t time_id = H5Acreate(group_id, "time", H5T_NATIVE_DOUBLE, attr_space, H5P_DEFAULT, H5P_DEFAULT); // Write the attribute data double time_data = counter*DT; herr_t status = H5Awrite(time_id, H5T_NATIVE_DOUBLE, &time_data); // Cleanup H5Aclose(time_id); H5Sclose(attr_space); for (i=0; i<NUM_SAVE_SPECIES; i++) { // Get species int species = save_species[i]; sprintf(hdf5_dataset_name, "%s/%s", hdf5_group_name, species_names[species]); // file and dataset identifiers hid_t filespace = H5Screate_simple(2, dimsf, NULL); hid_t memspace = H5Screate_simple(2, chunk_dims, NULL); // Create chunked dataset. hid_t plist_id = H5Pcreate(H5P_DATASET_CREATE); H5Pset_chunk(plist_id, 2, chunk_dims); // Create compression filter (Not supported in parallel yet...) //unsigned int gzip_level = 9; //herr_t status = H5Pset_filter(plist_id, H5Z_FILTER_DEFLATE, // H5Z_FLAG_OPTIONAL, 1, &gzip_level); hid_t dset_id = H5Dcreate(h5_file_id, hdf5_dataset_name, H5T_DATA_TYPE, filespace, H5P_DEFAULT, plist_id, H5P_DEFAULT); H5Pclose(plist_id); H5Sclose(filespace); // Select hyperslab in the file. filespace = H5Dget_space(dset_id); status = H5Sselect_hyperslab(filespace, H5S_SELECT_SET, h5_offset, NULL, h5_count, chunk_dims); // Copy data to h5_data transfer_hdf5_data(h5_data, &(C0[species][ny0*nz0*mid_coord_x]), &(C1[species][ny0*nz0*mid_coord_x]), init_values[species], chunk_dims); // Create property list for collective dataset write. plist_id = H5Pcreate(H5P_DATASET_XFER); H5Pset_dxpl_mpio(plist_id, H5FD_MPIO_COLLECTIVE); status = H5Dwrite(dset_id, H5T_DATA_TYPE, memspace, filespace, plist_id, h5_data); // Close/release resources. H5Dclose(dset_id); H5Sclose(filespace); H5Sclose(memspace); H5Pclose(plist_id); } H5Gclose(group_id); } // No HDF5 else { // Get species int species = save_species[i]; for (i=0; i<NUM_SAVE_SPECIES; i++) { sprintf(caoutfile, "%s/Ca%d_T%d_rank%d_%d_%d.np", outdirname, species, counter, coord[2], coord[1], coord[0]); if(save_binary_file) store2Dmatrixfile_double_bin(caoutfile, C1[species], ny0, nz0, mid_coord_x); else store2Dmatrixfile_double_1D(caoutfile, C1[species], ny0, nz0, mid_coord_x); } } } counter += 1; } // # Update Ca for(i=0;i<7;i++){ C_temp=C0[i]; C0[i]=C1[i]; C1[i]=C_temp; } MPI_Waitall(6, ar_send_req, ar_status); } time_main+=timing(); if(my_id==0){ if(save_data) fclose(fpdata); printf("cubiod_c: h:%d size_x:%d size_y:%d size_z:%d dt:%f, T:%f, TimeStep:%d, DT:%f, x_slice_num:%d\n", h, size_x, size_y, size_z,dt,T,(int)(T/dt),DT,x_slice_num); printf("nx0:%d ny0:%d nz0:%d size/array:%7.3f MB total size:%7.3f MB\n", nx0,ny0,nz0,nx0*ny0*nz0*8*1e-6,nx0*ny0*nz0*8*1e-6*12); #ifdef __PAPI__ if ( PAPI_stop( EventSet, res_papi ) != PAPI_OK){ printf("PAPI_accum_counters failed\n"); } for (i = 0; i<NUM_EVENTS; i++){ PAPI_event_code_to_name(Events[i], EventName); printf("PAPI Event name: %s, value: %lld\n", EventName, res_papi[i]); } #endif printf("computing time: %7.3f \n", time_conc); printf("updateryr time: %7.3f \n", time_ryr); printf("communica time: %7.3f \n", time_comm); printf("main time: %7.3f \n", time_main); #ifdef __PAPI__ printf("PAPI Performanc/core: %7.3f GFLOPS\n", res_papi[0]/1e9/time_conc); #endif } if (save_hdf5) { H5Fclose(h5_file_id); free(h5_data); } for(i=0;i<5;i++){ free(C0[i]); free(C1[i]); } free(C0[6]); free(C0[5]); free(i0_ryr); free(i1_ryr); free(i2_ryr); free(i0_csqn); free(i1_csqn); free(i2_csqn); free(i0_cleft); free(i1_cleft); free(i2_cleft); free(cleft_nb); MPI_Finalize(); return 0; } void laplace3D (int nx0, int ny0, int nz0, double* C0, int nx1, int ny1, int nz1, double* C1, double alpha)//, int num_threads) { // Set num threads // omp_set_num_threads(num_threads); // Local variables int i, j, k; double C0_tmp; // Main kernel loop // #pragma omp parallel for private(i, j, k, C0_tmp) //collapse(3) for (i=1; i<nx0-1; i++) { for (j=1; j<ny0-1; j++) { for (k=1; k<nz0-1; k++) { // Main kernel C0_tmp = -6*C0[i*nz0*ny0+j*nz0+k] + C0[(i-1)*nz0*ny0+j*nz0+k] + C0[(i+1)*nz0*ny0+j*nz0+k] + C0[i*nz0*ny0+(j-1)*nz0+k] + C0[i*nz0*ny0+(j+1)*nz0+k] + C0[i*nz0*ny0+j*nz0+k-1] + C0[i*nz0*ny0+j*nz0+k+1]; // Put value back into return array with offset to indices C1[i*nz1*ny1+j*nz1+k] = C0[i*nz1*ny1+j*nz1+k] + C0_tmp*alpha; } } } } void reaction3D (int nx0, int ny0, int nz0, double* Ca, int nx1, int ny1, int nz1, double* buff, double B_tot, double k_on, double k_off, double dt)//, int num_threads) { // Set num threads // omp_set_num_threads(num_threads); // Local variables int i, j, k; double J; // Use pointers reducing indexing into memory to once double* Ca_ijk; double* buff_ijk; // Main kernel loop // #pragma omp parallel for private(i, j, k, J, Ca_ijk, buff_ijk) //collapse(3) for (i=1; i<nx0-1; i++) { for (j=1; j<ny0-1; j++) { for (k=1; k<nz0-1; k++) { // Main kernel Ca_ijk = &Ca[i*nz0*ny0+j*nz0+k]; buff_ijk = &buff[i*nz0*ny0+j*nz0+k]; J = k_on*(B_tot - *buff_ijk)*(*Ca_ijk) - k_off*(*buff_ijk); *Ca_ijk -= dt*J; *buff_ijk += dt*J; } } } } void serca3D (int nx0, int ny0, int nz0, double* Ca_i, int nx1, int ny1, int nz1, double* Ca_SR, double dt, double gamma, double fudge)//, int num_threads) { // Set num threads // omp_set_num_threads(num_threads); // Local variables int i, j, k; double J; // Use pointers reducing indexing into memory to once double Ca_i2_ijk; double Ca_SR2_ijk; // Main kernel loop // #pragma omp parallel for private(i, j, k, J, Ca_i2_ijk, Ca_SR2_ijk) //collapse(3) for (i=1; i<nx0-1; i++) { for (j=1; j<ny0-1; j++) { for (k=1; k<nz0-1; k++) { // Main kernel Ca_i2_ijk = Ca_i[i*nz0*ny0+j*nz0+k]; Ca_SR2_ijk = Ca_SR[i*nz0*ny0+j*nz0+k]; Ca_i2_ijk *= Ca_i2_ijk; Ca_SR2_ijk *= Ca_SR2_ijk; J = fudge*(570997802.885875*Ca_i2_ijk - 0.0425239333622699*Ca_SR2_ijk)/(106720651.206402*Ca_i2_ijk + 182.498197548666*Ca_SR2_ijk + 5.35062954944879); Ca_i[i*nz0*ny0+j*nz0+k] -= dt*J; Ca_SR[i*nz0*ny0+j*nz0+k] += dt*J/gamma; } } } } void update_ryr(int h_scale,int nx0, int ny0, int nz0, double* Ca_i, double* Ca_SR, double* Ca_CSQN, double* C10, double* C12, double* C13, double* C14, double k_on_CSQN, double k_off_CSQN, double CSQN_tot, double gamma, double K, double dt, int ryr_len, int* i0_ryr, int* i1_ryr, int* i2_ryr, int csqn_len, int* i0_csqn, int* i1_csqn, int* i2_csqn, int cleft_len, int* i0_cleft, int* i1_cleft, int* i2_cleft,int* cleft_nb, int* states0, int* states1) { int i,j; int x_copy_from; int x,y,z; int nb_y,nb_z; int idx,idx_cleft,idx_csqn; double J; int open; double c0,c1; //extend csqn on x direction // for(j=(1-h_scale);j<h_scale;j++){ //extend cdqn on x+ direction for 30nm for(j=0;j<h_scale;j++){ for(i=0;i<csqn_len;i+=1){ x=i0_csqn[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_csqn[i]; z=i2_csqn[i]; idx=x*ny0*nz0+y*nz0+z; //CSQN step: J = k_on_CSQN*(CSQN_tot - Ca_CSQN[idx])*Ca_SR[idx] - k_off_CSQN*Ca_CSQN[idx]; Ca_SR[idx] -= dt*J; Ca_CSQN[idx] += dt*J; } } //add no_flux boundary by copy the neighbour's value on no_flux voxel //add x+ front no-flux plane on ryr with +1 offset, and copy from -1 x-plane(where ryr is on) j=1; x_copy_from=-1; for(i=0;i<csqn_len;i+=1){ x=i0_csqn[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_csqn[i]; z=i2_csqn[i]; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =(x+x_copy_from)*ny0*nz0+y*nz0+z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } //add x+ back no-flux plane on ryr with h_scale offset, and copy from +1 x-plane(outside of csqn) if(h_scale==2)//15 nm j=h_scale+1;//guarantee that there is at least one voxel inner the no-flux boundary else//5nm 3mn 1nm, j=h_scale; x_copy_from=+1; for(i=0;i<csqn_len;i+=1){ x=i0_csqn[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_csqn[i]; z=i2_csqn[i]; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =(x+x_copy_from)*ny0*nz0+y*nz0+z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } //extend y-z plane no_flux boundary along x+ direction with +1 offset and copy value from outside of CSQN by cleft_nb index int k; if(h_scale==2)//15 nm k=1;//guarantee that there is at least one voxel inner the no-flux boundary else//5nm 3mn 1nm, k=0; for(j=2;j<h_scale+k;j++){ for(i=0;i<cleft_len;i+=1){ x=i0_cleft[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_cleft[i]; z=i2_cleft[i]; nb_y=cleft_nb[i]/8-1; nb_z=cleft_nb[i]%8-1; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =x*ny0*nz0+(y+nb_y)*nz0+z+nb_z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } } //add x- front no-flux plane on ryr with -h_scale/2(15nm) offset, and copy from +1 x-plane(t-tubule) j=0-h_scale/2; x_copy_from=1; for(i=0;i<csqn_len;i+=1){ x=i0_csqn[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_csqn[i]; z=i2_csqn[i]; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =(x+x_copy_from)*ny0*nz0+y*nz0+z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } //add x- back no-flux plane on ryr with -h_scale/2+1 offset, and copy from -1 x-plane(t-tubule) /* if(h_scale=2) j=0-h_scale/2-h_scale; else j=0-h_scale/2-h_scale+1; */ /* how thick should t-tubule be? now, just set it 2 lines on x- direction */ // j=0-h_scale/2-h_scale-1; j=0-h_scale/2-1; x_copy_from=-1; for(i=0;i<csqn_len;i+=1){ x=i0_csqn[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_csqn[i]; z=i2_csqn[i]; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =(x+x_copy_from)*ny0*nz0+y*nz0+z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } /* how thick should t-tubule be? */ /* //extend y-z plane no_flux boundary along x- direction with +1 offset and copy value from outside of CSQN by cleft_nb index int k; if(h_scale==2)//15 nm k=1;//guarantee that there is at least one voxel inner the no-flux boundary else//5nm 3mn 1nm, k=0; for(j=0-h_scale/2-1;j>0-h_scale/2-h_scale+1-k;j--){ for(i=0;i<cleft_len;i+=1){ x=i0_cleft[i]+j; #ifdef DEBUG_TEST if((x<0)||x>(nx0-1)) { printf("wrong csqn x index\n"); exit(0); } #endif y=i1_cleft[i]; z=i2_cleft[i]; nb_y=cleft_nb[i]/8-1; nb_z=cleft_nb[i]%8-1; idx_cleft=x*ny0*nz0+y*nz0+z; idx_csqn =x*ny0*nz0+(y+nb_y)*nz0+z+nb_z; C10[idx_cleft]=C10[idx_csqn]; C12[idx_cleft]=C12[idx_csqn]; C13[idx_cleft]=C13[idx_csqn]; C14[idx_cleft]=C14[idx_csqn]; } } */ for ( i = 0; i < ryr_len; i += 1 ) { x=i0_ryr[i]; y=i1_ryr[i]; z=i2_ryr[i]; idx=x*ny0*nz0+y*nz0+z; // #Continous formulation // #states[:,i] += dt*stern(t, states[:,i], Ca_i[idx]) stern_discrete(dt, &states0[i],&states1[i], Ca_i[idx]); open = states0[i]*(1-states1[i]); // #Exp Euler: // #J_RyR = k*open*(Ca_SR[idx]-Ca_i[idx]) // #Ca_i[idx] += dt*J_RyR // #Ca_SR[idx] -= dt*J_RyR/gamma; // #Analytical update: // K = exp(-k_s*dt*(1+1/gamma)) if (open){ if(DB_PF) printf("open [%d] ryr[%d,%d,%d] \n", i, x, y,z); c0 = (Ca_i[idx] + gamma*Ca_SR[idx])/(1+gamma); c1 = (Ca_i[idx] - Ca_SR[idx])/(1+1/gamma); Ca_i[idx] = c0 + c1*K; Ca_SR[idx] = c0 - c1*K/gamma; } } } void stern(double t, double* y0, double* y1, double Ca){ double m = *y0; double h = *y1; double kim = 0.005; double kom = 0.06; double K_i = 0.01*10; double K_o = 0.01*41.4; double ki = kim/K_i; double ko = kom/(K_o*K_o); double dm = ko*Ca*Ca*(1-m)-kom*m; double dh = ki*Ca*(1-h)-kim*h; *y0=dm; *y1=dh; } void stern_discrete(double dt, int* y0, int* y1, double Ca){ double kim = 0.002; // 1/ms double kom = 1.5; // 0.5 1/ms double kd_i = 20.0; // 20.0 um*ms double kd_o = 0.9; // um*ms^N 0.7, 0.8, 0.9, 1.0 double Ca_ki = Ca/kd_i; double Ca_ko = Ca/kd_o; double ki = Ca_ki*Ca_ki; // (Ca/kd_i)^2 double ko = Ca_ko*Ca_ko*Ca_ko*Ca_ko; // ko = (Ca/kd_o)^4 //double kim = 0.005; // Original: 0.005 //double kom = 0.04; // Original: 0.06 //double ki = Ca*1.5*1e-3; // Original: Ca*0.5*1e-3 //double ko = 1e-6*Ca*Ca*3500; // Original: 1e-6*Ca*Ca*{35,1200,2000,3500} double r; int m, h; m = *y0; if(m==1){ r = my_random(); m = 1 - (r<(dt*kom)); } else { r=my_random(); m = 1*(r<(dt*ko)); } h = *y1; if(h==1){ r = my_random(); h = 1 - (r<(dt*kim)); } else{ r = my_random(); h = 1*(r<(dt*ki)); } *y0=m; *y1=h; } inline double my_random() { double r; double x; // r=(double)(rand()%100000000); // x=(r*1e-8); x=((double)rand())/(double)RAND_MAX; return x; } void store2Dmatrixfile_double_1D(char* outfile, double* ar, int rows, int cols, int x_strid){ FILE *fpdata; int i,j; if ((fpdata=fopen(outfile, "w"))==NULL) { printf("fialed open output file "); printf("%s",outfile); printf(" ! \n "); exit(0); } // printf("----Generating list output to "); // printf("%s",outfile); // printf(" file----\n"); for(i=0;i<rows;i++) { for(j=0;j<cols;j++) { fprintf(fpdata,"%.9e ", ar[x_strid*rows*cols+i*cols+j]); } fprintf(fpdata,"\n"); } fclose(fpdata); return; } void store2Dmatrixfile_double_bin(char* outfile, double* ar, int rows, int cols, int x_strid) { FILE *fpdata; int i,j; if ((fpdata=fopen(outfile, "wb"))==NULL) { printf("failed open output file "); printf("%s",outfile); printf(" ! \n "); exit(0); } fwrite(&ar[x_strid*rows*cols],sizeof(double),rows*cols,fpdata); fclose(fpdata); return; } void transfer_hdf5_data(hdf5_data_type* h5_data, double* ar0, double* ar1, double scale_value, hsize_t* chunk_dims) { int i,j; int rows=chunk_dims[0]; int cols=chunk_dims[1]; // Transfer data from padded ar to stripped data for(i=0;i<rows;i++) { for(j=0;j<cols;j++) { double rel_data_diff = (ar1[i*(cols+2)+j+1]-ar0[i*(cols+2)+j+1])/scale_value; h5_data[i*cols+j] = (hdf5_data_type)round(rel_data_diff*H5_DATA_LIMIT_1); } } } void store2Dmatrixfile_int_1D(char* outfile, int* ar, int rows, int cols){ FILE *fpdata; int i,j; if ((fpdata=fopen(outfile, "w"))==NULL) { printf("failed open output file "); printf("%s",outfile); printf(" ! \n "); exit(0); } printf("----Generating list output to "); printf("%s",outfile); printf(" file----\n"); for(i=0;i<rows;i++) { for(j=0;j<cols;j++) fprintf(fpdata,"%d ",ar[i*cols+j]); fprintf(fpdata,"\n"); } fclose(fpdata); return; } double my_min(double* ar, int len) { double min=ar[0]; int i; for ( i = 0; i < len; i += 1 ) { if(ar[i]<min) min=ar[i]; } return min; } double my_max(double* ar, int len) { double max=ar[0]; int i; for ( i = 0; i < len; i += 1 ) { if(ar[i]>max) max=ar[i]; } return max; } double timing(){ double time; struct timeval timmer; gettimeofday(&timmer,NULL); time = 1000000*timmer.tv_sec + timmer.tv_usec; time /= 1000000; return time; } int load_indices_serial(int nx, int ny, int nz, int h, int** i0_ryr, int** i1_ryr, int** i2_ryr, int* ryr_len, int** i0_csqn, int** i1_csqn, int** i2_csqn, int* csqn_len, int** i0_cleft, int** i1_cleft, int** i2_cleft, int** cleft_nb, int* cleft_len, int x_slice_mid, int x_slice_width, int x_slice_num, int use_failing) { int i,j,k; int nx_old; int ny_old; int nz_old; nx_old=nx; ny_old=ny; nz_old=nz; // Scale nx, xy, nz in terms of RyR if(30%h!=0){ printf("30 must be divisible by h!"); exit(1); } int h_scale; h_scale = 30/h; nx = nx/h_scale; ny = ny/h_scale; nz = nz/h_scale; // All CaRU placed mid-sarcomere // int mid_x = (nx+1)/2; // load RyR indices from file int* i1; int* i2; int i1_len; int i2_len; char i_RyR_indices_name[200]; char j_RyR_indices_name[200]; sprintf(i_RyR_indices_name, "i_RyR_indices%s.dat", use_failing ? "_failing" : ""); sprintf(j_RyR_indices_name, "j_RyR_indices%s.dat", use_failing ? "_failing" : ""); if (use_failing) printf("Load failing indices"); else printf("Load normal indices"); i1=loadRyRindexfile_int(i_RyR_indices_name, &i1_len); i2=loadRyRindexfile_int(j_RyR_indices_name, &i2_len); // # Only use the subset which are inside the geometry if(i1_len==i2_len) printf("num RyR before reduction: %d\n", i1_len); else printf("num RyR is wrong: i1_len!=i2_len\n"); int* i1_temp; int* i2_temp; int i1_temp_len=0; for ( i = 0; i < i1_len; i += 1 ) { if(i1[i]<ny) i1_temp_len++; } i1_temp=malloc(i1_temp_len*sizeof(int)); i2_temp=malloc(i1_temp_len*sizeof(int)); j=0; for ( i = 0; i < i1_len; i += 1 ) { if(i1[i]<ny){ i1_temp[j]=i1[i]; i2_temp[j]=i2[i]; j++; } } free(i1); free(i2); int i1_ryr_len=0; for ( i = 0; i < i1_temp_len; i += 1 ) { if(i2_temp[i]<nz) i1_ryr_len++; } *i0_ryr=malloc(x_slice_num*i1_ryr_len*sizeof(int)); *i1_ryr=malloc(x_slice_num*i1_ryr_len*sizeof(int)); *i2_ryr=malloc(x_slice_num*i1_ryr_len*sizeof(int)); j=0; for ( i = 0; i < i1_temp_len; i += 1 ) { if(i2_temp[i]<nz){ for(k=0; k < x_slice_num; k++){ (*i1_ryr)[k*i1_ryr_len+j]=i1_temp[i]; (*i2_ryr)[k*i1_ryr_len+j]=i2_temp[i]; } j++; } } free(i1_temp); free(i2_temp); // Scale indices and move to center of macro voxel for ( i = 0; i < i1_ryr_len; i += 1 ) { for(k=0; k < x_slice_num; k++){ (*i0_ryr)[k*i1_ryr_len+i] = k*x_slice_width+x_slice_mid; //for those ryr just on 0 boundary, avoid to subtracting their coords to negative if((*i1_ryr)[k*i1_ryr_len+i]>0) (*i1_ryr)[k*i1_ryr_len+i] = (*i1_ryr)[k*i1_ryr_len+i]*h_scale - floor((double)h_scale/2); else (*i1_ryr)[k*i1_ryr_len+i] = (*i1_ryr)[k*i1_ryr_len+i]*h_scale; if((*i2_ryr)[k*i1_ryr_len+i]>0) (*i2_ryr)[k*i1_ryr_len+i] = (*i2_ryr)[k*i1_ryr_len+i]*h_scale - floor((double)h_scale/2); else (*i2_ryr)[k*i1_ryr_len+i] = (*i2_ryr)[k*i1_ryr_len+i]*h_scale; } } *ryr_len=i1_ryr_len*x_slice_num; // load CSQN indices from file char i_csqn_indices_name[200]; char j_csqn_indices_name[200]; sprintf(i_csqn_indices_name, "i_csqn_indices%s.dat", use_failing ? "_failing" : ""); sprintf(j_csqn_indices_name, "j_csqn_indices%s.dat", use_failing ? "_failing" : ""); i1 = loadRyRindexfile_int(i_csqn_indices_name, &i1_len); i2 = loadRyRindexfile_int(j_csqn_indices_name, &i2_len); if(i1_len==i2_len) printf("num CSQN before reduction: %d\n", i1_len); else printf("num CSQN is wrong: i1_len!=i2_len\n"); //# Only use the subset which are inside the geometry // i1_csqn = i1[i2<nz]*h_scale // i2_csqn = i2[i2<nz]*h_scale // i0_csqn = np.ones(len(i1_csqn), dtype=int)*mid_x*h_scale i1_temp_len=0; for ( i = 0; i < i1_len; i += 1 ) { if(i1[i]<ny) i1_temp_len++; } i1_temp=malloc(i1_temp_len*sizeof(int)); i2_temp=malloc(i1_temp_len*sizeof(int)); j=0; for ( i = 0; i < i1_len; i += 1 ) { if(i1[i]<ny){ i1_temp[j]=i1[i]; i2_temp[j]=i2[i]; j++; } } free(i1); free(i2); int i1_csqn_len=0; for ( i = 0; i < i1_temp_len; i += 1 ) { if(i2_temp[i]<nz) i1_csqn_len++; } *i0_csqn=malloc(x_slice_num*i1_csqn_len*sizeof(int)); *i1_csqn=malloc(x_slice_num*i1_csqn_len*sizeof(int)); *i2_csqn=malloc(x_slice_num*i1_csqn_len*sizeof(int)); j=0; for ( i = 0; i < i1_temp_len; i += 1 ) { if(i2_temp[i]<nz){ for(k=0; k < x_slice_num; k++){ (*i1_csqn)[k*i1_csqn_len+j]=i1_temp[i]; (*i2_csqn)[k*i1_csqn_len+j]=i2_temp[i]; } j++; } } free(i1_temp); free(i2_temp); // Scale indices and move to center of macro voxel for(k=0; k < x_slice_num; k++){ for ( i = 0; i < i1_csqn_len; i += 1 ) { (*i0_csqn)[k*i1_csqn_len+i] = k*x_slice_width+x_slice_mid; (*i1_csqn)[k*i1_csqn_len+i] = (*i1_csqn)[k*i1_csqn_len+i]*h_scale; (*i2_csqn)[k*i1_csqn_len+i] = (*i2_csqn)[k*i1_csqn_len+i]*h_scale; } } int* i0_csqn_list; int* i1_csqn_list; int* i2_csqn_list; int m; int csqn_count; *csqn_len=x_slice_num*i1_csqn_len*h_scale*h_scale; *cleft_len=0;//x_slice_num*i1_csqn_len*4*h_scale; // # Add CSQN to all voxels covered by the original CSQN array if (h_scale > 1){ i0_csqn_list=malloc(x_slice_num*i1_csqn_len*h_scale*h_scale*sizeof(int)); i1_csqn_list=malloc(x_slice_num*i1_csqn_len*h_scale*h_scale*sizeof(int)); i2_csqn_list=malloc(x_slice_num*i1_csqn_len*h_scale*h_scale*sizeof(int)); csqn_count=0; // # Add offsetted versions of the csqn for ( m = 0; m < x_slice_num; m += 1 ) { for ( i = 0; i < h_scale; i += 1 ) { for ( j = 0; j < h_scale; j += 1 ) { for ( k = 0; k < i1_csqn_len; k += 1 ) { i0_csqn_list[csqn_count]=(*i0_csqn)[m*i1_csqn_len+k]; i1_csqn_list[csqn_count]=(*i1_csqn)[m*i1_csqn_len+k]+i; i2_csqn_list[csqn_count]=(*i2_csqn)[m*i1_csqn_len+k]+j; csqn_count++; } } } } if(csqn_count!=(*csqn_len)) { printf("csqn_count wrong\n"); exit(0); } } else { i0_csqn_list=(*i0_csqn); i1_csqn_list=(*i1_csqn); i2_csqn_list=(*i2_csqn); } int a_slice_csqn_len=i1_csqn_len*h_scale*h_scale; BinarySort_two(&i1_csqn_list[0],&i2_csqn_list[0],a_slice_csqn_len); int* y_index; y_index=malloc(ny_old*sizeof(int)); for ( i = 0; i < ny_old; i += 1 ) { y_index[i]=-1; } for ( i = a_slice_csqn_len-1; i >= 0; i -= 1 ) { y_index[i1_csqn_list[i]]=i; } //generate cleft index on Y-Z plane,just wrapping the outside of a group of CSQN, //If cleft is in the outside of the mesh or is already indexed by a CSQN, then it is not a true cleft. //Also generate the relative coordinates for th neighbour of each cleft from which to copy the value. //the relative coordinate of y is cleft_nb%8-1, and that of z is cleft_nb/8-1 int coord_y,coord_z; *i1_cleft=(int*)malloc(i1_csqn_len*4*h_scale*sizeof(int)); *i2_cleft=(int*)malloc(i1_csqn_len*4*h_scale*sizeof(int)); *cleft_nb=(int*)malloc(i1_csqn_len*4*h_scale*sizeof(int)); *cleft_len=0; for ( k = 0; k < i1_csqn_len; k += 1 ) { for ( j = 0; j < h_scale; j += 1 ) { //z bottom line coord_y=(*i1_csqn)[k]-1; coord_z=(*i2_csqn)[k]+j; if(IsTrueCleft(coord_y, coord_z, ny_old, nz_old, i1_csqn_list, i2_csqn_list, y_index, a_slice_csqn_len)) { (*i1_cleft)[(*cleft_len)]=coord_y; (*i2_cleft)[(*cleft_len)]=coord_z; //copy from outside // (*cleft_nb)[(*cleft_len)]=0+1; // copy from inside (*cleft_nb)[(*cleft_len)]=16+1; (*cleft_len)++; } //y left line coord_y=(*i1_csqn)[k]+j; coord_z=(*i2_csqn)[k]-1; if(IsTrueCleft(coord_y, coord_z, ny_old, nz_old, i1_csqn_list, i2_csqn_list, y_index, a_slice_csqn_len)) { (*i1_cleft)[(*cleft_len)]=coord_y; (*i2_cleft)[(*cleft_len)]=coord_z; //copy from inside // (*cleft_nb)[(*cleft_len)]=8+0; //copy from inside (*cleft_nb)[(*cleft_len)]=8+2; (*cleft_len)++; } //z top line coord_y=(*i1_csqn)[k]+h_scale; coord_z=(*i2_csqn)[k]+j; if(IsTrueCleft(coord_y, coord_z, ny_old, nz_old, i1_csqn_list, i2_csqn_list, y_index, a_slice_csqn_len)) { (*i1_cleft)[(*cleft_len)]=coord_y; (*i2_cleft)[(*cleft_len)]=coord_z; //copy from outside // (*cleft_nb)[(*cleft_len)]=16+1; // copy from inside (*cleft_nb)[(*cleft_len)]=0+1; (*cleft_len)++; } //y right line coord_y=(*i1_csqn)[k]+j; coord_z=(*i2_csqn)[k]+h_scale; if(IsTrueCleft(coord_y, coord_z, ny_old, nz_old, i1_csqn_list, i2_csqn_list, y_index, a_slice_csqn_len)) { (*i1_cleft)[(*cleft_len)]=coord_y; (*i2_cleft)[(*cleft_len)]=coord_z; //copy from outside // (*cleft_nb)[(*cleft_len)]=8+2; // copy from inside (*cleft_nb)[(*cleft_len)]=8+0; (*cleft_len)++; } } } if((*cleft_len)>i1_csqn_len*4*h_scale){ printf("wrong cleft_len found\n"); exit(0); } //add cleft for multiple 2um x-slices int* i0_cleft_list; int* i1_cleft_list; int* i2_cleft_list; int* cleft_nb_list; i0_cleft_list=malloc(x_slice_num*(*cleft_len)*sizeof(int)); i1_cleft_list=malloc(x_slice_num*(*cleft_len)*sizeof(int)); i2_cleft_list=malloc(x_slice_num*(*cleft_len)*sizeof(int)); cleft_nb_list=malloc(x_slice_num*(*cleft_len)*sizeof(int)); for(k=0; k < x_slice_num; k++){ for ( i = 0; i < (*cleft_len); i += 1 ) { i0_cleft_list[k*(*cleft_len)+i] = k*x_slice_width+x_slice_mid; i1_cleft_list[k*(*cleft_len)+i] = (*i1_cleft)[i]; i2_cleft_list[k*(*cleft_len)+i] = (*i2_cleft)[i]; cleft_nb_list[k*(*cleft_len)+i] = (*cleft_nb)[i]; } } free(*i1_cleft); free(*i2_cleft); free(*cleft_nb); *i0_cleft=i0_cleft_list; *i1_cleft=i1_cleft_list; *i2_cleft=i2_cleft_list; *cleft_nb=cleft_nb_list; *cleft_len=x_slice_num*(*cleft_len); if (h_scale > 1){ free(*i0_csqn); free(*i1_csqn); free(*i2_csqn); *i0_csqn=i0_csqn_list; *i1_csqn=i1_csqn_list; *i2_csqn=i2_csqn_list; } return h_scale; } int IsTrueCleft(int coord_y, int coord_z, int size_y, int size_z, int *i1_csqn, int *i2_csqn, int* y_index, int csqn_len) { int i; //in outside of the mesh if((coord_y<0)||(coord_y>=size_y)||(coord_z<0)||(coord_z>=size_z)) return 0; i=y_index[coord_y]; //not in CSQN if(i<0) return 1; while(i1_csqn[i]==coord_y){ //in CSQN if(i2_csqn[i]==coord_z) return 0; i++; //not in CSQN if(i>=csqn_len) return 1; } return 1; } int idxinrank(int nx, int ny, int nz, int i0, int i1, int i2, int rank, MPI_Comm comm3d) { int coords[3]; MPI_Cart_coords(comm3d,rank,3,coords); if( (i0>=coords[2]*nx)&&((i0<coords[2]+1)*nx)&& (i1>=coords[1]*ny)&&((i1<coords[1]+1)*ny)&& (i2>=coords[0]*nz)&&((i2<coords[0]+1)*nz)) { return 1; } else return 0; } int idxbl2rank(int nx, int ny, int nz, int i0, int i1, int i2, int* coords, MPI_Comm comm3d) { int rank=0; coords[2]=i0/nx; coords[1]=i1/ny; coords[0]=i2/nz; MPI_Cart_rank(comm3d,coords,&rank); return rank; } int distr_ryr_csqn_state(int h, int size_x, int size_y, int size_z, int nx, int ny, int nz, int** i0_ryr, int** i1_ryr, int** i2_ryr, int* ryr_len, int** i0_csqn, int** i1_csqn, int** i2_csqn, int* csqn_len, int** i0_cleft, int** i1_cleft, int** i2_cleft,int** cleft_nb, int* cleft_len, int** states0, int** states1, int x_slice_mid,int x_slice_width, int x_slice_num, MPI_Comm comm3d, MPI_Comm comm, int use_failing) { int i,j; int h_scale; int* global_i0_ryr; int* global_i1_ryr; int* global_i2_ryr; int* global_i0_ryr_reorder; int* global_i1_ryr_reorder; int* global_i2_ryr_reorder; int* global_i0_csqn; int* global_i1_csqn; int* global_i2_csqn; int* global_i0_csqn_reorder; int* global_i1_csqn_reorder; int* global_i2_csqn_reorder; int* global_i0_cleft; int* global_i1_cleft; int* global_i2_cleft; int* global_cleft_nb; int* global_i0_cleft_reorder; int* global_i1_cleft_reorder; int* global_i2_cleft_reorder; int* global_cleft_nb_reorder; int global_ryr_len; int global_csqn_len; int global_cleft_len; int* global_states0; int* global_states0_reorder; int* ryr_rec_count; int* ryr_rec_disp; int* ryr_rec_offset; int* csqn_rec_count; int* csqn_rec_disp; int* csqn_rec_offset; int* cleft_rec_count; int* cleft_rec_disp; int* cleft_rec_offset; int my_id; int nproc; int coords[3]; MPI_Comm_rank(comm,&my_id); MPI_Comm_size(comm,&nproc); if(my_id==0){ h_scale=load_indices_serial(size_x, size_y, size_z, h, &global_i0_ryr, &global_i1_ryr, &global_i2_ryr, &global_ryr_len, &global_i0_csqn, &global_i1_csqn,&global_i2_csqn,&global_csqn_len, &global_i0_cleft, &global_i1_cleft, &global_i2_cleft, &global_cleft_nb, &global_cleft_len, x_slice_mid,x_slice_width,x_slice_num, use_failing); printf("load indices from file: h:%d, h_scale:%d, nx:%d, ny:%d, nz:%d, ryr_len:%d, csqn_len:%d cleft_len:%d\n", h, h_scale, nx, ny, nz, global_ryr_len, global_csqn_len, global_cleft_len); if(global_ryr_len>0) global_states0=malloc(global_ryr_len*sizeof(int)); else global_states0=malloc(1*sizeof(int)); for ( i = 0; i < global_ryr_len; i++) global_states0[i]=0; if(global_ryr_len>=23){ for ( i = 1; i < 23; i =i+3 ) global_states0[i]=1; } else { for ( i = 1; i < global_ryr_len ; i =i+10 ) global_states0[i]=1; } if(DB_PF){ for(i=0;i<global_ryr_len;i++){ if(global_states0[i]==1) printf("ryr[%d]:%d,%d,%d \n",i,global_i0_ryr[i],global_i1_ryr[i],global_i2_ryr[i]); } } ryr_rec_count=malloc(nproc*sizeof(int)); csqn_rec_count=malloc(nproc*sizeof(int)); cleft_rec_count=malloc(nproc*sizeof(int)); for (i = 0; i < nproc; i++) { ryr_rec_count[i]=0; csqn_rec_count[i]=0; cleft_rec_count[i]=0; } for(i=0;i<global_ryr_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_ryr[i],global_i1_ryr[i],global_i2_ryr[i],coords,comm3d); ryr_rec_count[j]++; } for(i=0;i<global_csqn_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_csqn[i],global_i1_csqn[i],global_i2_csqn[i],coords,comm3d); csqn_rec_count[j]++; } for(i=0;i<global_cleft_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_cleft[i],global_i1_cleft[i],global_i2_cleft[i],coords,comm3d); cleft_rec_count[j]++; } for (i = 0; i < nproc; i++) { if(DB_PF) printf("ryr_rec_count[%d]: %d\n",i, ryr_rec_count[i]); if(DB_PF) printf("csqn_rec_count[%d]: %d\n",i, csqn_rec_count[i]); if(DB_PF) printf("cleft_rec_count[%d]: %d\n",i, cleft_rec_count[i]); } ryr_rec_disp = malloc(nproc*sizeof(int)); csqn_rec_disp = malloc(nproc*sizeof(int)); cleft_rec_disp = malloc(nproc*sizeof(int)); ryr_rec_disp[0] = 0; csqn_rec_disp[0] = 0; cleft_rec_disp[0] = 0; for (i = 1; i < nproc; i++) { ryr_rec_disp[i] = ryr_rec_disp[i-1] + ryr_rec_count[i-1]; csqn_rec_disp[i] = csqn_rec_disp[i-1] + csqn_rec_count[i-1]; cleft_rec_disp[i] = cleft_rec_disp[i-1] + cleft_rec_count[i-1]; } if(global_ryr_len!=ryr_rec_disp[nproc-1]+ryr_rec_count[nproc-1]) { printf("Global ryr Count mismatch %d\n", ryr_rec_disp[nproc-1]+ryr_rec_count[nproc-1]); } if(global_csqn_len!=csqn_rec_disp[nproc-1]+csqn_rec_count[nproc-1]) { printf("Global csqn Count mismatch %d\n", csqn_rec_disp[nproc-1]+csqn_rec_count[nproc-1]); } if(global_cleft_len!=cleft_rec_disp[nproc-1]+cleft_rec_count[nproc-1]) { printf("Global cleft Count mismatch %d\n", cleft_rec_disp[nproc-1]+cleft_rec_count[nproc-1]); } ryr_rec_offset = malloc(nproc*sizeof(int)); csqn_rec_offset = malloc(nproc*sizeof(int)); cleft_rec_offset = malloc(nproc*sizeof(int)); for (i = 0; i < nproc; i++) { ryr_rec_offset[i]=0; csqn_rec_offset[i]=0; cleft_rec_offset[i]=0; } global_i0_ryr_reorder=malloc(global_ryr_len*sizeof(int)); global_i1_ryr_reorder=malloc(global_ryr_len*sizeof(int)); global_i2_ryr_reorder=malloc(global_ryr_len*sizeof(int)); global_states0_reorder=malloc(global_ryr_len*sizeof(int)); for(i=0;i<global_ryr_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_ryr[i],global_i1_ryr[i],global_i2_ryr[i],coords,comm3d); global_i0_ryr_reorder[ryr_rec_disp[j]+ryr_rec_offset[j]]=global_i0_ryr[i]-coords[2]*nx+1; global_i1_ryr_reorder[ryr_rec_disp[j]+ryr_rec_offset[j]]=global_i1_ryr[i]-coords[1]*ny+1; global_i2_ryr_reorder[ryr_rec_disp[j]+ryr_rec_offset[j]]=global_i2_ryr[i]-coords[0]*nz+1; global_states0_reorder[ryr_rec_disp[j]+ryr_rec_offset[j]]=global_states0[i]; ryr_rec_offset[j]++; } for (i = 0; i < nproc; i++) { if(ryr_rec_offset[i]!=ryr_rec_count[i]) printf("ryr reorder count error on proc %d \n",i); } free(global_i0_ryr); free(global_i1_ryr); free(global_i2_ryr); free(global_states0); free(ryr_rec_offset); //distribute cleft to there own MPI process global_i0_csqn_reorder=malloc(global_csqn_len*sizeof(int)); global_i1_csqn_reorder=malloc(global_csqn_len*sizeof(int)); global_i2_csqn_reorder=malloc(global_csqn_len*sizeof(int)); for(i=0;i<global_csqn_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_csqn[i],global_i1_csqn[i],global_i2_csqn[i],coords,comm3d); global_i0_csqn_reorder[csqn_rec_disp[j]+csqn_rec_offset[j]]=global_i0_csqn[i]-coords[2]*nx+1; global_i1_csqn_reorder[csqn_rec_disp[j]+csqn_rec_offset[j]]=global_i1_csqn[i]-coords[1]*ny+1; global_i2_csqn_reorder[csqn_rec_disp[j]+csqn_rec_offset[j]]=global_i2_csqn[i]-coords[0]*nz+1; csqn_rec_offset[j]++; } for (i = 0; i < nproc; i++) { if(csqn_rec_offset[i]!=csqn_rec_count[i]) printf("csqn reorder count error on proc %d \n",i); } free(global_i0_csqn); free(global_i1_csqn); free(global_i2_csqn); free(csqn_rec_offset); global_i0_cleft_reorder=malloc(global_cleft_len*sizeof(int)); global_i1_cleft_reorder=malloc(global_cleft_len*sizeof(int)); global_i2_cleft_reorder=malloc(global_cleft_len*sizeof(int)); global_cleft_nb_reorder=malloc(global_cleft_len*sizeof(int)); for(i=0;i<global_cleft_len;i++) { j=idxbl2rank(nx,ny,nz,global_i0_cleft[i],global_i1_cleft[i],global_i2_cleft[i],coords,comm3d); global_i0_cleft_reorder[cleft_rec_disp[j]+cleft_rec_offset[j]]=global_i0_cleft[i]-coords[2]*nx+1; global_i1_cleft_reorder[cleft_rec_disp[j]+cleft_rec_offset[j]]=global_i1_cleft[i]-coords[1]*ny+1; global_i2_cleft_reorder[cleft_rec_disp[j]+cleft_rec_offset[j]]=global_i2_cleft[i]-coords[0]*nz+1; global_cleft_nb_reorder[cleft_rec_disp[j]+cleft_rec_offset[j]]=global_cleft_nb[i]; cleft_rec_offset[j]++; } for (i = 0; i < nproc; i++) { if(cleft_rec_offset[i]!=cleft_rec_count[i]) printf("cleft reorder count error on proc %d \n",i); } free(global_i0_cleft); free(global_i1_cleft); free(global_i2_cleft); free(global_cleft_nb); free(cleft_rec_offset); } //MPI_Gather(&n_ryr,1,MPI_INT,&states_rec_count[0],1,MPI_INT,0,comm); MPI_Scatter(&ryr_rec_count[0],1,MPI_INT,ryr_len,1, MPI_INT,0,comm); MPI_Scatter(&csqn_rec_count[0],1,MPI_INT,csqn_len,1, MPI_INT,0,comm); MPI_Scatter(&cleft_rec_count[0],1,MPI_INT,cleft_len,1, MPI_INT,0,comm); if(*ryr_len>0){ *i0_ryr=(int*)mpi_malloc(my_id,*ryr_len*sizeof(int)); *i1_ryr=(int*)mpi_malloc(my_id,*ryr_len*sizeof(int)); *i2_ryr=(int*)mpi_malloc(my_id,*ryr_len*sizeof(int)); } else { *i0_ryr=(int*)mpi_malloc(my_id,1*sizeof(int)); *i1_ryr=(int*)mpi_malloc(my_id,1*sizeof(int)); *i2_ryr=(int*)mpi_malloc(my_id,1*sizeof(int)); } if(*csqn_len>0) { *i0_csqn=(int*)mpi_malloc(my_id,*csqn_len*sizeof(int)); *i1_csqn=(int*)mpi_malloc(my_id,*csqn_len*sizeof(int)); *i2_csqn=(int*)mpi_malloc(my_id,*csqn_len*sizeof(int)); } else { *i0_csqn=(int*)mpi_malloc(my_id,1*sizeof(int)); *i1_csqn=(int*)mpi_malloc(my_id,1*sizeof(int)); *i2_csqn=(int*)mpi_malloc(my_id,1*sizeof(int)); } if(*cleft_len>0) { *i0_cleft=(int*)mpi_malloc(my_id,*cleft_len*sizeof(int)); *i1_cleft=(int*)mpi_malloc(my_id,*cleft_len*sizeof(int)); *i2_cleft=(int*)mpi_malloc(my_id,*cleft_len*sizeof(int)); *cleft_nb=(int*)mpi_malloc(my_id,*cleft_len*sizeof(int)); } else { *i0_cleft=(int*)mpi_malloc(my_id,1*sizeof(int)); *i1_cleft=(int*)mpi_malloc(my_id,1*sizeof(int)); *i2_cleft=(int*)mpi_malloc(my_id,1*sizeof(int)); *cleft_nb=(int*)mpi_malloc(my_id,1*sizeof(int)); } if(*ryr_len>0){ *states0=(int*)mpi_malloc(my_id,*ryr_len*sizeof(int)); *states1=(int*)mpi_malloc(my_id,*ryr_len*sizeof(int)); for ( i = 0; i < *ryr_len; i += 1 ) { (*states0)[i]=0; (*states1)[i]=0; } } else { *states0=(int*)mpi_malloc(my_id,1*sizeof(int)); *states1=(int*)mpi_malloc(my_id,1*sizeof(int)); (*states0)[0]=0; (*states1)[0]=0; } MPI_Scatterv(global_i0_ryr_reorder, ryr_rec_count,ryr_rec_disp, MPI_INT, *i0_ryr, *ryr_len, MPI_INT, 0, comm); MPI_Scatterv(global_i1_ryr_reorder, ryr_rec_count,ryr_rec_disp, MPI_INT, *i1_ryr, *ryr_len, MPI_INT, 0, comm); MPI_Scatterv(global_i2_ryr_reorder, ryr_rec_count,ryr_rec_disp, MPI_INT, *i2_ryr, *ryr_len, MPI_INT, 0, comm); MPI_Scatterv(global_i0_csqn_reorder, csqn_rec_count,csqn_rec_disp, MPI_INT, *i0_csqn, *csqn_len, MPI_INT, 0, comm); MPI_Scatterv(global_i1_csqn_reorder, csqn_rec_count,csqn_rec_disp, MPI_INT, *i1_csqn, *csqn_len, MPI_INT, 0, comm); MPI_Scatterv(global_i2_csqn_reorder, csqn_rec_count,csqn_rec_disp, MPI_INT, *i2_csqn, *csqn_len, MPI_INT, 0, comm); MPI_Scatterv(global_i0_cleft_reorder, cleft_rec_count,cleft_rec_disp, MPI_INT, *i0_cleft, *cleft_len, MPI_INT, 0, comm); MPI_Scatterv(global_i1_cleft_reorder, cleft_rec_count,cleft_rec_disp, MPI_INT, *i1_cleft, *cleft_len, MPI_INT, 0, comm); MPI_Scatterv(global_i2_cleft_reorder, cleft_rec_count,cleft_rec_disp, MPI_INT, *i2_cleft, *cleft_len, MPI_INT, 0, comm); MPI_Scatterv(global_cleft_nb_reorder, cleft_rec_count,cleft_rec_disp, MPI_INT, *cleft_nb, *cleft_len, MPI_INT, 0, comm); MPI_Scatterv(global_states0_reorder, ryr_rec_count, ryr_rec_disp, MPI_INT, *states0, *ryr_len, MPI_INT, 0, comm); //MPI_Bcast(&global_ryr_num,1,MPI_INT,0,comm); if(DB_PF) printf("Thread%d: ryr_len=%d\n",my_id, *ryr_len); // sprintf(caoutfile,"%s/Ca%d_T%d_rank%d_%d_%d_s0.np",outdirname,i,counter,coord[2],coord[1],coord[0]); // store2Dmatrixfile_double_1D(caoutfile,C1[i],ny0,nz0,30); //MPI_Gatherv(states0, n_ryr, MPI_INT, global_states0, states_rec_count, states_rec_disp, MPI_INT, 0, comm); // if(my_id==2) { // for(i=0;i<*ryr_len;i++) printf("Thread2 states[%d]: %d\n",i,(*states0)[i]); // } if(DB_PF){ for(i=0;i<*ryr_len;i++){ if((*states0)[i]==1){ printf("Proc%d,ryr_len=%d,ryr[%d]:%d,%d,%d \n",my_id, *ryr_len,i,(*i0_ryr)[i],(*i1_ryr)[i],(*i2_ryr)[i]); } } } if(my_id==0){ free(ryr_rec_count); free(ryr_rec_disp); free(csqn_rec_count); free(csqn_rec_disp); free(cleft_rec_count); free(cleft_rec_disp); free(global_i0_ryr_reorder); free(global_i1_ryr_reorder); free(global_i2_ryr_reorder); free(global_i0_csqn_reorder); free(global_i1_csqn_reorder); free(global_i2_csqn_reorder); free(global_i0_cleft_reorder); free(global_i1_cleft_reorder); free(global_i2_cleft_reorder); free(global_cleft_nb_reorder); free(global_states0_reorder); } return 30/h; } //int* loadRyRindexfile_int(char* infile, CONDFN cf, int cond) int* loadRyRindexfile_int(char* infile, int* count) { FILE *fpdata; int* arreturn; int i; int temp_d; *count=0; if(DB_PF) printf("Load file name: %s\n", infile); fpdata = fopen(infile, "r"); if(fpdata==NULL) { printf("\nFailure to open input file.\n"); exit(0); } while(fscanf(fpdata, "%d", &temp_d)!=EOF){ // if(cf(temp_d,cond)) count++; (*count)++; // printf("%d,",temp_d); } if(DB_PF) printf("There are %d indices satisfy the condition\n",*count); arreturn = malloc((*count)*sizeof(int)); if (arreturn == NULL) { printf("\nFailure trying to allocate room for array.\n"); exit(0); } rewind(fpdata); i=0; while(fscanf(fpdata, "%d", &temp_d)!=EOF){ // if(cf(temp_d,cond)) { arreturn[i]=temp_d; i++; // } } fclose(fpdata); if (*count != i) { printf("Wrong indices number\n"); exit(0); } if(DB_PF) printf("load file %s over \n", infile); return arreturn; } void readparam(int* iconf, double* conf) { FILE* file2; char Data[MAX_LINE_LENGTH]; if((file2=fopen("param","r")) == NULL) { printf("Error opening param file\n"); return; } // h fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[0]); // size_x fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[1]); // size_y fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[2]); // size_z fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[3]); // x_domains fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[4]); // y_domains fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[5]); // z_domains fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[6]); // save_data fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[7]); // use_failing fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[8]); // T fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%le\n",&conf[0]); // DT fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%le\n",&conf[1]); // save data in binary file fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[9]); // save data in hdf5 format fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d\n",&iconf[10]); // blocking_y_for_cache fgets(Data,MAX_LINE_LENGTH,file2); fscanf(file2,"%d",&iconf[11]); fclose(file2); } void updateBound(double* C00, double* C01, double* C02, double* C03, double* C04, int C_flag, int nx0, int ny0, int nz0, double* yz_sbuf0,double* yz_rbuf0, double* xz_sbuf0,double* xz_rbuf0, double* xy_sbuf0,double* xy_rbuf0, double* yz_sbuf1,double* yz_rbuf1, double* xz_sbuf1,double* xz_rbuf1, double* xy_sbuf1,double* xy_rbuf1, int* neighbor, MPI_Status* ar_status, MPI_Request* ar_send_req, MPI_Request* ar_recv_req, MPI_Comm comm, MPI_Comm comm3d) { int i,j,k; int nx=nx0-2; int ny=ny0-2; int nz=nz0-2; int dims[3]; int periods[3]; int coords[3]; int ZN=0, ZP=1, YN=2, YP=3, XN=4, XP=5; MPI_Cart_get(comm3d, 3, dims, periods, coords); // Ghost X end sheet if(coords[2]==0){ i=0; for (j=1; j<ny0-1; j++) for (k=1; k<nz0-1; k++){ C00[i*nz0*ny0+j*nz0+k] = C00[(i+1)*nz0*ny0+j*nz0+k]; C01[i*nz0*ny0+j*nz0+k] = C01[(i+1)*nz0*ny0+j*nz0+k]; C02[i*nz0*ny0+j*nz0+k] = C02[(i+1)*nz0*ny0+j*nz0+k]; C03[i*nz0*ny0+j*nz0+k] = C03[(i+1)*nz0*ny0+j*nz0+k]; C04[i*nz0*ny0+j*nz0+k] = C04[(i+1)*nz0*ny0+j*nz0+k]; } } else { putin_sendbuffer_yz(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &yz_sbuf0[0*ny*nz],ny*nz); putin_sendbuffer_yz(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &yz_sbuf0[1*ny*nz],ny*nz); putin_sendbuffer_yz(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &yz_sbuf0[2*ny*nz],ny*nz); putin_sendbuffer_yz(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &yz_sbuf0[3*ny*nz],ny*nz); putin_sendbuffer_yz(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &yz_sbuf0[4*ny*nz],ny*nz); } MPI_Isend(yz_sbuf0,5*ny*nz,MPI_DOUBLE,neighbor[XN],C_flag+1000, comm, &ar_send_req[0]); MPI_Irecv(yz_rbuf0,5*ny*nz,MPI_DOUBLE,neighbor[XN],C_flag+1000, comm, &ar_recv_req[0]); // MPI_Sendrecv(yz_sbuf0,5*ny*nz,MPI_DOUBLE,neighbor[XN],C_flag+1000, // yz_rbuf0,5*ny*nz,MPI_DOUBLE,neighbor[XN],C_flag+1000,comm,&status); if(coords[2]==(dims[2]-1)) { i=nx0-1; for (j=1; j<ny0-1; j++) for (k=1; k<nz0-1; k++){ C00[i*nz0*ny0+j*nz0+k] = C00[(i-1)*nz0*ny0+j*nz0+k]; C01[i*nz0*ny0+j*nz0+k] = C01[(i-1)*nz0*ny0+j*nz0+k]; C02[i*nz0*ny0+j*nz0+k] = C02[(i-1)*nz0*ny0+j*nz0+k]; C03[i*nz0*ny0+j*nz0+k] = C03[(i-1)*nz0*ny0+j*nz0+k]; C04[i*nz0*ny0+j*nz0+k] = C04[(i-1)*nz0*ny0+j*nz0+k]; } } else { putin_sendbuffer_yz( (nx0-2)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &yz_sbuf1[0*ny*nz],ny*nz); putin_sendbuffer_yz( (nx0-2)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &yz_sbuf1[1*ny*nz],ny*nz); putin_sendbuffer_yz( (nx0-2)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &yz_sbuf1[2*ny*nz],ny*nz); putin_sendbuffer_yz( (nx0-2)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &yz_sbuf1[3*ny*nz],ny*nz); putin_sendbuffer_yz( (nx0-2)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &yz_sbuf1[4*ny*nz],ny*nz); } MPI_Isend(yz_sbuf1,5*ny*nz,MPI_DOUBLE,neighbor[XP],C_flag+1000, comm, &ar_send_req[1]); MPI_Irecv(yz_rbuf1,5*ny*nz,MPI_DOUBLE,neighbor[XP],C_flag+1000, comm, &ar_recv_req[1]); // MPI_Sendrecv(yz_sbuf1,5*ny*nz,MPI_DOUBLE,neighbor[XP],C_flag+1000, // yz_rbuf1,5*ny*nz,MPI_DOUBLE,neighbor[XP],C_flag+1000,comm,&status); // printf("exchange X end sheet ok! coords[%d,%d,%d]\n",coords[0],coords[1],coords[2]); // Ghost Y end sheet if(coords[1]==0){ j=0; for (i=1; i<nx0-1; i++) for (k=1; k<nz0-1; k++){ C00[i*nz0*ny0+j*nz0+k] = C00[i*nz0*ny0+(j+1)*nz0+k]; C01[i*nz0*ny0+j*nz0+k] = C01[i*nz0*ny0+(j+1)*nz0+k]; C02[i*nz0*ny0+j*nz0+k] = C02[i*nz0*ny0+(j+1)*nz0+k]; C03[i*nz0*ny0+j*nz0+k] = C03[i*nz0*ny0+(j+1)*nz0+k]; C04[i*nz0*ny0+j*nz0+k] = C04[i*nz0*ny0+(j+1)*nz0+k]; } } else { putin_sendbuffer_xz( 1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &xz_sbuf0[0*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &xz_sbuf0[1*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &xz_sbuf0[2*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &xz_sbuf0[3*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &xz_sbuf0[4*nx*nz],nx*nz); } MPI_Isend(xz_sbuf0,5*nx*nz,MPI_DOUBLE,neighbor[YN],C_flag+2000, comm, &ar_send_req[2]); MPI_Irecv(xz_rbuf0,5*nx*nz,MPI_DOUBLE,neighbor[YN],C_flag+2000, comm, &ar_recv_req[2]); // MPI_Sendrecv(xz_sbuf0,5*nx*nz,MPI_DOUBLE,neighbor[YN],C_flag+2000, // xz_rbuf0,5*nx*nz,MPI_DOUBLE,neighbor[YN],C_flag+2000,comm,&status); if(coords[1]==(dims[1]-1)) { j=ny0-1; for (i=1; i<nx0-1; i++) for (k=1; k<nz0-1; k++){ C00[i*nz0*ny0+j*nz0+k] = C00[i*nz0*ny0+(j-1)*nz0+k]; C01[i*nz0*ny0+j*nz0+k] = C01[i*nz0*ny0+(j-1)*nz0+k]; C02[i*nz0*ny0+j*nz0+k] = C02[i*nz0*ny0+(j-1)*nz0+k]; C03[i*nz0*ny0+j*nz0+k] = C03[i*nz0*ny0+(j-1)*nz0+k]; C04[i*nz0*ny0+j*nz0+k] = C04[i*nz0*ny0+(j-1)*nz0+k]; } } else { putin_sendbuffer_xz( 1*nz0*ny0+(ny0-2)*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &xz_sbuf1[0*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+(ny0-2)*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &xz_sbuf1[1*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+(ny0-2)*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &xz_sbuf1[2*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+(ny0-2)*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &xz_sbuf1[3*nx*nz],nx*nz); putin_sendbuffer_xz( 1*nz0*ny0+(ny0-2)*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &xz_sbuf1[4*nx*nz],nx*nz); } MPI_Isend(xz_sbuf1,5*nx*nz,MPI_DOUBLE,neighbor[YP],C_flag+2000, comm, &ar_send_req[3]); MPI_Irecv(xz_rbuf1,5*nx*nz,MPI_DOUBLE,neighbor[YP],C_flag+2000, comm, &ar_recv_req[3]); // MPI_Sendrecv(xz_sbuf1,5*nx*nz,MPI_DOUBLE,neighbor[YP],C_flag+2000, // xz_rbuf1,5*nx*nz,MPI_DOUBLE,neighbor[YP],C_flag+2000,comm,&status); // printf("exchange Y end sheet ok! coords[%d,%d,%d]\n",coords[0],coords[1],coords[2]); // Ghost Z end sheet if(coords[0]==0){ k=0; for (i=1; i<nx0-1; i++) for (j=1; j<ny0-1; j++){ C00[i*nz0*ny0+j*nz0+k] = C00[i*nz0*ny0+j*nz0+k+1]; C01[i*nz0*ny0+j*nz0+k] = C01[i*nz0*ny0+j*nz0+k+1]; C02[i*nz0*ny0+j*nz0+k] = C02[i*nz0*ny0+j*nz0+k+1]; C03[i*nz0*ny0+j*nz0+k] = C03[i*nz0*ny0+j*nz0+k+1]; C04[i*nz0*ny0+j*nz0+k] = C04[i*nz0*ny0+j*nz0+k+1]; } } else { putin_sendbuffer_xy(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &xy_sbuf0[0*nx*ny],nx*ny); putin_sendbuffer_xy(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &xy_sbuf0[1*nx*ny],nx*ny); putin_sendbuffer_xy(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &xy_sbuf0[2*nx*ny],nx*ny); putin_sendbuffer_xy(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &xy_sbuf0[3*nx*ny],nx*ny); putin_sendbuffer_xy(1*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &xy_sbuf0[4*nx*ny],nx*ny); } MPI_Isend(xy_sbuf0,5*nx*ny,MPI_DOUBLE,neighbor[ZN],C_flag+3000, comm, &ar_send_req[4]); MPI_Irecv(xy_rbuf0,5*nx*ny,MPI_DOUBLE,neighbor[ZN],C_flag+3000, comm, &ar_recv_req[4]); // MPI_Sendrecv(xy_sbuf0,5*nx*ny,MPI_DOUBLE,neighbor[ZN],C_flag+3000, // xy_rbuf0,5*nx*ny,MPI_DOUBLE,neighbor[ZN],C_flag+3000,comm,&status); if(coords[0]==(dims[0]-1)) { k=nz0-1; for (i=1; i<nx0-1; i++) for (j=1; j<ny0-1; j++){ C00[i*nz0*ny0+j*nz0+k] = C00[i*nz0*ny0+j*nz0+k-1]; C01[i*nz0*ny0+j*nz0+k] = C01[i*nz0*ny0+j*nz0+k-1]; C02[i*nz0*ny0+j*nz0+k] = C02[i*nz0*ny0+j*nz0+k-1]; C03[i*nz0*ny0+j*nz0+k] = C03[i*nz0*ny0+j*nz0+k-1]; C04[i*nz0*ny0+j*nz0+k] = C04[i*nz0*ny0+j*nz0+k-1]; } } else { putin_sendbuffer_xy( 1*nz0*ny0+nz0+nz0-2,nx0,ny0, nz0, C00, nx, ny, nz, &xy_sbuf1[0*nx*ny],nx*ny); putin_sendbuffer_xy( 1*nz0*ny0+nz0+nz0-2,nx0,ny0, nz0, C01, nx, ny, nz, &xy_sbuf1[1*nx*ny],nx*ny); putin_sendbuffer_xy( 1*nz0*ny0+nz0+nz0-2,nx0,ny0, nz0, C02, nx, ny, nz, &xy_sbuf1[2*nx*ny],nx*ny); putin_sendbuffer_xy( 1*nz0*ny0+nz0+nz0-2,nx0,ny0, nz0, C03, nx, ny, nz, &xy_sbuf1[3*nx*ny],nx*ny); putin_sendbuffer_xy( 1*nz0*ny0+nz0+nz0-2,nx0,ny0, nz0, C04, nx, ny, nz, &xy_sbuf1[4*nx*ny],nx*ny); } MPI_Isend(xy_sbuf1,5*nx*ny,MPI_DOUBLE,neighbor[ZP],C_flag+3000, comm, &ar_send_req[5]); MPI_Irecv(xy_rbuf1,5*nx*ny,MPI_DOUBLE,neighbor[ZP],C_flag+3000, comm, &ar_recv_req[5]); // MPI_Sendrecv(xy_sbuf1,5*nx*ny,MPI_DOUBLE,neighbor[ZP],C_flag+3000, // xy_rbuf1,5*nx*ny,MPI_DOUBLE,neighbor[ZP],C_flag+3000,comm,&status); MPI_Waitall(6, ar_recv_req, ar_status); if(coords[2]!=0){ getout_recvbuffer_yz( 1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &yz_rbuf0[0*ny*nz],ny*nz); getout_recvbuffer_yz( 1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &yz_rbuf0[1*ny*nz],ny*nz); getout_recvbuffer_yz( 1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &yz_rbuf0[2*ny*nz],ny*nz); getout_recvbuffer_yz( 1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &yz_rbuf0[3*ny*nz],ny*nz); getout_recvbuffer_yz( 1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &yz_rbuf0[4*ny*nz],ny*nz); } if(coords[2]!=(dims[2]-1)){ getout_recvbuffer_yz((nx0-1)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &yz_rbuf1[0*ny*nz],ny*nz); getout_recvbuffer_yz((nx0-1)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &yz_rbuf1[1*ny*nz],ny*nz); getout_recvbuffer_yz((nx0-1)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &yz_rbuf1[2*ny*nz],ny*nz); getout_recvbuffer_yz((nx0-1)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &yz_rbuf1[3*ny*nz],ny*nz); getout_recvbuffer_yz((nx0-1)*nz0*ny0+1*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &yz_rbuf1[4*ny*nz],ny*nz); } if(coords[1]!=0){ getout_recvbuffer_xz( 1*nz0*ny0+1,nx0,ny0, nz0, C00, nx, ny, nz, &xz_rbuf0[0*nx*nz],nx*nz); getout_recvbuffer_xz( 1*nz0*ny0+1,nx0,ny0, nz0, C01, nx, ny, nz, &xz_rbuf0[1*nx*nz],nx*nz); getout_recvbuffer_xz( 1*nz0*ny0+1,nx0,ny0, nz0, C02, nx, ny, nz, &xz_rbuf0[2*nx*nz],nx*nz); getout_recvbuffer_xz( 1*nz0*ny0+1,nx0,ny0, nz0, C03, nx, ny, nz, &xz_rbuf0[3*nx*nz],nx*nz); getout_recvbuffer_xz( 1*nz0*ny0+1,nx0,ny0, nz0, C04, nx, ny, nz, &xz_rbuf0[4*nx*nz],nx*nz); } if(coords[1]!=(dims[1]-1)){ getout_recvbuffer_xz(1*nz0*ny0+(ny0-1)*nz0+1,nx0,ny0, nz0, C00, nx, ny, nz, &xz_rbuf1[0*nx*nz],nx*nz); getout_recvbuffer_xz(1*nz0*ny0+(ny0-1)*nz0+1,nx0,ny0, nz0, C01, nx, ny, nz, &xz_rbuf1[1*nx*nz],nx*nz); getout_recvbuffer_xz(1*nz0*ny0+(ny0-1)*nz0+1,nx0,ny0, nz0, C02, nx, ny, nz, &xz_rbuf1[2*nx*nz],nx*nz); getout_recvbuffer_xz(1*nz0*ny0+(ny0-1)*nz0+1,nx0,ny0, nz0, C03, nx, ny, nz, &xz_rbuf1[3*nx*nz],nx*nz); getout_recvbuffer_xz(1*nz0*ny0+(ny0-1)*nz0+1,nx0,ny0, nz0, C04, nx, ny, nz, &xz_rbuf1[4*nx*nz],nx*nz); } if(coords[0]!=0){ getout_recvbuffer_xy( 1*nz0*ny0+1*nz0, nx0,ny0, nz0, C00, nx, ny, nz, &xy_rbuf0[0*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+1*nz0, nx0,ny0, nz0, C01, nx, ny, nz, &xy_rbuf0[1*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+1*nz0, nx0,ny0, nz0, C02, nx, ny, nz, &xy_rbuf0[2*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+1*nz0, nx0,ny0, nz0, C03, nx, ny, nz, &xy_rbuf0[3*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+1*nz0, nx0,ny0, nz0, C04, nx, ny, nz, &xy_rbuf0[4*nx*ny],nx*ny); } if(coords[0]!=(dims[0]-1)){ getout_recvbuffer_xy( 1*nz0*ny0+nz0+nz0-1,nx0,ny0, nz0, C00, nx, ny, nz, &xy_rbuf1[0*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+nz0+nz0-1,nx0,ny0, nz0, C01, nx, ny, nz, &xy_rbuf1[1*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+nz0+nz0-1,nx0,ny0, nz0, C02, nx, ny, nz, &xy_rbuf1[2*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+nz0+nz0-1,nx0,ny0, nz0, C03, nx, ny, nz, &xy_rbuf1[3*nx*ny],nx*ny); getout_recvbuffer_xy( 1*nz0*ny0+nz0+nz0-1,nx0,ny0, nz0, C04, nx, ny, nz, &xy_rbuf1[4*nx*ny],nx*ny); } // printf("exchange Z end sheet ok! coords[%d,%d,%d]\n",coords[0],coords[1],coords[2]); } void putin_sendbuffer_yz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i; if(sbuf_len!=ny*nz) { printf("yz sbuf_len error!\n"); exit(0); } for ( i = 0; i < ny; i += 1 ) { memcpy(&sbuf[i*nz],&arr[base_addr+i*nz0],nz*sizeof(double)); } } void putin_sendbuffer_xz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i; if(sbuf_len!=nx*nz) { printf("xz sbuf_len error!\n"); exit(0); } for ( i = 0; i < nx; i += 1 ) { memcpy(&sbuf[i*nz],&arr[base_addr+i*ny0*nz0],nz*sizeof(double)); } } void putin_sendbuffer_xy(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i, j; if(sbuf_len!=nx*ny) { printf("xy sbuf_len error!\n"); exit(0); } for ( i = 0; i < nx; i += 1 ) { for ( j = 0; j < ny; j += 1 ) { sbuf[i*ny+j]=arr[base_addr+i*ny0*nz0+j*nz0]; } } } void getout_recvbuffer_yz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i; if(sbuf_len!=ny*nz) { printf("yz rbuf_len error!\n"); exit(0); } for ( i = 0; i < ny; i += 1 ) { memcpy(&arr[base_addr+i*nz0],&sbuf[i*nz],nz*sizeof(double)); } } void getout_recvbuffer_xz(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i; if(sbuf_len!=nx*nz) { printf("xz rbuf_len error!\n"); exit(0); } for ( i = 0; i < nx; i += 1 ) { memcpy(&arr[base_addr+i*ny0*nz0],&sbuf[i*nz],nz*sizeof(double)); } } void getout_recvbuffer_xy(int base_addr,int nx0,int ny0, int nz0, double* arr, int nx, int ny, int nz, double* sbuf, int sbuf_len) { int i, j; if(sbuf_len!=nx*ny) { printf("xy rbuf_len error!\n"); exit(0); } for ( i = 0; i < nx; i += 1 ) { for ( j = 0; j < ny; j += 1 ) { arr[base_addr+i*ny0*nz0+j*nz0]=sbuf[i*ny+j]; } } } void BinarySort_two(int* pData, int* vData, int Count) { dichotomy_two(pData,vData,0,Count-1); } void dichotomy_two(int* pData,int* vData, int left,int right) { int i,j; int middle,iTemp; i = left; j = right; middle = pData[(left+right)/2]; do{ while((pData[i]<middle) && (i<right)) i++; while((pData[j]>middle) && (j>left)) j--; if(i<=j) { iTemp = pData[i]; pData[i] = pData[j]; pData[j] = iTemp; iTemp =vData[i]; vData[i]=vData[j]; vData[j]=iTemp; i++; j--; } }while(i<=j); if(left<j) dichotomy_two(pData,vData,left,j); if(right>i) dichotomy_two(pData,vData,i,right); } void *mpi_malloc ( int id, /* IN - Process rank */ int bytes) /* IN - Bytes to allocate */ { void *buffer; if ((buffer = malloc ((size_t) bytes)) == NULL) { printf ("Error: Malloc failed for process %d\n", id); fflush (stdout); MPI_Abort (MPI_COMM_WORLD, 4); } return buffer; } void compute_pde_ode(int nx0, int ny0, int nz0, double dt,double gamma, double fudge, double* alpha, double* B_tot, double* k_on, double* k_off, double** C0, double** C1, int div_y) { // Main kernel int i,j,k,jj,idx; int ny; double J; double Ca_ijk; double buff_ijk; double Ca_i2_ijk; double Ca_SR2_ijk; ny=ny0-2; for (i=1; i<nx0-1; i++) { for (jj=0; jj<ny/div_y; jj++) { //blocking for cache size on y line for (j=jj*div_y+1; j<(jj+1)*div_y+1; j++) { //Laplace diffusion process five array together for(idx=0;idx<5;idx++) { #pragma ivdep #pragma prefetch for (k=1; k<nz0-1; k++) { C1[idx][i*nz0*ny0+j*nz0+k] =alpha[idx]*( C0[idx][i*nz0*ny0+j*nz0+k]*(-6)+ C0[idx][(i-1)*nz0*ny0+j*nz0+k] + C0[idx][(i+1)*nz0*ny0+j*nz0+k] + C0[idx][i*nz0*ny0+(j-1)*nz0+k] + C0[idx][i*nz0*ny0+(j+1)*nz0+k] + C0[idx][i*nz0*ny0+j*nz0+k-1] + C0[idx][i*nz0*ny0+j*nz0+k+1]) + C0[idx][i*nz0*ny0+j*nz0+k]; } } //Reaction for(idx=2;idx<6;idx++) { #pragma ivdep #pragma prefetch for (k=1; k<nz0-1; k++) { Ca_ijk = C1[0][i*nz0*ny0+j*nz0+k]; buff_ijk = C1[idx][i*nz0*ny0+j*nz0+k]; J = k_on[idx]*(B_tot[idx] - buff_ijk)*Ca_ijk - k_off[idx]*buff_ijk; C1[0][i*nz0*ny0+j*nz0+k] -= dt*J; C1[idx][i*nz0*ny0+j*nz0+k] += dt*J; } } // serca3D #pragma ivdep #pragma prefetch for (k=1; k<nz0-1; k++) { // Main kernel Ca_i2_ijk = C1[0][i*nz0*ny0+j*nz0+k]; Ca_SR2_ijk = C1[1][i*nz0*ny0+j*nz0+k]; Ca_i2_ijk *= Ca_i2_ijk; Ca_SR2_ijk *= Ca_SR2_ijk; J = fudge*(570997802.885875*Ca_i2_ijk - 0.0425239333622699*Ca_SR2_ijk)/(106720651.206402*Ca_i2_ijk + 182.498197548666*Ca_SR2_ijk + 5.35062954944879); C1[0][i*nz0*ny0+j*nz0+k] -= dt*J; C1[1][i*nz0*ny0+j*nz0+k] += dt*J/gamma; } } } } }
nvector_openmp.c
/* ----------------------------------------------------------------- * Programmer(s): David J. Gardner and Carol S. Woodward @ LLNL * ----------------------------------------------------------------- * Acknowledgements: This NVECTOR module is based on the NVECTOR * Serial module by Scott D. Cohen, Alan C. * Hindmarsh, Radu Serban, and Aaron Collier * @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * This is the implementation file for an OpenMP implementation * of the NVECTOR module. * -----------------------------------------------------------------*/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <nvector/nvector_openmp.h> #include <sundials/sundials_math.h> #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define ONEPT5 RCONST(1.5) /* Private functions for special cases of vector operations */ static void VCopy_OpenMP(N_Vector x, N_Vector z); /* z=x */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x+y */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z); /* z=x-y */ static void VNeg_OpenMP(N_Vector x, N_Vector z); /* z=-x */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x+y) */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z); /* z=c(x-y) */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax+y */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z); /* z=ax-y */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y); /* y <- ax+y */ static void VScaleBy_OpenMP(realtype a, N_Vector x); /* x <- ax */ /* Private functions for special cases of vector array operations */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X+Y */ static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=X-Y */ static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X+Y) */ static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=c(X-Y) */ static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX+Y */ static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z); /* Z=aX-Y */ static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y); /* Y <- aX+Y */ /* * ----------------------------------------------------------------- * exported functions * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------- * Returns vector type ID. Used to identify vector implementation * from abstract N_Vector interface. */ N_Vector_ID N_VGetVectorID_OpenMP(N_Vector v) { return SUNDIALS_NVEC_OPENMP; } /* ---------------------------------------------------------------------------- * Function to create a new empty vector */ N_Vector N_VNewEmpty_OpenMP(sunindextype length, int num_threads) { N_Vector v; N_VectorContent_OpenMP content; /* Create vector */ v = NULL; v = N_VNewEmpty(); if (v == NULL) return(NULL); /* Attach operations */ /* constructors, destructors, and utility operations */ v->ops->nvgetvectorid = N_VGetVectorID_OpenMP; v->ops->nvclone = N_VClone_OpenMP; v->ops->nvcloneempty = N_VCloneEmpty_OpenMP; v->ops->nvdestroy = N_VDestroy_OpenMP; v->ops->nvspace = N_VSpace_OpenMP; v->ops->nvgetarraypointer = N_VGetArrayPointer_OpenMP; v->ops->nvsetarraypointer = N_VSetArrayPointer_OpenMP; v->ops->nvgetlength = N_VGetLength_OpenMP; /* standard vector operations */ v->ops->nvlinearsum = N_VLinearSum_OpenMP; v->ops->nvconst = N_VConst_OpenMP; v->ops->nvprod = N_VProd_OpenMP; v->ops->nvdiv = N_VDiv_OpenMP; v->ops->nvscale = N_VScale_OpenMP; v->ops->nvabs = N_VAbs_OpenMP; v->ops->nvinv = N_VInv_OpenMP; v->ops->nvaddconst = N_VAddConst_OpenMP; v->ops->nvdotprod = N_VDotProd_OpenMP; v->ops->nvmaxnorm = N_VMaxNorm_OpenMP; v->ops->nvwrmsnormmask = N_VWrmsNormMask_OpenMP; v->ops->nvwrmsnorm = N_VWrmsNorm_OpenMP; v->ops->nvmin = N_VMin_OpenMP; v->ops->nvwl2norm = N_VWL2Norm_OpenMP; v->ops->nvl1norm = N_VL1Norm_OpenMP; v->ops->nvcompare = N_VCompare_OpenMP; v->ops->nvinvtest = N_VInvTest_OpenMP; v->ops->nvconstrmask = N_VConstrMask_OpenMP; v->ops->nvminquotient = N_VMinQuotient_OpenMP; /* fused and vector array operations are disabled (NULL) by default */ /* local reduction kernels */ v->ops->nvdotprodlocal = N_VDotProd_OpenMP; v->ops->nvmaxnormlocal = N_VMaxNorm_OpenMP; v->ops->nvminlocal = N_VMin_OpenMP; v->ops->nvl1normlocal = N_VL1Norm_OpenMP; v->ops->nvinvtestlocal = N_VInvTest_OpenMP; v->ops->nvconstrmasklocal = N_VConstrMask_OpenMP; v->ops->nvminquotientlocal = N_VMinQuotient_OpenMP; v->ops->nvwsqrsumlocal = N_VWSqrSumLocal_OpenMP; v->ops->nvwsqrsummasklocal = N_VWSqrSumMaskLocal_OpenMP; /* XBraid interface operations */ v->ops->nvbufsize = N_VBufSize_OpenMP; v->ops->nvbufpack = N_VBufPack_OpenMP; v->ops->nvbufunpack = N_VBufUnpack_OpenMP; /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof *content); if (content == NULL) { N_VDestroy(v); return(NULL); } /* Attach content */ v->content = content; /* Initialize content */ content->length = length; content->num_threads = num_threads; content->own_data = SUNFALSE; content->data = NULL; return(v); } /* ---------------------------------------------------------------------------- * Function to create a new vector */ N_Vector N_VNew_OpenMP(sunindextype length, int num_threads) { N_Vector v; realtype *data; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create a vector with user data component */ N_Vector N_VMake_OpenMP(sunindextype length, realtype *v_data, int num_threads) { N_Vector v; v = NULL; v = N_VNewEmpty_OpenMP(length, num_threads); if (v == NULL) return(NULL); if (length > 0) { /* Attach data */ NV_OWN_DATA_OMP(v) = SUNFALSE; NV_DATA_OMP(v) = v_data; } return(v); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors. */ N_Vector* N_VCloneVectorArray_OpenMP(int count, N_Vector w) { N_Vector* vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector*) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VClone_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to create an array of new vectors with NULL data array. */ N_Vector* N_VCloneVectorArrayEmpty_OpenMP(int count, N_Vector w) { N_Vector* vs; int j; if (count <= 0) return(NULL); vs = NULL; vs = (N_Vector*) malloc(count * sizeof(N_Vector)); if(vs == NULL) return(NULL); for (j = 0; j < count; j++) { vs[j] = NULL; vs[j] = N_VCloneEmpty_OpenMP(w); if (vs[j] == NULL) { N_VDestroyVectorArray_OpenMP(vs, j-1); return(NULL); } } return(vs); } /* ---------------------------------------------------------------------------- * Function to free an array created with N_VCloneVectorArray_OpenMP */ void N_VDestroyVectorArray_OpenMP(N_Vector* vs, int count) { int j; for (j = 0; j < count; j++) N_VDestroy_OpenMP(vs[j]); free(vs); vs = NULL; return; } /* ---------------------------------------------------------------------------- * Function to return number of vector elements */ sunindextype N_VGetLength_OpenMP(N_Vector v) { return NV_LENGTH_OMP(v); } /* ---------------------------------------------------------------------------- * Function to print a vector to stdout */ void N_VPrint_OpenMP(N_Vector x) { N_VPrintFile_OpenMP(x, stdout); } /* ---------------------------------------------------------------------------- * Function to print a vector to outfile */ void N_VPrintFile_OpenMP(N_Vector x, FILE *outfile) { sunindextype i, N; realtype *xd; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); for (i = 0; i < N; i++) { #if defined(SUNDIALS_EXTENDED_PRECISION) fprintf(outfile, "%11.8Lg\n", xd[i]); #elif defined(SUNDIALS_DOUBLE_PRECISION) fprintf(outfile, "%11.8g\n", xd[i]); #else fprintf(outfile, "%11.8g\n", xd[i]); #endif } fprintf(outfile, "\n"); return; } /* * ----------------------------------------------------------------- * implementation of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Create new vector from existing vector without attaching data */ N_Vector N_VCloneEmpty_OpenMP(N_Vector w) { N_Vector v; N_VectorContent_OpenMP content; if (w == NULL) return(NULL); /* Create vector */ v = NULL; v = N_VNewEmpty(); if (v == NULL) return(NULL); /* Attach operations */ if (N_VCopyOps(w, v)) { N_VDestroy(v); return(NULL); } /* Create content */ content = NULL; content = (N_VectorContent_OpenMP) malloc(sizeof *content); if (content == NULL) { N_VDestroy(v); return(NULL); } /* Attach content */ v->content = content; /* Initialize content */ content->length = NV_LENGTH_OMP(w); content->num_threads = NV_NUM_THREADS_OMP(w); content->own_data = SUNFALSE; content->data = NULL; return(v); } /* ---------------------------------------------------------------------------- * Create new vector from existing vector and attach data */ N_Vector N_VClone_OpenMP(N_Vector w) { N_Vector v; realtype *data; sunindextype length; v = NULL; v = N_VCloneEmpty_OpenMP(w); if (v == NULL) return(NULL); length = NV_LENGTH_OMP(w); /* Create data */ if (length > 0) { /* Allocate memory */ data = NULL; data = (realtype *) malloc(length * sizeof(realtype)); if(data == NULL) { N_VDestroy_OpenMP(v); return(NULL); } /* Attach data */ NV_OWN_DATA_OMP(v) = SUNTRUE; NV_DATA_OMP(v) = data; } return(v); } /* ---------------------------------------------------------------------------- * Destroy vector and free vector memory */ void N_VDestroy_OpenMP(N_Vector v) { if (v == NULL) return; /* free content */ if (v->content != NULL) { /* free data array if it's owned by the vector */ if (NV_OWN_DATA_OMP(v) && NV_DATA_OMP(v) != NULL) { free(NV_DATA_OMP(v)); NV_DATA_OMP(v) = NULL; } free(v->content); v->content = NULL; } /* free ops and vector */ if (v->ops != NULL) { free(v->ops); v->ops = NULL; } free(v); v = NULL; return; } /* ---------------------------------------------------------------------------- * Get storage requirement for N_Vector */ void N_VSpace_OpenMP(N_Vector v, sunindextype *lrw, sunindextype *liw) { *lrw = NV_LENGTH_OMP(v); *liw = 1; return; } /* ---------------------------------------------------------------------------- * Get vector data pointer */ realtype *N_VGetArrayPointer_OpenMP(N_Vector v) { return((realtype *) NV_DATA_OMP(v)); } /* ---------------------------------------------------------------------------- * Set vector data pointer */ void N_VSetArrayPointer_OpenMP(realtype *v_data, N_Vector v) { if (NV_LENGTH_OMP(v) > 0) NV_DATA_OMP(v) = v_data; return; } /* ---------------------------------------------------------------------------- * Compute linear combination z[i] = a*x[i]+b*y[i] */ void N_VLinearSum_OpenMP(realtype a, N_Vector x, realtype b, N_Vector y, N_Vector z) { sunindextype i, N; realtype c, *xd, *yd, *zd; N_Vector v1, v2; booleantype test; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; if ((b == ONE) && (z == y)) { /* BLAS usage: axpy y <- ax+y */ Vaxpy_OpenMP(a,x,y); return; } if ((a == ONE) && (z == x)) { /* BLAS usage: axpy x <- by+x */ Vaxpy_OpenMP(b,y,x); return; } /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) { VSum_OpenMP(x, y, z); return; } /* Cases: (1) a == 1.0, b = -1.0, (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { v1 = test ? y : x; v2 = test ? x : y; VDiff_OpenMP(v2, v1, z); return; } /* Cases: (1) a == 1.0, b == other or 0.0, (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin1_OpenMP(c, v1, v2, z); return; } /* Cases: (1) a == -1.0, b != 1.0, (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; v1 = test ? y : x; v2 = test ? x : y; VLin2_OpenMP(c, v1, v2, z); return; } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) { VScaleSum_OpenMP(a, x, y, z); return; } /* Case: a == -b */ if (a == -b) { VScaleDiff_OpenMP(a, x, y, z); return; } /* Do all cases not handled above: (1) a == other, b == 0.0 - user should have called N_VScale (2) a == 0.0, b == other - user should have called N_VScale (3) a,b == other, a !=b, a != -b */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,b,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+(b*yd[i]); return; } /* ---------------------------------------------------------------------------- * Assigns constant value to all vector elements, z[i] = c */ void N_VConst_OpenMP(realtype c, N_Vector z) { sunindextype i, N; realtype *zd; i = 0; /* initialize to suppress clang warning */ zd = NULL; N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(z)) for (i = 0; i < N; i++) zd[i] = c; return; } /* ---------------------------------------------------------------------------- * Compute componentwise product z[i] = x[i]*y[i] */ void N_VProd_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]*yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise division z[i] = x[i]/y[i] */ void N_VDiv_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]/yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaler multiplication z[i] = c*x[i] */ void N_VScale_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; if (z == x) { /* BLAS usage: scale x <- cx */ VScaleBy_OpenMP(c, x); return; } if (c == ONE) { VCopy_OpenMP(x, z); } else if (c == -ONE) { VNeg_OpenMP(x, z); } else { N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*xd[i]; } return; } /* ---------------------------------------------------------------------------- * Compute absolute value of vector components z[i] = SUNRabs(x[i]) */ void N_VAbs_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = SUNRabs(xd[i]); return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = 1 / x[i] */ void N_VInv_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = ONE/xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute componentwise addition of a scaler to a vector z[i] = x[i] + b */ void N_VAddConst_OpenMP(N_Vector x, realtype b, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,b,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+b; return; } /* ---------------------------------------------------------------------------- * Computes the dot product of two vectors, a = sum(x[i]*y[i]) */ realtype N_VDotProd_OpenMP(N_Vector x, N_Vector y) { sunindextype i, N; realtype sum, *xd, *yd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); #pragma omp parallel for default(none) private(i) shared(N,xd,yd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += xd[i]*yd[i]; } return(sum); } /* ---------------------------------------------------------------------------- * Computes max norm of a vector */ realtype N_VMaxNorm_OpenMP(N_Vector x) { sunindextype i, N; realtype tmax, max, *xd; i = 0; /* initialize to suppress clang warning */ max = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel default(none) private(i,tmax) shared(N,max,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmax = ZERO; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (SUNRabs(xd[i]) > tmax) tmax = SUNRabs(xd[i]); } #pragma omp critical { if (tmax > max) max = tmax; } } return(max); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a vector */ realtype N_VWrmsNorm_OpenMP(N_Vector x, N_Vector w) { return(SUNRsqrt(N_VWSqrSumLocal_OpenMP(x, w)/(NV_LENGTH_OMP(x)))); } /* ---------------------------------------------------------------------------- * Computes weighted root mean square norm of a masked vector */ realtype N_VWrmsNormMask_OpenMP(N_Vector x, N_Vector w, N_Vector id) { return(SUNRsqrt(N_VWSqrSumMaskLocal_OpenMP(x, w, id)/(NV_LENGTH_OMP(x)))); } /* ---------------------------------------------------------------------------- * Finds the minimun component of a vector */ realtype N_VMin_OpenMP(N_Vector x) { sunindextype i, N; realtype min, *xd; realtype tmin; i = 0; /* initialize to suppress clang warning */ xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); min = xd[0]; #pragma omp parallel default(none) private(i,tmin) shared(N,min,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { tmin = xd[0]; #pragma omp for schedule(static) for (i = 1; i < N; i++) { if (xd[i] < tmin) tmin = xd[i]; } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted L2 norm of a vector */ realtype N_VWL2Norm_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(SUNRsqrt(sum)); } /* ---------------------------------------------------------------------------- * Computes L1 norm of a vector */ realtype N_VL1Norm_OpenMP(N_Vector x) { sunindextype i, N; realtype sum, *xd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,xd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i<N; i++) sum += SUNRabs(xd[i]); return(sum); } /* ---------------------------------------------------------------------------- * Compare vector component values to a scaler */ void N_VCompare_OpenMP(realtype c, N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { zd[i] = (SUNRabs(xd[i]) >= c) ? ONE : ZERO; } return; } /* ---------------------------------------------------------------------------- * Compute componentwise inverse z[i] = ONE/x[i] and checks if x[i] == ZERO */ booleantype N_VInvTest_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd, val; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); val = ZERO; #pragma omp parallel for default(none) private(i) shared(N,val,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (xd[i] == ZERO) val = ONE; else zd[i] = ONE/xd[i]; } if (val > ZERO) return (SUNFALSE); else return (SUNTRUE); } /* ---------------------------------------------------------------------------- * Compute constraint mask of a vector */ booleantype N_VConstrMask_OpenMP(N_Vector c, N_Vector x, N_Vector m) { sunindextype i, N; realtype temp; realtype *cd, *xd, *md; booleantype test; i = 0; /* initialize to suppress clang warning */ cd = xd = md = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); cd = NV_DATA_OMP(c); md = NV_DATA_OMP(m); temp = ZERO; #pragma omp parallel for default(none) private(i,test) shared(N,xd,cd,md,temp) \ schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { md[i] = ZERO; /* Continue if no constraints were set for the variable */ if (cd[i] == ZERO) continue; /* Check if a set constraint has been violated */ test = (SUNRabs(cd[i]) > ONEPT5 && xd[i]*cd[i] <= ZERO) || (SUNRabs(cd[i]) > HALF && xd[i]*cd[i] < ZERO); if (test) { temp = md[i] = ONE; /* Here is a race to write to temp */ } } /* Return false if any constraint was violated */ return (temp == ONE) ? SUNFALSE : SUNTRUE; } /* ---------------------------------------------------------------------------- * Compute minimum componentwise quotient */ realtype N_VMinQuotient_OpenMP(N_Vector num, N_Vector denom) { sunindextype i, N; realtype *nd, *dd, min, tmin, val; i = 0; /* initialize to suppress clang warning */ nd = dd = NULL; N = NV_LENGTH_OMP(num); nd = NV_DATA_OMP(num); dd = NV_DATA_OMP(denom); min = BIG_REAL; #pragma omp parallel default(none) private(i,tmin,val) shared(N,min,nd,dd) \ num_threads(NV_NUM_THREADS_OMP(num)) { tmin = BIG_REAL; #pragma omp for schedule(static) for (i = 0; i < N; i++) { if (dd[i] != ZERO) { val = nd[i]/dd[i]; if (val < tmin) tmin = val; } } if (tmin < min) { #pragma omp critical { if (tmin < min) min = tmin; } } } return(min); } /* ---------------------------------------------------------------------------- * Computes weighted square sum of a vector */ realtype N_VWSqrSumLocal_OpenMP(N_Vector x, N_Vector w) { sunindextype i, N; realtype sum, *xd, *wd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); #pragma omp parallel for default(none) private(i) shared(N,xd,wd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { sum += SUNSQR(xd[i]*wd[i]); } return(sum); } /* ---------------------------------------------------------------------------- * Computes weighted square sum of a masked vector */ realtype N_VWSqrSumMaskLocal_OpenMP(N_Vector x, N_Vector w, N_Vector id) { sunindextype i, N; realtype sum, *xd, *wd, *idd; i = 0; /* initialize to suppress clang warning */ sum = ZERO; xd = wd = idd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); wd = NV_DATA_OMP(w); idd = NV_DATA_OMP(id); #pragma omp parallel for default(none) private(i) shared(N,xd,wd,idd) \ reduction(+:sum) schedule(static) num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) { if (idd[i] > ZERO) { sum += SUNSQR(xd[i]*wd[i]); } } return(sum); } /* * ----------------------------------------------------------------- * fused vector operations * ----------------------------------------------------------------- */ int N_VLinearCombination_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector z) { int i; sunindextype j, N; realtype* zd=NULL; realtype* xd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], z); return(0); } /* should have called N_VLinearSum */ if (nvec == 2) { N_VLinearSum_OpenMP(c[0], X[0], c[1], X[1], z); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(z); zd = NV_DATA_OMP(z); /* * X[0] += c[i]*X[i], i = 1,...,nvec-1 */ if ((X[0] == z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * X[0] = c[0] * X[0] + sum{ c[i] * X[i] }, i = 1,...,nvec-1 */ if (X[0] == z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] *= c[0]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } /* * z = sum{ c[i] * X[i] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c,zd) \ num_threads(NV_NUM_THREADS_OMP(z)) { xd = NV_DATA_OMP(X[0]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[0] * xd[j]; } for (i=1; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] += c[i] * xd[j]; } } } return(0); } int N_VScaleAddMulti_OpenMP(int nvec, realtype* a, N_Vector x, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a[0], x, ONE, Y[0], Z[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,yd) shared(nvec,Y,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { yd[j] += a[i] * xd[j]; } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,yd,zd) shared(nvec,Y,Z,N,a,xd) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a[i] * xd[j] + yd[j]; } } } return(0); } int N_VDotProdMulti_OpenMP(int nvec, N_Vector x, N_Vector* Y, realtype* dotprods) { int i; sunindextype j, N; realtype sum; realtype* xd=NULL; realtype* yd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VDotProd */ if (nvec == 1) { dotprods[0] = N_VDotProd_OpenMP(x, Y[0]); return(0); } /* get vector length and data array */ N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); /* initialize dot products */ for (i=0; i<nvec; i++) { dotprods[i] = ZERO; } /* compute multiple dot products */ #pragma omp parallel default(none) private(i,j,yd,sum) shared(nvec,Y,N,xd,dotprods) \ num_threads(NV_NUM_THREADS_OMP(x)) { for (i=0; i<nvec; i++) { yd = NV_DATA_OMP(Y[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += xd[j] * yd[j]; } #pragma omp critical { dotprods[i] += sum; } } } return(0); } /* * ----------------------------------------------------------------- * vector array operations * ----------------------------------------------------------------- */ int N_VLinearSumVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, realtype b, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; realtype c; N_Vector* V1; N_Vector* V2; booleantype test; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VLinearSum */ if (nvec == 1) { N_VLinearSum_OpenMP(a, X[0], b, Y[0], Z[0]); return(0); } /* BLAS usage: axpy y <- ax+y */ if ((b == ONE) && (Z == Y)) return(VaxpyVectorArray_OpenMP(nvec, a, X, Y)); /* BLAS usage: axpy x <- by+x */ if ((a == ONE) && (Z == X)) return(VaxpyVectorArray_OpenMP(nvec, b, Y, X)); /* Case: a == b == 1.0 */ if ((a == ONE) && (b == ONE)) return(VSumVectorArray_OpenMP(nvec, X, Y, Z)); /* Cases: */ /* (1) a == 1.0, b = -1.0, */ /* (2) a == -1.0, b == 1.0 */ if ((test = ((a == ONE) && (b == -ONE))) || ((a == -ONE) && (b == ONE))) { V1 = test ? Y : X; V2 = test ? X : Y; return(VDiffVectorArray_OpenMP(nvec, V2, V1, Z)); } /* Cases: */ /* (1) a == 1.0, b == other or 0.0, */ /* (2) a == other or 0.0, b == 1.0 */ /* if a or b is 0.0, then user should have called N_VScale */ if ((test = (a == ONE)) || (b == ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin1VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Cases: */ /* (1) a == -1.0, b != 1.0, */ /* (2) a != 1.0, b == -1.0 */ if ((test = (a == -ONE)) || (b == -ONE)) { c = test ? b : a; V1 = test ? Y : X; V2 = test ? X : Y; return(VLin2VectorArray_OpenMP(nvec, c, V1, V2, Z)); } /* Case: a == b */ /* catches case both a and b are 0.0 - user should have called N_VConst */ if (a == b) return(VScaleSumVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Case: a == -b */ if (a == -b) return(VScaleDiffVectorArray_OpenMP(nvec, a, X, Y, Z)); /* Do all cases not handled above: */ /* (1) a == other, b == 0.0 - user should have called N_VScale */ /* (2) a == 0.0, b == other - user should have called N_VScale */ /* (3) a,b == other, a !=b, a != -b */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* compute linear sum for each vector pair in vector arrays */ #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a,b) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = a * xd[j] + b * yd[j]; } } } return(0); } int N_VScaleVectorArray_OpenMP(int nvec, realtype* c, N_Vector* X, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VScale */ if (nvec == 1) { N_VScale_OpenMP(c[0], X[0], Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[i] *= c[i] */ if (X == Z) { #pragma omp parallel default(none) private(i,j,xd) shared(nvec,X,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { xd[j] *= c[i]; } } } return(0); } /* * Z[i] = c[i] * X[i] */ #pragma omp parallel default(none) private(i,j,xd,zd) shared(nvec,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c[i] * xd[j]; } } } return(0); } int N_VConstVectorArray_OpenMP(int nvec, realtype c, N_Vector* Z) { int i; sunindextype j, N; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VConst */ if (nvec == 1) { N_VConst_OpenMP(c, Z[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* set each vector in the vector array to a constant */ #pragma omp parallel default(none) private(i,j,zd) shared(nvec,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (i=0; i<nvec; i++) { zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) { zd[j] = c; } } } return(0); } int N_VWrmsNormVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNorm_OpenMP(X[0], W[0]); return(0); } /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VWrmsNormMaskVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* W, N_Vector id, realtype* nrm) { int i; sunindextype j, N; realtype sum; realtype* wd=NULL; realtype* xd=NULL; realtype* idd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); /* should have called N_VWrmsNorm */ if (nvec == 1) { nrm[0] = N_VWrmsNormMask_OpenMP(X[0], W[0], id); return(0); } /* get vector length and mask data array */ N = NV_LENGTH_OMP(X[0]); idd = NV_DATA_OMP(id); /* initialize norms */ for (i=0; i<nvec; i++) { nrm[i] = ZERO; } /* compute the WRMS norm for each vector in the vector array */ #pragma omp parallel default(none) private(i,j,xd,wd,sum) shared(nvec,X,W,N,idd,nrm) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); wd = NV_DATA_OMP(W[i]); sum = ZERO; #pragma omp for schedule(static) for (j=0; j<N; j++) { if (idd[j] > ZERO) sum += SUNSQR(xd[j] * wd[j]); } #pragma omp critical { nrm[i] += sum; } } } for (i=0; i<nvec; i++) { nrm[i] = SUNRsqrt(nrm[i]/N); } return(0); } int N_VScaleAddMultiVectorArray_OpenMP(int nvec, int nsum, realtype* a, N_Vector* X, N_Vector** Y, N_Vector** Z) { int i, j; sunindextype k, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; int retval; N_Vector* YY; N_Vector* ZZ; i = 0; /* initialize to suppress clang warning */ k = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VLinearSum */ if (nsum == 1) { N_VLinearSum_OpenMP(a[0], X[0], ONE, Y[0][0], Z[0][0]); return(0); } /* should have called N_VScaleAddMulti */ YY = (N_Vector*) malloc(nsum * sizeof(N_Vector)); ZZ = (N_Vector*) malloc(nsum * sizeof(N_Vector)); for (j=0; j<nsum; j++) { YY[j] = Y[j][0]; ZZ[j] = Z[j][0]; } retval = N_VScaleAddMulti_OpenMP(nsum, a, X[0], YY, ZZ); free(YY); free(ZZ); return(retval); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VLinearSumVectorArray */ if (nsum == 1) { retval = N_VLinearSumVectorArray_OpenMP(nvec, a[0], X, ONE, Y[0], Z[0]); return(retval); } /* ---------------------------- * Compute multiple linear sums * ---------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(X[0]); /* * Y[i][j] += a[i] * x[j] */ if (Y == Z) { #pragma omp parallel default(none) private(i,j,k,xd,yd) shared(nvec,nsum,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { yd[k] += a[j] * xd[k]; } } } } return(0); } /* * Z[i][j] = Y[i][j] + a[i] * x[j] */ #pragma omp parallel default(none) private(i,j,k,xd,yd,zd) shared(nvec,nsum,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); for (j=0; j<nsum; j++) { yd = NV_DATA_OMP(Y[j][i]); zd = NV_DATA_OMP(Z[j][i]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = a[j] * xd[k] + yd[k]; } } } } return(0); } int N_VLinearCombinationVectorArray_OpenMP(int nvec, int nsum, realtype* c, N_Vector** X, N_Vector* Z) { int i; /* vector arrays index in summation [0,nsum) */ int j; /* vector index in vector array [0,nvec) */ sunindextype k; /* element index in vector [0,N) */ sunindextype N; realtype* zd=NULL; realtype* xd=NULL; realtype* ctmp; N_Vector* Y; i = 0; /* initialize to suppress clang warning */ k = 0; /* invalid number of vectors */ if (nvec < 1) return(-1); if (nsum < 1) return(-1); /* --------------------------- * Special cases for nvec == 1 * --------------------------- */ if (nvec == 1) { /* should have called N_VScale */ if (nsum == 1) { N_VScale_OpenMP(c[0], X[0][0], Z[0]); return(0); } /* should have called N_VLinearSum */ if (nsum == 2) { N_VLinearSum_OpenMP(c[0], X[0][0], c[1], X[1][0], Z[0]); return(0); } /* should have called N_VLinearCombination */ Y = (N_Vector*) malloc(nsum * sizeof(N_Vector)); for (i=0; i<nsum; i++) { Y[i] = X[i][0]; } N_VLinearCombination_OpenMP(nsum, c, Y, Z[0]); free(Y); return(0); } /* -------------------------- * Special cases for nvec > 1 * -------------------------- */ /* should have called N_VScaleVectorArray */ if (nsum == 1) { ctmp = (realtype*) malloc(nvec * sizeof(realtype)); for (j=0; j<nvec; j++) { ctmp[j] = c[0]; } N_VScaleVectorArray_OpenMP(nvec, ctmp, X[0], Z); free(ctmp); return(0); } /* should have called N_VLinearSumVectorArray */ if (nsum == 2) { N_VLinearSumVectorArray_OpenMP(nvec, c[0], X[0], c[1], X[1], Z); return(0); } /* -------------------------- * Compute linear combination * -------------------------- */ /* get vector length */ N = NV_LENGTH_OMP(Z[0]); /* * X[0][j] += c[i]*X[i][j], i = 1,...,nvec-1 */ if ((X[0] == Z) && (c[0] == ONE)) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * X[0][j] = c[0] * X[0][j] + sum{ c[i] * X[i][j] }, i = 1,...,nvec-1 */ if (X[0] == Z) { #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] *= c[0]; } for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * Z[j] = sum{ c[i] * X[i][j] }, i = 0,...,nvec-1 */ #pragma omp parallel default(none) private(i,j,k,xd,zd) shared(nvec,nsum,X,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(Z[0])) { for (j=0; j<nvec; j++) { /* scale first vector in the sum into the output vector */ xd = NV_DATA_OMP(X[0][j]); zd = NV_DATA_OMP(Z[j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] = c[0] * xd[k]; } /* scale and sum remaining vectors into the output vector */ for (i=1; i<nsum; i++) { xd = NV_DATA_OMP(X[i][j]); #pragma omp for schedule(static) for (k=0; k<N; k++) { zd[k] += c[i] * xd[k]; } } } } return(0); } /* * ----------------------------------------------------------------- * OPTIONAL XBraid interface operations * ----------------------------------------------------------------- */ int N_VBufSize_OpenMP(N_Vector x, sunindextype *size) { if (x == NULL) return(-1); *size = NV_LENGTH_OMP(x) * ((sunindextype)sizeof(realtype)); return(0); } int N_VBufPack_OpenMP(N_Vector x, void *buf) { sunindextype i, N; realtype *xd = NULL; realtype *bd = NULL; if (x == NULL || buf == NULL) return(-1); N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); bd = (realtype*) buf; #pragma omp for schedule(static) for (i = 0; i < N; i++) bd[i] = xd[i]; return(0); } int N_VBufUnpack_OpenMP(N_Vector x, void *buf) { sunindextype i, N; realtype *xd = NULL; realtype *bd = NULL; if (x == NULL || buf == NULL) return(-1); N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); bd = (realtype*) buf; #pragma omp for schedule(static) for (i = 0; i < N; i++) xd[i] = bd[i]; return(0); } /* * ----------------------------------------------------------------- * private functions for special cases of vector operations * ----------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- * Copy vector components into a second vector */ static void VCopy_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector sum */ static void VSum_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference */ static void VDiff_OpenMP(N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = xd[i]-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute the negative of a vector */ static void VNeg_OpenMP(N_Vector x, N_Vector z) { sunindextype i, N; realtype *xd, *zd; i = 0; /* initialize to suppress clang warning */ xd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,xd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = -xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector sum */ static void VScaleSum_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]+yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute scaled vector difference */ static void VScaleDiff_OpenMP(realtype c, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,c,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = c*(xd[i]-yd[i]); return; } /* ---------------------------------------------------------------------------- * Compute vector sum z[i] = a*x[i]+y[i] */ static void VLin1_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])+yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute vector difference z[i] = a*x[i]-y[i] */ static void VLin2_OpenMP(realtype a, N_Vector x, N_Vector y, N_Vector z) { sunindextype i, N; realtype *xd, *yd, *zd; i = 0; /* initialize to suppress clang warning */ xd = yd = zd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); zd = NV_DATA_OMP(z); #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd,zd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) zd[i] = (a*xd[i])-yd[i]; return; } /* ---------------------------------------------------------------------------- * Compute special cases of linear sum */ static void Vaxpy_OpenMP(realtype a, N_Vector x, N_Vector y) { sunindextype i, N; realtype *xd, *yd; i = 0; /* initialize to suppress clang warning */ xd = yd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); yd = NV_DATA_OMP(y); if (a == ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += xd[i]; return; } if (a == -ONE) { #pragma omp parallel for default(none) private(i) shared(N,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] -= xd[i]; return; } #pragma omp parallel for default(none) private(i) shared(N,a,xd,yd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) yd[i] += a*xd[i]; return; } /* ---------------------------------------------------------------------------- * Compute scaled vector x[i] = a*x[i] */ static void VScaleBy_OpenMP(realtype a, N_Vector x) { sunindextype i, N; realtype *xd; i = 0; /* initialize to suppress clang warning */ xd = NULL; N = NV_LENGTH_OMP(x); xd = NV_DATA_OMP(x); #pragma omp parallel for default(none) private(i) shared(N,a,xd) schedule(static) \ num_threads(NV_NUM_THREADS_OMP(x)) for (i = 0; i < N; i++) xd[i] *= a; return; } /* * ----------------------------------------------------------------- * private functions for special cases of vector array operations * ----------------------------------------------------------------- */ static int VSumVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] + yd[j]; } } return(0); } static int VDiffVectorArray_OpenMP(int nvec, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = xd[j] - yd[j]; } } return(0); } static int VScaleSumVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] + yd[j]); } } return(0); } static int VScaleDiffVectorArray_OpenMP(int nvec, realtype c, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,c) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = c * (xd[j] - yd[j]); } } return(0); } static int VLin1VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) + yd[j]; } } return(0); } static int VLin2VectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y, N_Vector* Z) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; realtype* zd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); #pragma omp parallel default(none) private(i,j,xd,yd,zd) shared(nvec,X,Y,Z,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); zd = NV_DATA_OMP(Z[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) zd[j] = (a * xd[j]) - yd[j]; } } return(0); } static int VaxpyVectorArray_OpenMP(int nvec, realtype a, N_Vector* X, N_Vector* Y) { int i; sunindextype j, N; realtype* xd=NULL; realtype* yd=NULL; i = 0; /* initialize to suppress clang warning */ j = 0; N = NV_LENGTH_OMP(X[0]); if (a == ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += xd[j]; } } return(0); } if (a == -ONE) { #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] -= xd[j]; } } return(0); } #pragma omp parallel default(none) private(i,j,xd,yd) shared(nvec,X,Y,N,a) \ num_threads(NV_NUM_THREADS_OMP(X[0])) { for (i=0; i<nvec; i++) { xd = NV_DATA_OMP(X[i]); yd = NV_DATA_OMP(Y[i]); #pragma omp for schedule(static) for (j=0; j<N; j++) yd[j] += a * xd[j]; } } return(0); } /* * ----------------------------------------------------------------- * Enable / Disable fused and vector array operations * ----------------------------------------------------------------- */ int N_VEnableFusedOps_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); if (tf) { /* enable all fused vector operations */ v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; /* enable all vector array operations */ v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; } else { /* disable all fused vector operations */ v->ops->nvlinearcombination = NULL; v->ops->nvscaleaddmulti = NULL; v->ops->nvdotprodmulti = NULL; /* disable all vector array operations */ v->ops->nvlinearsumvectorarray = NULL; v->ops->nvscalevectorarray = NULL; v->ops->nvconstvectorarray = NULL; v->ops->nvwrmsnormvectorarray = NULL; v->ops->nvwrmsnormmaskvectorarray = NULL; v->ops->nvscaleaddmultivectorarray = NULL; v->ops->nvlinearcombinationvectorarray = NULL; } /* return success */ return(0); } int N_VEnableLinearCombination_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombination = N_VLinearCombination_OpenMP; else v->ops->nvlinearcombination = NULL; /* return success */ return(0); } int N_VEnableScaleAddMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmulti = N_VScaleAddMulti_OpenMP; else v->ops->nvscaleaddmulti = NULL; /* return success */ return(0); } int N_VEnableDotProdMulti_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvdotprodmulti = N_VDotProdMulti_OpenMP; else v->ops->nvdotprodmulti = NULL; /* return success */ return(0); } int N_VEnableLinearSumVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearsumvectorarray = N_VLinearSumVectorArray_OpenMP; else v->ops->nvlinearsumvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscalevectorarray = N_VScaleVectorArray_OpenMP; else v->ops->nvscalevectorarray = NULL; /* return success */ return(0); } int N_VEnableConstVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvconstvectorarray = N_VConstVectorArray_OpenMP; else v->ops->nvconstvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormvectorarray = N_VWrmsNormVectorArray_OpenMP; else v->ops->nvwrmsnormvectorarray = NULL; /* return success */ return(0); } int N_VEnableWrmsNormMaskVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvwrmsnormmaskvectorarray = N_VWrmsNormMaskVectorArray_OpenMP; else v->ops->nvwrmsnormmaskvectorarray = NULL; /* return success */ return(0); } int N_VEnableScaleAddMultiVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvscaleaddmultivectorarray = N_VScaleAddMultiVectorArray_OpenMP; else v->ops->nvscaleaddmultivectorarray = NULL; /* return success */ return(0); } int N_VEnableLinearCombinationVectorArray_OpenMP(N_Vector v, booleantype tf) { /* check that vector is non-NULL */ if (v == NULL) return(-1); /* check that ops structure is non-NULL */ if (v->ops == NULL) return(-1); /* enable/disable operation */ if (tf) v->ops->nvlinearcombinationvectorarray = N_VLinearCombinationVectorArray_OpenMP; else v->ops->nvlinearcombinationvectorarray = NULL; /* return success */ return(0); }
trsm_x_dia_u_lo_col.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_DIA *A, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, ALPHA_Number *y, const ALPHA_INT ldy) { ALPHA_INT m = A->rows; ALPHA_INT main_diag_pos = 0; int num_thread = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT i = 0; i < A->ndiag; i++) if(A->distance[i] == 0) { main_diag_pos = i; } #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for(ALPHA_INT out_y_col = 0; out_y_col < columns; out_y_col++) { for (ALPHA_INT r = 0; r < m; r++) { ALPHA_Number temp; alpha_setzero(temp); for (ALPHA_INT ndiag = 0; ndiag < main_diag_pos; ndiag++) { if (-A->distance[ndiag] <= r) { ALPHA_INT ac = r + A->distance[ndiag]; alpha_madde(temp, A->values[ndiag * A->lval + r], y[out_y_col * ldy + ac]); } } ALPHA_Number t; alpha_setzero(t); alpha_mul(t, alpha, x[out_y_col * ldx + r]); alpha_sub(y[out_y_col * ldy + r], t, temp); } } return ALPHA_SPARSE_STATUS_SUCCESS; }
core_dpotrf_blasfeo.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from core_blas/core_zpotrf.c, normal z -> d, Thu Aug 8 17:24:58 2019 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" #include "blasfeo_d_aux.h" /***************************************************************************//** * * @ingroup core_potrf * * Performs the Cholesky factorization of a symmetric positive definite * matrix A. The factorization has the form * * \f[ A = L \times L^T, \f] * or * \f[ A = U^T \times U, \f] * * where U is an upper triangular matrix and L is a lower triangular matrix. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] A * On entry, the symmetric positive definite matrix A. * If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A * contains the upper triangular part of the matrix A, and the strictly * lower triangular part of A is not referenced. * If uplo = PlasmaLower, the leading N-by-N lower triangular part of A * contains the lower triangular part of the matrix A, and the strictly * upper triangular part of A is not referenced. * On exit, if return value = 0, the factor U or L from the Cholesky * factorization A = U^T*U or A = L*L^T. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * ******************************************************************************/ __attribute__((weak)) int plasma_core_dpotrf_blasfeo(plasma_enum_t uplo, int n, struct blasfeo_dmat *sA, int ai, int aj) { // return LAPACKE_dpotrf_work(LAPACK_COL_MAJOR, // lapack_const(uplo), // n, // A, lda); fprintf(stderr, "before blasfeo dpotrf ai: %d aj: %d\n", ai, aj); blasfeo_dpotrf_l(n, sA, ai, aj, sA, ai, aj); return 0; } /******************************************************************************/ void plasma_core_omp_dpotrf_blasfeo(plasma_enum_t uplo, int n, struct blasfeo_dmat *sA, int ai, int aj, int iinfo, plasma_sequence_t *sequence, plasma_request_t *request) { // make a local copy of the structure, such that the orignal one can be safely destroyed when out of scope struct blasfeo_dmat sA2; sA2 = *sA; double *A = sA->pA; int sda = sA->cn; // #pragma omp task depend(inout:A[0:lda*n]) #pragma omp task depend(inout:A[0:sda*n]) { if (sequence->status == PlasmaSuccess) { fprintf(stderr, "before core dpotrf2\n"); int info = plasma_core_dpotrf_blasfeo(uplo, n, &sA2, ai, aj); if (info != 0) plasma_request_fail(sequence, request, iinfo+info); } } }
seq_multivector.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Member functions for hypre_Vector class. * *****************************************************************************/ #include "seq_multivector.h" #include "_hypre_utilities.h" #include <stdlib.h> #include <string.h> #include <assert.h> /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCreate *--------------------------------------------------------------------------*/ hypre_Multivector * hypre_SeqMultivectorCreate( HYPRE_Int size, HYPRE_Int num_vectors ) { hypre_Multivector *mvector; mvector = (hypre_Multivector *) hypre_MAlloc(sizeof(hypre_Multivector), HYPRE_MEMORY_HOST); hypre_MultivectorNumVectors(mvector) = num_vectors; hypre_MultivectorSize(mvector) = size; hypre_MultivectorOwnsData(mvector) = 1; hypre_MultivectorData(mvector) = NULL; mvector->num_active_vectors=0; mvector->active_indices=NULL; return mvector; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInitialize *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInitialize( hypre_Multivector *mvector ) { HYPRE_Int ierr = 0, i, size, num_vectors; size = hypre_MultivectorSize(mvector); num_vectors = hypre_MultivectorNumVectors(mvector); if (NULL==hypre_MultivectorData(mvector)) hypre_MultivectorData(mvector) = (HYPRE_Complex *) hypre_MAlloc(sizeof(HYPRE_Complex)*size*num_vectors, HYPRE_MEMORY_HOST); /* now we create a "mask" of "active" vectors; initially all active */ if (NULL==mvector->active_indices) { mvector->active_indices hypre_CTAlloc(HYPRE_Int, num_vectors, HYPRE_MEMORY_HOST); for (i=0; i<num_vectors; i++) mvector->active_indices[i] = i; mvector->num_active_vectors=num_vectors; } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetDataOwner *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetDataOwner(hypre_Multivector *mvector, HYPRE_Int owns_data) { HYPRE_Int ierr=0; hypre_MultivectorOwnsData(mvector) = owns_data; return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorDestroy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorDestroy(hypre_Multivector *mvector) { HYPRE_Int ierr=0; if (NULL!=mvector) { if (hypre_MultivectorOwnsData(mvector) && NULL!=hypre_MultivectorData(mvector)) hypre_TFree( hypre_MultivectorData(mvector) , HYPRE_MEMORY_HOST); if (NULL!=mvector->active_indices) hypre_TFree(mvector->active_indices, HYPRE_MEMORY_HOST); hypre_TFree(mvector, HYPRE_MEMORY_HOST); } return ierr; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetMask * (this routine accepts mask in "zeros and ones format, and converts it to the one used in the structure "hypre_Multivector") *-------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetMask(hypre_Multivector *mvector, HYPRE_Int * mask) { HYPRE_Int i, num_vectors = mvector->num_vectors; if (mvector->active_indices != NULL) hypre_TFree(mvector->active_indices, HYPRE_MEMORY_HOST); mvector->active_indices hypre_CTAlloc(HYPRE_Int, num_vectors, HYPRE_MEMORY_HOST); mvector->num_active_vectors=0; if (mask!=NULL) for (i=0; i<num_vectors; i++) { if ( mask[i] ) mvector->active_indices[mvector->num_active_vectors++]=i; } else for (i=0; i<num_vectors; i++) mvector->active_indices[mvector->num_active_vectors++]=i; return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetConstantValues *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetConstantValues(hypre_Multivector *v, HYPRE_Complex value) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); if (v->num_active_vectors == v->num_vectors) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = value; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = start_offset; j < end_offset; j++) vector_data[j]= value; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorSetRandomValues * * returns vector of values randomly distributed between -1.0 and +1.0 *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorSetRandomValues(hypre_Multivector *v, HYPRE_Int seed) { HYPRE_Int i, j, start_offset, end_offset; HYPRE_Int size = hypre_MultivectorSize(v); HYPRE_Complex *vector_data = hypre_MultivectorData(v); hypre_SeedRand(seed); /* comment from vector.c: RDF: threading this loop may cause problems because of hypre_Rand() */ if (v->num_active_vectors == v->num_vectors) { for (j = 0; j < v->num_vectors*size; j++) vector_data[j] = 2.0 * hypre_Rand() - 1.0; } else { for (i = 0; i < v->num_active_vectors; i++) { start_offset = v->active_indices[i]*size; end_offset = start_offset+size; for (j = start_offset; j < end_offset; j++) vector_data[j]= 2.0 * hypre_Rand() - 1.0; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorCopy * copies data from x to y * y should have already been initialized at the same size as x *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorCopy(hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, size, num_bytes, num_active_vectors, *x_active_ind, * y_active_ind; HYPRE_Complex *x_data, *y_data, *dest, * src; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); num_active_vectors = x->num_active_vectors; size = x->size; x_data = x->data; y_data = y->data; x_active_ind=x->active_indices; y_active_ind=y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { num_bytes = x->num_vectors * size; hypre_TMemcpy(y_data, x_data, HYPRE_Complex, num_bytes, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); } else { num_bytes = size; for (i=0; i < num_active_vectors; i++) { src=x_data + size * x_active_ind[i]; dest = y_data + size * y_active_ind[i]; hypre_Memcpy(dest, src, HYPRE_Complex, num_bytes, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); } } return 0; } HYPRE_Int hypre_SeqMultivectorCopyWithoutMask(hypre_Multivector *x , hypre_Multivector *y) { HYPRE_Int byte_count; hypre_assert (x->size == y->size && x->num_vectors == y->num_vectors); byte_count = x->size * x->num_vectors; hypre_Memcpy(y->data, x->data, HYPRE_Complex, byte_count, HYPRE_MEMORY_HOST, HYPRE_MEMORY_HOST); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorAxpy *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorAxpy(HYPRE_Complex alpha, hypre_Multivector *x, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *src, *dest; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; if (x->num_active_vectors == x->num_vectors && y->num_active_vectors == y->num_vectors) { for(i = 0; i < x->num_vectors*size; i++) dest[i] += alpha * src[i]; } else { for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] += alpha * src[j]; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorByDiag: " y(<y_mask>) = alpha(<mask>) .* x(<x_mask>) " *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorByDiag(hypre_Multivector *x, HYPRE_Int *mask, HYPRE_Int n, HYPRE_Complex *alpha, hypre_Multivector *y) { HYPRE_Int i, j, size, num_active_vectors, *x_active_ind, *y_active_ind; HYPRE_Int *al_active_ind, num_active_als; HYPRE_Complex *x_data, *y_data, *dest, *src, current_alpha; hypre_assert (x->size == y->size && x->num_active_vectors == y->num_active_vectors); /* build list of active indices in alpha */ al_active_ind = hypre_TAlloc(HYPRE_Int, n, HYPRE_MEMORY_HOST); num_active_als = 0; if (mask!=NULL) for (i=0; i<n; i++) { if (mask[i]) al_active_ind[num_active_als++]=i; } else for (i=0; i<n; i++) al_active_ind[num_active_als++]=i; hypre_assert (num_active_als==x->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(i = 0; i < num_active_vectors; i++) { src = x_data + x_active_ind[i]*size; dest = y_data + y_active_ind[i]*size; current_alpha=alpha[ al_active_ind[i] ]; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < size; j++) dest[j] = current_alpha*src[j]; } hypre_TFree(al_active_ind, HYPRE_MEMORY_HOST); return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProd *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProd(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *results ) { HYPRE_Int i, j, k, size, *x_active_ind, *y_active_ind; HYPRE_Int x_num_active_vectors, y_num_active_vectors; HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; hypre_assert (x->size==y->size); x_data = x->data; y_data = y->data; size = x->size; x_num_active_vectors = x->num_active_vectors; y_num_active_vectors = y->num_active_vectors; /* we assume that "results" points to contiguous array of (x_num_active_vectors X y_num_active_vectors) doubles */ x_active_ind = x->active_indices; y_active_ind = y->active_indices; for(j = 0; j < y_num_active_vectors; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i = 0; i < x_num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k = 0; k < size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); /* column-wise storage for results */ *results++ = current_product; } } return 0; } /*-------------------------------------------------------------------------- * hypre_SeqMultivectorInnerProdDiag *--------------------------------------------------------------------------*/ HYPRE_Int hypre_SeqMultivectorInnerProdDiag(hypre_Multivector *x, hypre_Multivector *y, HYPRE_Real *diagResults) { HYPRE_Complex *x_data, *y_data, *y_ptr, *x_ptr; HYPRE_Real current_product; HYPRE_Int i, k, size, num_active_vectors, *x_active_ind, *y_active_ind; hypre_assert(x->size==y->size && x->num_active_vectors == y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; num_active_vectors = x->num_active_vectors; x_active_ind = x->active_indices; y_active_ind = y->active_indices; for (i=0; i<num_active_vectors; i++) { x_ptr = x_data + x_active_ind[i]*size; y_ptr = y_data + y_active_ind[i]*size; current_product = 0.0; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) reduction(+:current_product) HYPRE_SMP_SCHEDULE #endif for(k=0; k<size; k++) current_product += x_ptr[k] * hypre_conj(y_ptr[k]); *diagResults++ = current_product; } return 0; } HYPRE_Int hypre_SeqMultivectorByMatrix(hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; hypre_assert(rHeight>0); hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; /* ------ set current "y" to first member in a sum ------ */ x_ptr = x_data + x_active_ind[0]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] = current_coef * x_ptr[k]; /* ------ now add all other members of a sum to "y" ----- */ for (i=1; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; } HYPRE_Int hypre_SeqMultivectorXapy (hypre_Multivector *x, HYPRE_Int rGHeight, HYPRE_Int rHeight, HYPRE_Int rWidth, HYPRE_Complex* rVal, hypre_Multivector *y) { HYPRE_Complex *x_data, *y_data, *x_ptr, *y_ptr, current_coef; HYPRE_Int i, j, k, size, gap, *x_active_ind, *y_active_ind; hypre_assert (rHeight==x->num_active_vectors && rWidth==y->num_active_vectors); x_data = x->data; y_data = y->data; size = x->size; x_active_ind = x->active_indices; y_active_ind = y->active_indices; gap = rGHeight - rHeight; for (j=0; j<rWidth; j++) { y_ptr = y_data + y_active_ind[j]*size; for (i=0; i<rHeight; i++) { x_ptr = x_data + x_active_ind[i]*size; current_coef = *rVal++; #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(k) HYPRE_SMP_SCHEDULE #endif for (k=0; k<size; k++) y_ptr[k] += current_coef * x_ptr[k]; } rVal += gap; } return 0; }
pqECDSA_verify.c
/* Name: pqECDSA_verify.c Author: Tan Teik Guan Description: Verify function for pq resistance for ECDSA using ZKBoo. Modified from MPC_SHA256_VERIFIER.c */ /* ============================================================================ Name : MPC_SHA256_VERIFIER.c Author : Sobuno Version : 0.1 Description : Verifies a proof for SHA-256 generated by MPC_SHA256.c ============================================================================ */ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "pqECDSA_shared.h" int NUM_ROUNDS = 100; int numLoops = 1; void printbits(uint32_t n) { if (n) { printbits(n >> 1); printf("%d", n & 1); } } int main(int argc, char * argv[]) { setbuf(stdout, NULL); init_EVP(); openmp_thread_setup(); unsigned char tbs[MSG_SIZE]; unsigned char r[MSG_SIZE]; unsigned char S[MSG_SIZE]; int i; if (argc != 5) { printf("Usage: %s <number of rounds (e.g. 20, 40, 60, 80, 100)> <to be signed (Hex 64 char)> <Signature r (Hex 64 char)> <Signature s (Hex 64 char)\n",argv[0]); return -1; } NUM_ROUNDS = atoi(argv[1]); hexToBin32(argv[2],tbs); hexToBin32(argv[3],r); hexToBin32(argv[4],S); printf("Iterations of SHA: %d\n", NUM_ROUNDS); a as[NUM_ROUNDS]; z zs[NUM_ROUNDS]; FILE *file; char outputFile[3*sizeof(int) + 8]; sprintf(outputFile, "ECDSA%i.bin", NUM_ROUNDS); file = fopen(outputFile, "rb"); if (!file) { printf("Unable to open file!"); return -1; } fread(&as, sizeof(a), NUM_ROUNDS, file); fread(&zs, sizeof(z), NUM_ROUNDS, file); fclose(file); struct timeval begin, delta; gettimeofday(&begin,NULL); for (int loops=0;loops<numLoops;loops++) { int err = 0; uint32_t y[32]; for (int i = 0; i< 32; i++) y[i] = as[0].yp[0][i]^as[0].yp[1][i]^as[0].yp[2][i]; int es[NUM_ROUNDS*2]; H3(y,as, NUM_ROUNDS, es); #pragma omp parallel for for(int i = 0; i<(NUM_ROUNDS); i++) { unsigned char bufx[32],bufy[32]; MP_INT bigS,bigr; MP_INT Pubx,Puby; MP_INT bigu1,bigu2; MP_INT bigGx, bigGy; MP_INT biginvS; MP_INT bigH,mod; err = 0; mpz_init(&bigS); mpz_init(&bigr); mpz_init(&Pubx); mpz_init(&Puby); ecReconstruct(&(as[i].yp[0][0]),&(as[i].yp[1][0]),&(as[i].yp[2][0]),&(as[i].yp[0][8]),&(as[i].yp[1][8]),&(as[i].yp[2][8]),bufx,bufy); mpz_import(&Pubx,32,1,1,0,0,bufx); mpz_import(&Puby,32,1,1,0,0,bufy); mpz_import(&bigr,8,1,4,0,0,&(as[0].yp[0][16])); mpz_import(&bigS,32,1,1,0,0,r); if (mpz_cmp(&bigr,&bigS)) { printf("signature r does not match: "); mpz_out_str(stdout,16,&bigr); printf("vs "); mpz_out_str(stdout,16,&bigS); printf("\n"); err |= 1; } reconstruct(&(as[0].yp[0][24]),&(as[0].yp[1][24]),&(as[0].yp[2][24]),bufx); mpz_import(&bigS,32,1,1,0,0,bufx); for (int i=0; i<32;i++) { if (bufx[i] != S[i]) { printf("signature S at byte %d [%02X][%02x] does not match\n",i,bufx[i],S[i]); err |= 2; } } // printf("verifying signature for ECDSA(tbs): "); mpz_init(&biginvS); mpz_init(&bigu1); mpz_init(&bigu2); mpz_init(&bigH); mpz_import(&bigH,32,1,1,0,0,tbs); mpz_init_set_str(&mod,CURVE_N,16); ecInvMod(&biginvS,&bigS,&mod); mpz_mul(&bigu1,&bigH,&biginvS); mpz_mod(&bigu1,&bigu1,&mod); mpz_mul(&bigu2,&bigr,&biginvS); mpz_mod(&bigu2,&bigu2,&mod); mpz_init_set_str(&bigGx,CURVE_Gx,16); mpz_init_set_str(&bigGy,CURVE_Gy,16); ecMul(&bigGx,&bigGy,&bigu1); ecMul(&Pubx,&Puby,&bigu2); ecAddPoint(&bigGx,&bigGy,&Pubx,&Puby); mpz_mod(&bigGx,&bigGx,&mod); if (mpz_cmp(&bigGx,&bigr)) { printf("invalid r. computed r : "); mpz_out_str(stdout,16,&bigGx); printf("\n"); err |= 4; } if (!err) { int verifyResult = verify(as[i], es[i], zs[i]); if (verifyResult != 0) { printf("round [%d] : Not Verified rc = %d\n", i, verifyResult); } else { printf("round [%d] ok \n",i); } } else printf("round [%d] error code = %d\n",i,err); mpz_clear(&biginvS); mpz_clear(&bigu1); mpz_clear(&bigu2); mpz_clear(&bigH); mpz_clear(&bigS); mpz_clear(&bigr); mpz_clear(&Pubx); mpz_clear(&Puby); mpz_clear(&mod); mpz_clear(&bigGx); mpz_clear(&bigGy); } } gettimeofday(&delta,NULL); unsigned long inMilli = (delta.tv_sec - begin.tv_sec)*1000000 + (delta.tv_usec - begin.tv_usec); inMilli /= 1000; printf("Total time for %d loops of %d rounds: %ju miliseconds\n", numLoops,NUM_ROUNDS,(uintmax_t)inMilli); printf("Time taken for 1 loops: %ju miliseconds\n", (uintmax_t)inMilli/numLoops); openmp_thread_cleanup(); cleanup_EVP(); return EXIT_SUCCESS; }
GB_unaryop__abs_uint16_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint16_fp32 // op(A') function: GB_tran__abs_uint16_fp32 // C type: uint16_t // A type: float // cast: uint16_t cij ; GB_CAST_UNSIGNED(cij,aij,16) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint16_t z ; GB_CAST_UNSIGNED(z,x,16) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT16 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint16_fp32 ( uint16_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint16_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__bget_uint16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_uint16) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__bget_uint16) // A.*B function (eWiseMult): GB (_AemultB_03__bget_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_uint16) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__bget_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_uint16) // C=scalar+B GB (_bind1st__bget_uint16) // C=scalar+B' GB (_bind1st_tran__bget_uint16) // C=A+scalar GB (_bind2nd__bget_uint16) // C=A'+scalar GB (_bind2nd_tran__bget_uint16) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = GB_BITGET (aij, bij, uint16_t, 16) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_BITGET (x, y, uint16_t, 16) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_UINT16 || GxB_NO_BGET_UINT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bget_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bget_uint16) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_uint16) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint16_t uint16_t bwork = (*((uint16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((node)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bget_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bget_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_uint16) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_uint16) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint16_t bij = Bx [p] ; Cx [p] = GB_BITGET (x, bij, uint16_t, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_uint16) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = Ax [p] ; Cx [p] = GB_BITGET (aij, y, uint16_t, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = GB_BITGET (x, aij, uint16_t, 16) ; \ } GrB_Info GB (_bind1st_tran__bget_uint16) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint16_t aij = Ax [pA] ; \ Cx [pC] = GB_BITGET (aij, y, uint16_t, 16) ; \ } GrB_Info GB (_bind2nd_tran__bget_uint16) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
main.c
/* Test for OpenMP on GPU device * Requires GCC 4.9.1 + * i.e. OpenMP v4.0 + * */ // Makefile // --------- // omp4: omp4.c // gcc -o omp4 omp4.c -lm -I/usr/include/gdal -L/usr/lib -lgdal // run.sh // --------- #include<stdio.h> #include<omp.h> #include<math.h> #include"gdal.h" void usage() { printf( "-----------------------------------------------------------\n"); printf( "--Calculate the weighted sum of WSA/BSA Albedo images------\n"); printf( "-----------------------------------------------------------\n"); printf( "--DFS: Diffuse Fraction of Sunlight------------------------\n"); printf( "-----------------------------------------------------------\n"); printf( "./omp4 outALB DFS inWSAfile inBSAfile inQA\n"); printf( "-----------------------------------------------------------\n"); return; } int main( int argc, char *argv[] ) { if( argc > 5 ){ usage(); return 1; } #pragma omp declare target float F(float); #pragma omp end declare target int ndev = omp_get_num_devices(); printf("Number of devices: %d\n", ndev); int default_device = omp_get_default_device(); printf("Default device = %d\n", default_device); omp_set_default_device(default_device+1); if (omp_get_default_device() != default_device+1) printf("Default device is still = %d\n", default_device); int i; int nthreads = omp_is_initial_device() ? 8 : 1024; if (!omp_is_initial_device()){ printf("1024 threads on target device\n"); nthreads = 1024; } else { printf("8 threads on initial device\n"); nthreads = 8; } return(EXIT_SUCCESS); } /* float x, y; #pragma omp threadprivate(x, y) void init(float a, float b){ #pragma omp single copyprivate(a,b,x,y){ scanf("%f %f %f %f", &a, &b, &x, &y); } } */ /*extern void init(float*, float*, int); extern void output(float*, int); void vec_mult(int N){ int i; float p[N], v1[N], v2[N]; init(v1, v2, N); #pragma omp target map(to: v1, v2) map(from: p) #pragma omp parallel for for (i=0; i<N; i++) p[i] = v1[i] * v2[i]; output(p, N); } */ /* #pragma omp declare target float F(float); #pragma omp end declare target #define N 1000000000 #define CHUNKSZ 1000000 void init(float *, int); float Z[N]; void pipedF() { int C, i; init(Z, N); for (C=0; C<N; C+=CHUNKSZ){ #pragma omp task #pragma omp target map(Z[C:CHUNKSZ]) #pragma omp parallel for for (i=0; i<CHUNKSZ; i++) Z[i] = F(Z[i]); } #pragma omp taskwait }*/ /* extern void init(float *, float *, int); extern void output(float *, int); void vec_mult(float *p, float *v1, float *v2, int N){ int i; init(v1, v2, N); #pragma omp target teams map(to: v1[0:N], v2[:N]) map(from: p[0:N]) #pragma omp distribute parallel for simd for (i=0; i<N; i++) p[i] = v1[i] * v2[i]; output(p, N); }*/
spmmd_x_csc_row.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #include <memory.h> #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_SPMAT_CSC *matA, const ALPHA_SPMAT_CSC *matB, ALPHA_Number *matC, const ALPHA_INT ldc) { if (matA->cols != matB->rows) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT m = matA->rows; ALPHA_INT n = matB->cols; ALPHA_INT num_thread = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for(ALPHA_INT i = 0; i < matA->rows; i++) { for(ALPHA_INT j = 0; j < matB->cols; j++) { alpha_setzero(matC[index2(i, j, ldc)]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT bc = 0; bc < n; bc++) { for (ALPHA_INT bi = matB->cols_start[bc]; bi < matB->cols_end[bc]; bi++) { ALPHA_INT ac = matB->row_indx[bi]; // ac == br ALPHA_Number bv; bv = matB->values[bi]; for (ALPHA_INT ai = matA->cols_start[ac]; ai < matA->cols_end[ac]; ai++) { ALPHA_INT ar = matA->row_indx[ai]; ALPHA_Number av; av = matA->values[ai]; ALPHA_Number tmp; alpha_mul(tmp, av, bv); alpha_adde(matC[index2(ar, bc, ldc)], tmp); } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
bitmap.h
/*! * Copyright 2014 by Contributors * \file bitmap.h * \brief a simple implement of bitmap * NOTE: bitmap is only threadsafe per word access, remember this when using bitmap * \author Tianqi Chen */ #ifndef TSOOBGX_COMMON_BITMAP_H_ #define TSOOBGX_COMMON_BITMAP_H_ #include <dmlc/omp.h> #include <vector> namespace tsoobgx { namespace common { /*! \brief bit map that contains set of bit indicators */ struct BitMap { /*! \brief internal data structure */ std::vector<uint32_t> data; /*! * \brief resize the bitmap to be certain size * \param size the size of bitmap */ inline void Resize(size_t size) { data.resize((size + 31U) >> 5, 0); } /*! * \brief query the i-th position of bitmap * \param i the position in */ inline bool Get(size_t i) const { return (data[i >> 5] >> (i & 31U)) & 1U; } /*! * \brief set i-th position to true * \param i position index */ inline void SetTrue(size_t i) { data[i >> 5] |= (1 << (i & 31U)); } /*! \brief initialize the value of bit map from vector of bool*/ inline void InitFromBool(const std::vector<int>& vec) { this->Resize(vec.size()); // parallel over the full cases auto nsize = static_cast<bst_omp_uint>(vec.size() / 32); #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < nsize; ++i) { uint32_t res = 0; for (int k = 0; k < 32; ++k) { int bit = vec[(i << 5) | k]; res |= (bit << k); } data[i] = res; } if (nsize != vec.size()) data.back() = 0; for (size_t i = nsize; i < vec.size(); ++i) { if (vec[i]) this->SetTrue(i); } } /*! \brief clear the bitmap, set all places to false */ inline void Clear() { std::fill(data.begin(), data.end(), 0U); } }; } // namespace common } // namespace tsoobgx #endif // TSOOBGX_COMMON_BITMAP_H_
p3.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define VECLEN 100000000 double *a, *b, sum; double begin; double time_spent; int main (int argc, char *argv[]) { int i; sum = 0.0; a = aligned_alloc(64, VECLEN * sizeof(double)); b = aligned_alloc(64, VECLEN * sizeof(double)); for (i=0; i < VECLEN; i++) a[i] = b[i] = 1.0 * i; omp_set_num_threads(4); begin = omp_get_wtime(); #pragma omp parallel for reduction(+:sum) schedule(static) for (i=0; i < VECLEN; i+=1) { sum = sum + (a[i]*b[i]); } time_spent = (double)(omp_get_wtime() - begin); printf("Sum = %f\n",sum); printf ("Time: %f\n", time_spent); }
matcomput.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <omp.h> #include <math.h> #include "mmio.h" #include "matcomput.h" float **readBandedMatrix(FILE *f, MM_typecode *matcode, int *row, int *col, int *nz, int wid) { int i, j, ret_code, m, n; float **val, value; if (mm_read_banner(f, matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } if ((ret_code = mm_read_mtx_crd_size(f, row, col, nz)) != 0) exit(1); val = (float **)malloc(wid * sizeof(double)); for (i = 0; i < wid; i++) val[i] = (float *)malloc(*col * sizeof(double)); for (i = 0; i < *nz; i++) { fscanf(f, "%d %d %f\n", &m, &n, &value); if(m == n) continue; val[m - n - 1][n - 1] = value; } if (f != stdin) fclose(f); return val; } float **readMatrix(FILE *f, MM_typecode *matcode, int *row, int *col) { int i, j, ret_code; float **val; if (mm_read_banner(f, matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } if ((ret_code = mm_read_mtx_array_size(f, row, col)) != 0) exit(1); val = (float **)malloc(*row * sizeof(double)); for (i = 0; i < *row; i++) val[i] = (float *)malloc(*col * sizeof(double)); for (j = 0; j < *col; j++) for (i = 0; i < *row; i++) fscanf(f, "%f", &val[i][j]); if (f != stdin) fclose(f); return val; } float *readVector(FILE *f, MM_typecode *matcode, int *row) { int i, col, ret_code; float *val; if (mm_read_banner(f, matcode) != 0) { printf("Could not process Matrix Market banner.\n"); exit(1); } if ((ret_code = mm_read_mtx_array_size(f, row, &col)) != 0) exit(1); val = (float *)malloc(*row * sizeof(double)); for (i = 0; i < *row; i++) fscanf(f, "%f", &val[i]); if (f != stdin) fclose(f); return val; } void fileWrite(FILE *f, int *row, float *C, MM_typecode *matcode) { int i, j; mm_write_banner(f, *matcode); fprintf(f, "%vector x\n"); mm_write_mtx_array_size(f, *row, 1); for (i = 0; i < *row; i++) fprintf(f, "%f\n", C[i]); fclose(f); } void threadReport(int *row, int tid, int i) { int limit = *row / 100 + 1; if (i%limit == 0) { if (tid < 10) printf(" Core 0%d: %d %% complete!\n", tid, i / limit); else printf(" Core %d: %d %% complete!\n", tid, i / limit); } } float **matTrans(float **A, int dim) { int i, j; float **val; val = (float **)malloc(dim * sizeof(double)); for (i = 0; i < dim; i++) { val[i] = (float *)malloc(dim * sizeof(double)); for (j = 0; j < dim; j++) val[i][j] = A[j][i]; } return val; } // CSweep: Column-sweep method for unit lower triangular system // tag means whether implement through parallel float *cSweep(float **L, float *f, int *row, int chunk, bool tag) { int i, j, n, tid, nthreads; float *val; val = (float *)malloc(*row * sizeof(double)); for (i = 0; i < *row; i++) { val[i] = f[i]; if (tag) { #pragma omp parallel shared(L,f,i,nthreads) private(j,tid) { #pragma omp for schedule (static, chunk) for (j = i + 1; j < *row; j++) f[j] -= f[i] * L[j][i]; } } else { for (j = i + 1; j < *row; j++) f[j] -= f[i] * L[j][i]; } } return val; } // Given the size and location to generate the submatrix. float **matSplit(float **L, int i0, int j0, int m, int n, char tag) { int i, j; float **val; val = (float **)calloc(m, sizeof(double)); for (i = 0; i < m; i++) { val[i] = (float *)calloc(n, sizeof(double)); if(tag == true) { for (j = 0; j < n; j++) if(i == j) val[i][j] = 1; else if(i > j) val[i][j] = L[i - j - 1][j + j0]; } else { for (j = 0; j < n; j++) if(i <= j) val[i][j] = L[m - 1 + i - j][j + j0]; } } return val; } // Given the size and location to generate the subvector. float *vecSplit(float *f, int i0, int m) { int i; float *val; val = (float *)calloc(m, sizeof(double)); for (i = 0; i < m; i++) val[i] = f[i + i0]; return val; } void matMerge(float ***L, int v, int wid, float **M) { int i, j, k; int num = exp2(v) - 1; for (k = 0; k < num; k++) for (i = 0; i < wid; i++) for (j = 0; j < wid; j++) M[i + k * wid][j] = L[k][i][j]; } void vecMerge(float **f, int v, int wid, float *val) { int i, k; int num = exp2(v); for (k = 0; k < num; k++) for (i = 0; i < wid; i++) val[i + k * wid] = f[k][i]; } void vecCombine(float **L, float *f, int dim, int x, int wid, int r, int chunk) { int i, j; float *v; int m0 = 2 * r * x * wid; v = (float *)calloc(dim, sizeof(double)); #pragma omp parallel shared(L, f, v, m0, x, wid) private(i, j) { #pragma omp for schedule (static, chunk) for (i = 0; i < wid * x; i++) for (j = 0; j < wid; j++) v[i + m0 + wid * x] += L[i + (2 * r) * wid * x][j] * f[j + (2 * r) * wid * x]; #pragma omp for schedule (static, chunk) for (i = 0; i < 2 * x * wid; i++) f[i + m0] -= v[i + m0]; } free(v); } void matCombine(float **L, float **C, int dim, int x, int wid, int r, int chunk) { int i, j, k; int m0 = 2 * (r - 1) * x * wid; #pragma omp parallel shared(L, C, m0, r, x, wid) private(i, j, k) { #pragma omp for schedule (static, chunk) for (i = 0; i < wid * x; i++) for (j = 0; j < wid; j++) C[i + m0][j] = L[i + (2 * r - 1) * wid * x][j]; #pragma omp for schedule (static, chunk) for (i = 0; i < wid * x; i++) for (k = 0; k < wid; k++) for (j = 0; j < wid; j++) C[i + m0 + wid * x][j] -= L[i + (2 * r) * wid * x][k] * L[k + (2 * r - 1) * wid * x][j]; } } float *BBTS(float **L, float *f, int dim, int wid, int chunk, int core, int tid) { int i, j, k, v, x, num; float **fpar, *val, **G[2]; // Dim0|1: ori|inverse, dim2: order; Dim3/4: Col/Row float ***Gs[2], ***Rs[2], ***Ls[2]; num = dim / wid; v = log2(num); fpar = (float **)calloc(num, sizeof(double)); val = (float *)calloc(dim, sizeof(double)); for (i = 0; i < 2; i++) { Ls[i] = (float ***)calloc(num, sizeof(double)); Gs[i] = (float ***)calloc(num, sizeof(double)); Rs[i] = (float ***)calloc(num, sizeof(double)); G[i] = (float **)calloc(dim - wid, sizeof(double)); for (j = 0; j < dim - wid; j++) G[i][j] = (float *)calloc(wid, sizeof(double)); } for (i = 0; i < num; i++) { fpar[i] = vecSplit(f, i * wid, wid); Ls[0][i] = matSplit(L, 0, i * wid, wid, wid, true); if (i != num - 1) { Rs[0][i] = matSplit(L, 0, i * wid, wid, wid, false); Rs[1][i] = matTrans(Rs[0][i], wid); for (j = 0; j < wid; j++) { Gs[1][i] = (float **)calloc(wid, sizeof(double)); } } } // Step 1 fpar[0] = cSweep(Ls[0][0], fpar[0], &wid, chunk, true); // Step 2-4 #pragma omp parallel shared(fpar, Ls, Rs, Gs, core, chunk) private(tid, i, j, k) { #pragma omp for schedule (static, chunk) for (i = 1; i < num; i++) { fpar[i] = cSweep(Ls[0][i], fpar[i], &wid, chunk, false); for (j = 0; j < wid; j++) Gs[1][i - 1][j] = cSweep(Ls[0][i], Rs[1][i - 1][j], &wid, chunk, false); Gs[0][i - 1] = matTrans(Gs[1][i - 1], wid); } } // Step 5-10 matMerge(Gs[0], v, wid, G[0]); vecMerge(fpar, v, wid, val); for (k = 1; k < v; k++) { // Step 6 update f with the last half part x = exp2(k - 1); vecCombine(G[(k - 1) % 2], val, dim, x, wid, 0, chunk); for (j = 1; j < exp2(v - k); j++) { vecCombine(G[(k - 1) % 2], val, dim, x, wid, j, chunk); matCombine(G[(k - 1) % 2], G[k % 2], dim, x, wid, j,chunk); } } vecCombine(G[(v - 1) % 2], val, dim, exp2(v - 1), wid, 0, chunk); return val; }
jacobi-v3.c
#include <stdio.h> #include <math.h> #include <assert.h> #ifdef _OPENMP #include <omp.h> #endif // Add timing support #include <sys/time.h> double time_stamp() { struct timeval t; double time; gettimeofday(&t, NULL); time = t.tv_sec + 1.0e-6*t.tv_usec; return time; } double time1, time2; void driver(void); void initialize(void); void jacobi(void); void error_check(void); /************************************************************ * program to solve a finite difference * discretization of Helmholtz equation : * (d2/dx2)u + (d2/dy2)u - alpha u = f * using Jacobi iterative method. * * Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998 * Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998 * * This C version program is translated by * Chunhua Liao, University of Houston, Jan, 2005 * * Directives are used in this code to achieve parallelism. * All do loops are parallelized with default 'static' scheduling. * * Input : n - grid dimension in x direction * m - grid dimension in y direction * alpha - Helmholtz constant (always greater than 0.0) * tol - error tolerance for iterative solver * relax - Successice over relaxation parameter * mits - Maximum iterations for iterative solver * * On output * : u(n,m) - Dependent variable (solutions) * : f(n,m) - Right hand side function *************************************************************/ #define MSIZE 500 int n,m,mits; double tol,relax=1.0,alpha=0.0543; double u[MSIZE][MSIZE],f[MSIZE][MSIZE],uold[MSIZE][MSIZE]; double dx,dy; unsigned long int chiterations = 0; unsigned long int chloads = 0; unsigned long int chstores = 0; unsigned long int chflops = 0; int main (void) { float toler; /* printf("Input n,m (< %d) - grid dimension in x,y direction:\n",MSIZE); scanf ("%d",&n); scanf ("%d",&m); printf("Input tol - error tolerance for iterative solver\n"); scanf("%f",&toler); tol=(double)toler; printf("Input mits - Maximum iterations for solver\n"); scanf("%d",&mits); */ n=MSIZE; m=MSIZE; tol=0.0000000001; mits=5000; #ifdef _OPENMP #pragma omp parallel { #pragma omp single printf("Running using %d threads...\n",omp_get_num_threads()); } #endif driver ( ) ; printf ("chloads =%lu chostores =%lu, chflops=%lu\n",chloads, chstores, chflops); assert (chflops == 16120260000); return 0; } /************************************************************* * Subroutine driver () * This is where the arrays are allocated and initialized. * * Working variables/arrays * dx - grid spacing in x direction * dy - grid spacing in y direction *************************************************************/ void driver( ) { initialize(); time1 = time_stamp(); /* Solve Helmholtz equation */ jacobi (); time2 = time_stamp(); printf("------------------------\n"); printf("Execution time = %f\n",time2-time1); /* error_check (n,m,alpha,dx,dy,u,f)*/ error_check ( ); } /* subroutine initialize (n,m,alpha,dx,dy,u,f) ****************************************************** * Initializes data * Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2) * ******************************************************/ void initialize( ) { int i,j, xx,yy; //double PI=3.1415926; dx = 2.0 / (n-1); dy = 2.0 / (m-1); /* Initialize initial condition and RHS */ //chiterations = n*m; #pragma aitool fp_plus(2) fp_multiply(2) for (i=0;i<n;i++) for (j=0;j<m;j++) { xx =(int)( -1.0 + dx * (i-1)); yy = (int)(-1.0 + dy * (j-1)) ; u[i][j] = 0.0; } //chiterations = n*m; #pragma aitool fp_minus(6) fp_multiply(5) for (i=0;i<n;i++) for (j=0;j<m;j++) { u[i][j] = 0.0; f[i][j] = -1.0*alpha *(1.0-xx*xx)*(1.0-yy*yy)\ - 2.0*(1.0-xx*xx)-2.0*(1.0-yy*yy); } //chiterations = n*m; #pragma aitool fp_plus(2) fp_minus(6) fp_multiply(7) for (i=0;i<n;i++) for (j=0;j<m;j++) { xx =(int)( -1.0 + dx * (i-1)); yy = (int)(-1.0 + dy * (j-1)) ; u[i][j] = 0.0; f[i][j] = -1.0*alpha *(1.0-xx*xx)*(1.0-yy*yy)\ - 2.0*(1.0-xx*xx)-2.0*(1.0-yy*yy); } } /* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,maxit) ****************************************************************** * Subroutine HelmholtzJ * Solves poisson equation on rectangular grid assuming : * (1) Uniform discretization in each direction, and * (2) Dirichlect boundary conditions * * Jacobi method is used in this routine * * Input : n,m Number of grid points in the X/Y directions * dx,dy Grid spacing in the X/Y directions * alpha Helmholtz eqn. coefficient * omega Relaxation factor * f(n,m) Right hand side function * u(n,m) Dependent variable/Solution * tol Tolerance for iterative solver * maxit Maximum number of iterations * * Output : u(n,m) - Solution *****************************************************************/ void jacobi( ) { double omega; int i,j,k; double error,resid,ax,ay,b; // double error_local; // float ta,tb,tc,td,te,ta1,ta2,tb1,tb2,tc1,tc2,td1,td2; // float te1,te2; // float second; omega=relax; /* * Initialize coefficients */ ax = 1.0/(dx*dx); /* X-direction coef */ ay = 1.0/(dy*dy); /* Y-direction coef */ b = -2.0/(dx*dx)-2.0/(dy*dy) - alpha; /* Central coeff */ error = 10.0 * tol; k = 1; while ((k<=mits)&&(error>tol)) { error = 0.0; /* Copy new solution into old */ { chiterations = n*m; for(i=0;i<n;i++) for(j=0;j<m;j++) uold[i][j] = u[i][j]; chiterations = (n-2)*(m-2); #pragma aitool fp_plus(5) fp_minus(2) fp_multiply(5) fp_divide(1) for (i=1;i<(n-1);i++) for (j=1;j<(m-1);j++) { resid = (ax*(uold[i-1][j] + uold[i+1][j])\ + ay*(uold[i][j-1] + uold[i][j+1])+ b * uold[i][j] - f[i][j])/b; u[i][j] = uold[i][j] - omega * resid; error = error + resid*resid ; } } /* omp end parallel */ /* Error check */ k = k + 1; if (k%500==0) printf("Finished %d iteration.\n",k); error = sqrt(error)/(n*m); } /* End iteration loop */ printf("Total Number of Iterations:%d\n",k); printf("Residual:%E\n", error); } /* subroutine error_check (n,m,alpha,dx,dy,u,f) implicit none ************************************************************ * Checks error between numerical and exact solution * ************************************************************/ void error_check ( ) { int i,j; double xx,yy,temp,error; dx = 2.0 / (n-1); dy = 2.0 / (m-1); error = 0.0 ; //chiterations = n*m; #pragma aitool fp_plus(3) fp_minus(3) fp_multiply(6) for (i=0;i<n;i++) for (j=0;j<m;j++) { xx = -1.0 + dx * (i-1); yy = -1.0 + dy * (j-1); temp = u[i][j] - (1.0-xx*xx)*(1.0-yy*yy); error = error + temp*temp; } error = sqrt(error)/(n*m); printf("Solution Error :%E \n",error); }