<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dialogcontrolling.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 16:28:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#ifndef SVTOOLS_DIALOGCONTROLLING_HXX
#include "dialogcontrolling.hxx"
#endif

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif

#include <algorithm>
#include <functional>

//........................................................................
namespace svt
{
//........................................................................

    //=====================================================================
    //= IWindowOperator
    //=====================================================================
    //---------------------------------------------------------------------
    IWindowOperator::~IWindowOperator()
    {
    }

    //=====================================================================
    //= IWindowEventFilter
    //=====================================================================
    //---------------------------------------------------------------------
    IWindowEventFilter::~IWindowEventFilter()
    {
    }

    //=====================================================================
    //= DialogController_Data
    //=====================================================================
    struct DialogController_Data
    {
        Window&                     rInstigator;
        ::std::vector< Window* >    aConcernedWindows;
        PWindowEventFilter          pEventFilter;
        PWindowOperator             pOperator;

        DialogController_Data( Window& _rInstigator, const PWindowEventFilter _pEventFilter, const PWindowOperator _pOperator )
            :rInstigator( _rInstigator )
            ,pEventFilter( _pEventFilter )
            ,pOperator( _pOperator )
        {
        }
    };

    //=====================================================================
    //= DialogController
    //=====================================================================
    //---------------------------------------------------------------------
    DialogController::DialogController( Window& _rInstigator, const PWindowEventFilter _pEventFilter,
            const PWindowOperator _pOperator )
        :m_pImpl( new DialogController_Data( _rInstigator, _pEventFilter, _pOperator ) )
    {
        DBG_ASSERT( m_pImpl->pEventFilter.get() && m_pImpl->pOperator.get(),
            "DialogController::DialogController: invalid filter and/or operator!" );

        m_pImpl->rInstigator.AddEventListener( LINK( this, DialogController, OnWindowEvent ) );
    }

    //---------------------------------------------------------------------
    DialogController::~DialogController()
    {
        reset();
    }

    //---------------------------------------------------------------------
    void DialogController::reset()
    {
        m_pImpl->rInstigator.RemoveEventListener( LINK( this, DialogController, OnWindowEvent ) );
        m_pImpl->aConcernedWindows.clear();
        m_pImpl->pEventFilter.reset();
        m_pImpl->pOperator.reset();
    }

    //---------------------------------------------------------------------
    void DialogController::addDependentWindow( Window& _rWindow )
    {
        m_pImpl->aConcernedWindows.push_back( &_rWindow );
        impl_update( _rWindow );
    }

    //---------------------------------------------------------------------
    IMPL_LINK( DialogController, OnWindowEvent, const VclSimpleEvent*, _pEvent )
    {
        if ( m_pImpl->pEventFilter->payAttentionTo( *_pEvent ) )
            impl_updateAll();
        return 0L;
    }

    //---------------------------------------------------------------------
    void DialogController::impl_updateAll()
    {
        for ( ::std::vector< Window* >::iterator loop = m_pImpl->aConcernedWindows.begin();
                loop != m_pImpl->aConcernedWindows.end();
                ++loop
            )
            impl_update( *(*loop) );
    }

    //---------------------------------------------------------------------
    void DialogController::impl_update( Window& _rWindow )
    {
        m_pImpl->pOperator->operateOn( _rWindow );
    }

    //=====================================================================
    //= ControlDependencyManager_Data
    //=====================================================================
    struct ControlDependencyManager_Data
    {
        ::std::vector< PDialogController >  aControllers;
    };

    //=====================================================================
    //= ControlDependencyManager
    //=====================================================================
    //---------------------------------------------------------------------
    ControlDependencyManager::ControlDependencyManager()
        :m_pImpl( new ControlDependencyManager_Data )
    {
    }

    //---------------------------------------------------------------------
    ControlDependencyManager::~ControlDependencyManager()
    {
    }

    //---------------------------------------------------------------------
    namespace
    {
        struct ResetDialogController : public ::std::unary_function< const PDialogController&, void >
        {
            void operator()( const PDialogController& _pController )
            {
                _pController->reset();
            }
        };
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::clear()
    {
        ::std::for_each( m_pImpl->aControllers.begin(), m_pImpl->aControllers.end(), ResetDialogController() );
        m_pImpl->aControllers.clear();
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5, Window& _rDependentWindow6 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        pController->addDependentWindow( _rDependentWindow6 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5, Window& _rDependentWindow6 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        pController->addDependentWindow( _rDependentWindow6 );
        m_pImpl->aControllers.push_back( pController );
    }

//........................................................................
} // namespace svt
//........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.2.388); FILE MERGED 2008/04/01 15:45:17 thb 1.2.388.3: #i85898# Stripping all external header guards 2008/04/01 12:43:47 thb 1.2.388.2: #i85898# Stripping all external header guards 2008/03/31 13:02:15 rt 1.2.388.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dialogcontrolling.cxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include "dialogcontrolling.hxx"
#include <vcl/window.hxx>

#include <algorithm>
#include <functional>

//........................................................................
namespace svt
{
//........................................................................

    //=====================================================================
    //= IWindowOperator
    //=====================================================================
    //---------------------------------------------------------------------
    IWindowOperator::~IWindowOperator()
    {
    }

    //=====================================================================
    //= IWindowEventFilter
    //=====================================================================
    //---------------------------------------------------------------------
    IWindowEventFilter::~IWindowEventFilter()
    {
    }

    //=====================================================================
    //= DialogController_Data
    //=====================================================================
    struct DialogController_Data
    {
        Window&                     rInstigator;
        ::std::vector< Window* >    aConcernedWindows;
        PWindowEventFilter          pEventFilter;
        PWindowOperator             pOperator;

        DialogController_Data( Window& _rInstigator, const PWindowEventFilter _pEventFilter, const PWindowOperator _pOperator )
            :rInstigator( _rInstigator )
            ,pEventFilter( _pEventFilter )
            ,pOperator( _pOperator )
        {
        }
    };

    //=====================================================================
    //= DialogController
    //=====================================================================
    //---------------------------------------------------------------------
    DialogController::DialogController( Window& _rInstigator, const PWindowEventFilter _pEventFilter,
            const PWindowOperator _pOperator )
        :m_pImpl( new DialogController_Data( _rInstigator, _pEventFilter, _pOperator ) )
    {
        DBG_ASSERT( m_pImpl->pEventFilter.get() && m_pImpl->pOperator.get(),
            "DialogController::DialogController: invalid filter and/or operator!" );

        m_pImpl->rInstigator.AddEventListener( LINK( this, DialogController, OnWindowEvent ) );
    }

    //---------------------------------------------------------------------
    DialogController::~DialogController()
    {
        reset();
    }

    //---------------------------------------------------------------------
    void DialogController::reset()
    {
        m_pImpl->rInstigator.RemoveEventListener( LINK( this, DialogController, OnWindowEvent ) );
        m_pImpl->aConcernedWindows.clear();
        m_pImpl->pEventFilter.reset();
        m_pImpl->pOperator.reset();
    }

    //---------------------------------------------------------------------
    void DialogController::addDependentWindow( Window& _rWindow )
    {
        m_pImpl->aConcernedWindows.push_back( &_rWindow );
        impl_update( _rWindow );
    }

    //---------------------------------------------------------------------
    IMPL_LINK( DialogController, OnWindowEvent, const VclSimpleEvent*, _pEvent )
    {
        if ( m_pImpl->pEventFilter->payAttentionTo( *_pEvent ) )
            impl_updateAll();
        return 0L;
    }

    //---------------------------------------------------------------------
    void DialogController::impl_updateAll()
    {
        for ( ::std::vector< Window* >::iterator loop = m_pImpl->aConcernedWindows.begin();
                loop != m_pImpl->aConcernedWindows.end();
                ++loop
            )
            impl_update( *(*loop) );
    }

    //---------------------------------------------------------------------
    void DialogController::impl_update( Window& _rWindow )
    {
        m_pImpl->pOperator->operateOn( _rWindow );
    }

    //=====================================================================
    //= ControlDependencyManager_Data
    //=====================================================================
    struct ControlDependencyManager_Data
    {
        ::std::vector< PDialogController >  aControllers;
    };

    //=====================================================================
    //= ControlDependencyManager
    //=====================================================================
    //---------------------------------------------------------------------
    ControlDependencyManager::ControlDependencyManager()
        :m_pImpl( new ControlDependencyManager_Data )
    {
    }

    //---------------------------------------------------------------------
    ControlDependencyManager::~ControlDependencyManager()
    {
    }

    //---------------------------------------------------------------------
    namespace
    {
        struct ResetDialogController : public ::std::unary_function< const PDialogController&, void >
        {
            void operator()( const PDialogController& _pController )
            {
                _pController->reset();
            }
        };
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::clear()
    {
        ::std::for_each( m_pImpl->aControllers.begin(), m_pImpl->aControllers.end(), ResetDialogController() );
        m_pImpl->aControllers.clear();
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnRadioCheck( RadioButton& _rRadio, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5, Window& _rDependentWindow6 )
    {
        PDialogController pController( new RadioDependentEnabler( _rRadio ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        pController->addDependentWindow( _rDependentWindow6 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        m_pImpl->aControllers.push_back( pController );
    }

    //---------------------------------------------------------------------
    void ControlDependencyManager::enableOnCheckMark( CheckBox& _rBox, Window& _rDependentWindow1, Window& _rDependentWindow2, Window& _rDependentWindow3, Window& _rDependentWindow4, Window& _rDependentWindow5, Window& _rDependentWindow6 )
    {
        PDialogController pController( new RadioDependentEnabler( _rBox ) );
        pController->addDependentWindow( _rDependentWindow1 );
        pController->addDependentWindow( _rDependentWindow2 );
        pController->addDependentWindow( _rDependentWindow3 );
        pController->addDependentWindow( _rDependentWindow4 );
        pController->addDependentWindow( _rDependentWindow5 );
        pController->addDependentWindow( _rDependentWindow6 );
        m_pImpl->aControllers.push_back( pController );
    }

//........................................................................
} // namespace svt
//........................................................................

<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "src/sksl/ir/SkSLVariableReference.h"

#include "include/private/SkSLModifiers.h"
#include "src/sksl/ir/SkSLVariable.h"
#include <string_view>

namespace SkSL {

VariableReference::VariableReference(Position pos, const Variable* variable, RefKind refKind)
    : INHERITED(pos, kExpressionKind, &variable->type())
    , fVariable(variable)
    , fRefKind(refKind) {
    SkASSERT(this->variable());
}

bool VariableReference::hasProperty(Property property) const {
    switch (property) {
        case Property::kSideEffects:      return false;
        case Property::kContainsRTAdjust: return this->variable()->name() == "sk_RTAdjust";
        default:
            SkASSERT(false);
            return false;
    }
}

std::string VariableReference::description() const {
    return std::string(this->variable()->name());
}

void VariableReference::setRefKind(RefKind refKind) {
    fRefKind = refKind;
}

void VariableReference::setVariable(const Variable* variable) {
    fVariable = variable;
}

}  // namespace SkSL
<commit_msg>[includes] Fix dangling IWYU issue<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "src/sksl/ir/SkSLVariableReference.h"

#include "src/sksl/ir/SkSLVariable.h"
#include <string_view>

namespace SkSL {

VariableReference::VariableReference(Position pos, const Variable* variable, RefKind refKind)
    : INHERITED(pos, kExpressionKind, &variable->type())
    , fVariable(variable)
    , fRefKind(refKind) {
    SkASSERT(this->variable());
}

bool VariableReference::hasProperty(Property property) const {
    switch (property) {
        case Property::kSideEffects:      return false;
        case Property::kContainsRTAdjust: return this->variable()->name() == "sk_RTAdjust";
        default:
            SkASSERT(false);
            return false;
    }
}

std::string VariableReference::description() const {
    return std::string(this->variable()->name());
}

void VariableReference::setRefKind(RefKind refKind) {
    fRefKind = refKind;
}

void VariableReference::setVariable(const Variable* variable) {
    fVariable = variable;
}

}  // namespace SkSL
<|endoftext|>


<commit_before>#include <strads/include/common.hpp>
#include <strads/netdriver/zmq/zmq-common.hpp>
#include <strads/netdriver/comm.hpp>
#include <strads/ps/strads-ps.hpp>
#include <mpi.h>
#include <zmq.hpp>
#include <string>
#include <vector>
#include <map>
#include <strads/cyclone/strads-cyclone.hpp>

using namespace std;

eCycloneRole Cyclone::role_ = cycloneUnknown;
int Cyclone::serverCount_ = -1;
int Cyclone::rank_ = -1;

map<int, _ringport *>*Cyclone::sendPortMap_ = NULL;
map<int, _ringport *>*Cyclone::recvPortMap_ = NULL;
int Cyclone::maxasync_ = -1;
int Cyclone::clientCount_ = -1;

void Cyclone::cycloneClientBGThread(Cyclone *Obj){

}

void Cyclone::printCycloneConf(void){
  if(role == cycloneClient){
    strads_msg(ERR, "[ Client rank %d ] -- sendmap.size(%ld) recvmap.size(%ld) \n", rank, sendPortMap.size(), recvPortMap.size());
  }else if(role == cycloneServer){
    strads_msg(ERR, "[ Server rank %d ] -- sendmap.size(%ld) recvmap.size(%ld) \n", rank, sendPortMap.size(), recvPortMap.size());
  }
}

void Cyclone::cycloneServerBGThread(Cyclone *Obj){

}

void *Cyclone::_makeCyclonePacket(void *usrPacket, int usrLen, CyclonePacket *pkt, int sendLen, int srcRank){

  return NULL;
}
void *Cyclone::serialize(std::string &key, std::string &value, int *pLen, int *pServerId){

  return NULL;
}

void Cyclone::deserialize(void *bytes, std::string &key, std::string &value){

}

void Cyclone::cycloneAsyncPutGet(Strads &ctx, std::string &key, std::string &value){

  int len=-1;
  int serverid=-1;
  void *buf = serialize(key, value, &len, &serverid); // convert user bytes into CyclonePacket with meta information

  CyclonePacket *packet = (CyclonePacket *)calloc(sizeof(CyclonePacket) + len, 1);
  void *ubuf = (void *)((uintptr_t)(packet) + sizeof(CyclonePacket));
  assert((uintptr_t)ubuf % sizeof(long) == 0);
  packet->ubuf = ubuf;
  memcpy(ubuf, buf, len);
  packet->len = sizeof(CyclonePacket) + len;
  packet->src = rank;
  packet->cbtype = cycmd_putgetasync;  // don't forget this

  auto ps = sendPortMap[serverid];
  _ringport *sport = ps;
  //  context *send_ctx = sport->ctx;
  //  ctx->increment_async_count();
  //  send_ctx->push_ps_entry_outq((void *)packet, sizeof(pspacket) + len);
  //  free((void *)packet);
  //  free(buf);
}

void Cyclone::cycloneSyncPut(Strads &ctx, std::string &key, std::string &value){

}

void Cyclone::cycloneSyncGet(Strads &ctx, std::string &key, std::string &value){

}

#if 0
void *make_cyclonepacket(void *usrPacket, int usrLen, pspacket *pspkt, int *sendLen, int srcRank);

void cyclone_put_get_async_ll(, string &key, string &value){

  int len=-1;
  int serverid=-1;
  void *buf = md_serialize(key, value, ctx->m_sched_machines, &len, &serverid);

  pspacket *packet = (pspacket *)calloc(sizeof(pspacket) + len, 1);
  void *ubuf = (void *)((uintptr_t)(packet) + sizeof(pspacket));
  assert((uintptr_t)ubuf % sizeof(long) == 0);
  packet->ubuf = ubuf;
  memcpy(ubuf, buf, len);
  packet->len = sizeof(pspacket) + len;
  packet->src = ctx->rank;
  packet->cbtype = cb_putgetasync;  // don't forget this
  auto ps = ctx->ps_sendportmap[serverid];
  _ringport *sport = ps;
  context *send_ctx = sport->ctx;

  ctx->increment_async_count();
  send_ctx->push_ps_entry_outq((void *)packet, sizeof(pspacket) + len);

  free((void *)packet);
  free(buf);
}

void cyclone_put_sync_ll(sharedctx *ctx, string &key, string &value){

  int len=-1;
  int serverid=-1;
  void *buf = md_serialize(key, value, ctx->m_sched_machines, &len, &serverid);
  //  ps_put_sync_ll(ctx, , len, serverId);
  //  pthread_cond_t wakeup_signal = PTHREAD_COND_INITIALIZER;
  //  pthread_mutex_t dummy_lock = PTHREAD_MUTEX_INITIALIZER;
  int rlen;
  pspacket *packet = (pspacket *)calloc(sizeof(pspacket) + len, 1);
  void *ubuf = (void *)((uintptr_t)(packet) + sizeof(pspacket));
  assert((uintptr_t)ubuf % sizeof(long) == 0);
  packet->ubuf = ubuf;
  memcpy(ubuf, buf, len);
  packet->len = sizeof(pspacket) + len;
  packet->src = ctx->rank;
  packet->cbtype = cb_putsync;  // don't forget this
  //  packet->putsync_signal = &wakeup_signal;
  packet->putsync_signal = NULL; // no use any more
  packet->slen = &rlen;
  auto ps = ctx->ps_sendportmap[serverid];
  _ringport *sport = ps;
  context *send_ctx = sport->ctx;
  send_ctx->push_ps_entry_outq((void *)packet, sizeof(pspacket) + len);

  pthread_mutex_lock(&ctx->m_lock_syncput);
  int rc = pthread_cond_wait(&ctx->m_upsignal_syncput, &ctx->m_lock_syncput);
  pthread_mutex_unlock(&ctx->m_lock_syncput);

  free((void *)packet); ///////////////////////////////////
  free(buf);
  checkResults("pthread cond wait signal failed ", rc);
}

void cyclone_get_sync_ll(sharedctx *ctx, string &key, string &value){

  int len=-1;
  int serverid=-1;
  void *buf = md_serialize(key, value, ctx->m_sched_machines, &len, &serverid);

  //  pthread_cond_t wakeup_signal = PTHREAD_COND_INITIALIZER;
  //  pthread_mutex_t dummy_lock = PTHREAD_MUTEX_INITIALIZER;
  void *retbuf;
  int rlen;
  pspacket *packet = (pspacket *)calloc(sizeof(pspacket) + len, 1);
  void *ubuf = (void *)((uintptr_t)(packet) + sizeof(pspacket));
  assert((uintptr_t)ubuf % sizeof(long) == 0);
  packet->ubuf = ubuf;
  memcpy(ubuf, buf, len);
  packet->len = sizeof(pspacket) + len;
  packet->src = ctx->rank;
  packet->cbtype = cb_getsync;  // don't forget this
  //  packet->getsync_signal = &wakeup_signal;
  packet->getsync_signal = NULL; // no use any more
  packet->getsync_buf = &retbuf;
  packet->rlen = &rlen;

  auto ps = ctx->ps_sendportmap[serverid];
  _ringport *sport = ps;
  context *send_ctx = sport->ctx;
  send_ctx->push_ps_entry_outq((void *)packet, sizeof(pspacket) + len);

  //  pthread_mutex_lock(&dummy_lock);
  //  int rc = pthread_cond_wait(&wakeup_signal, &dummy_lock); // sleep until row arrive from the ps server
  //  checkResults("pthread cond wait signal failed ", rc);
  pthread_mutex_lock(&ctx->m_lock_syncget);
  int rc = pthread_cond_wait(&ctx->m_upsignal_syncget, &ctx->m_lock_syncget);
  pthread_mutex_unlock(&ctx->m_lock_syncget);

  void *msg = (void *)((uintptr_t)retbuf + sizeof(pspacket));
  key.clear();
  assert(value.size() == 0);
  md_deserialize(msg, key, value);
  free(retbuf);

  free((void *)packet); ////////////////////////////////////////////////////////////////
  free(buf);

  return;
  //  return retbuf;
}

void cyclone_put_get_async_callback_ll(pspacket *packet, int plen, sharedctx *ctx){

  ctx->decrement_async_count();

  assert(packet->cbtype == cb_putgetasync);
  void *ubuf = (void *)((uintptr_t)packet + sizeof(pspacket));              // user buffer

  string key;
  string value;
  md_deserialize(ubuf, key, value);

  assert(ctx->ps_callback_func != NULL);
  (*ctx->ps_callback_func)(ctx, key, value);
  free((void *)packet);
}

void *cyclone_client_recvthread(void *arg){ // receive
  psbgthreadctx *bctx= (psbgthreadctx *)arg;
  sharedctx *ctx = bctx->parentctx;
  _ringport **rport = (_ringport **)calloc(sizeof(_ringport *), ctx->m_sched_machines);
  context **recvctx = (context **)calloc(sizeof(context *), ctx->m_sched_machines);
  for(int i=0; i < ctx->m_worker_machines; i++){
    auto pr = ctx->ps_recvportmap[i];
    rport[i] = pr;
    recvctx[i] = rport[i]->ctx;
  }
  int clock = 0 ;
  while(1){
    void *msg = NULL;
    int len =-1;
    msg = recvctx[clock]->pull_ps_entry_inq(&len);
    if(msg != NULL){
      pspacket *pkt = (pspacket *)msg;
      if(pkt->cbtype == cb_putgetasync){
	//	assert(0);
	ps_put_get_async_callback_ll(pkt, len, ctx);
	//recvctx[clock]->release_buffer(msg); don't do this
	// call call back function. BUT this should be done another bg thread update thread.
      }else if(pkt->cbtype == cb_putsync){
	//	pthread_cond_t *wakeup_signal = pkt->putsync_signal;
	//	*(pkt->slen) = len;
	//	strads_msg(INF, "[ps client ] Wake Up blocked thread (%p) \n", wakeup_signal);
	//  pthread_mutex_lock(&ctx->m_lock_syncput);
	//  int rc = pthread_cond_wait(&ctx->m_upsignal_syncput, &ctx->m_lock_syncput);
	//  pthread_mutex_unlock(&ctx->m_lock_syncput);
	pthread_mutex_lock(&ctx->m_lock_syncput);
	int rc = pthread_cond_signal(&ctx->m_upsignal_syncput);
	pthread_mutex_unlock(&ctx->m_lock_syncput);
	checkResults("pthread cond wait up signal ", rc);
	//	recvctx[clock]->release_buffer(msg); //for sync_put
	free(pkt);
      }else if(pkt->cbtype == cb_getsync){
	//	_parse_rawpacket(ctx, (void *)pkt);
	//	pthread_cond_t *wakeup_signal = pkt->getsync_signal;

	//strads_msg(ERR, "RECV THREAD pkt->getsync_buf : %p \n", pkt->getsync_buf);
	*(pkt->getsync_buf) = (void *)pkt;
	*(pkt->rlen) = len;
	//	strads_msg(INF, "[ps client ] Wake Up blocked thread (%p) \n", wakeup_signal);
	//	int rc = pthread_cond_signal(wakeup_signal);
	//	checkResults("pthread cond wait up signal ", rc);
	pthread_mutex_lock(&ctx->m_lock_syncget);
	int rc = pthread_cond_signal(&ctx->m_upsignal_syncget);
	pthread_mutex_unlock(&ctx->m_lock_syncget);
	//recvctx[clock]->release_buffer(msg); don't do this
      }else{
	assert(0);
      }
      // PARSE pkt
      // case call back for sync_put
      // case call back for sync_get
      // case call back for async put_and_get_async
      // recv_ctx->release_buffer(msg); for sync_put
    }
    clock++;
    clock = clock % ctx->m_worker_machines;
  }
}

void *cyclone_server_recvthread(void *arg){ // receive

  psbgthreadctx *bctx= (psbgthreadctx *)arg;
  sharedctx *ctx = bctx->parentctx;
  _ringport **rport = (_ringport **)calloc(sizeof(_ringport *), ctx->m_worker_machines);
  context **recvctx = (context **)calloc(sizeof(context *), ctx->m_worker_machines);
  _ringport **sport = (_ringport **)calloc(sizeof(_ringport *), ctx->m_worker_machines);
  context **sendctx = (context **)calloc(sizeof(context *), ctx->m_worker_machines);

  for(int i=0; i < ctx->m_worker_machines; i++){
    auto pr = ctx->ps_recvportmap[i];
    rport[i] = pr;
    recvctx[i] = rport[i]->ctx;
    auto ps = ctx->ps_sendportmap[i];
    sport[i] = ps;
    sendctx[i] = sport[i]->ctx;
  }

  int clock=0;
  while(1){
    void *msg = NULL;
    int len=-1;
    msg = recvctx[clock]->pull_ps_entry_inq(&len);
    if(msg != NULL){
      pspacket *pkt = (pspacket *)msg;
      int src = pkt->src;
      assert(clock == src);
      //      strads_msg(ERR, "[PS server  serverid : %d]  process a packet from machine %d\n",
      //		 (ctx->rank - ctx->m_sched_machines), pkt->src);
      void *ubuf = (void *)((uintptr_t)(pkt) + sizeof(pspacket));
      assert((uintptr_t)ubuf % sizeof(long) == 0);
      void *rbuf=NULL;
      int rlen=-1;

      string key;
      string value;
      md_deserialize(ubuf, key, value);  // reset ptr of pairs and word
      if(pkt->cbtype == cb_putgetasync){
	(*ctx->ps_server_pgasyncfunc)(key, value, ctx);
      }else if(pkt->cbtype == cb_putsync){
	(*ctx->ps_server_putsyncfunc)(key, value, ctx);
      }else if(pkt->cbtype == cb_getsync){
	(*ctx->ps_server_getsyncfunc)(key, value, ctx);
      }else{
	assert(0);
      }
      int pLen, pServerId;
      void *payload = md_serialize(key, value, ctx->m_sched_machines, &pLen, &pServerId);
      int sendLen;
      void *sendbuf = make_cyclonepacket(payload, pLen, pkt, &sendLen, ctx->rank);

      pspacket *pstmp = (pspacket *)sendbuf;
      assert(pstmp->cbtype == pkt->cbtype);

      sendctx[clock]->push_ps_entry_outq((void *)sendbuf, sendLen);
      free(pkt);
      free(payload);
      free(sendbuf);

      // TODO REplace send with helper thread and send thread
    }
    clock ++ ;
    clock = clock % ctx->m_worker_machines;
  }
}

// take user packet as byte string and make a new pspacket with the header from client and new user packet from ps server
// Since client pspacket header contains client specific information,
//  that should be kept for the message to be sent back to the client.
void *make_cyclonepacket(void *usrPacket, int usrLen, pspacket *pspkt, int *sendLen, int srcRank){
  void *bstring = (void *)calloc(sizeof(pspacket) + usrLen, 1);
  memcpy(bstring, pspkt, sizeof(pspacket));
  //  pspacket *newpkt = (pspacket*)bstring;
  //  newpkt->src = srcRank; // reset src machine rank only, don't touch any thing else

  void *pos = (void *)((uintptr_t)(bstring) + sizeof(pspacket));
  memcpy(pos, usrPacket, usrLen);
  *sendLen = sizeof(pspacket) + usrLen;
  //  strads_msg(ERR, "sendLen: %d   sizeof(pspacket): %ld  usrLen: %d \n", *sendLen, sizeof(pspacket), usrLen);
  return bstring;
}

void *md_serialize(std::string &key, std::string &value, int servers, int *pLen, int *pServerId){

  std::hash<std::string> string_hash;
  size_t hashValue = string_hash(key);
  int serverId = hashValue % servers;
  int keyLen = key.size();
  int valueLen = value.size();

  void *bstring = (void *)calloc(sizeof(mdpacket)+keyLen+valueLen, 1);
  mdpacket *md = (mdpacket *)bstring;
  md->keyLen = keyLen;
  md->serverId = serverId;
  md->hashValue = hashValue;
  md->valueLen = valueLen;

  md->keyString = (void *)((uintptr_t)(bstring) + sizeof(mdpacket));
  md->valueString = (void *)((uintptr_t)(md->keyString) + keyLen);

  assert(keyLen == key.size());
  memcpy(md->keyString, key.c_str(), keyLen);

  assert(valueLen == value.size());
  memcpy(md->valueString, value.c_str(), valueLen);
  md->length = keyLen + valueLen + sizeof(mdpacket);

  *pLen = md->length;
  *pServerId = serverId;

  //  strads_msg(ERR, "[md serialize ]  md->keyLen(%d), md->serverId(%d), md->hadhValue(%lu), md->valueLen(%d), md->valueLen(%d) PKT Lentgh(%d)\n",
  //             md->keyLen, md->serverId, md->hashValue, md->valueLen, valueLen, *pLen);
  return bstring;
}

// reset ptr of pairs and word
// then deserailize
void md_deserialize(void *bstring, std::string &key, std::string&value){
  assert(key.size() == 0);
  assert(value.size() == 0);
  assert(bstring);
  mdpacket *md = (mdpacket *)bstring;
  int keyLen = md->keyLen;
  int valueLen = md->valueLen;
  md->keyString = (void *)((uintptr_t)(bstring) + sizeof(mdpacket));
  md->valueString = (void *)((uintptr_t)(md->keyString) + keyLen);
  key.assign((char *)md->keyString, keyLen);
  value.assign((char *)md->valueString, valueLen);
  return ;
}
#endif
<commit_msg>hangout bug fix<commit_after>#include <strads/include/common.hpp>
#include <strads/netdriver/zmq/zmq-common.hpp>
#include <strads/netdriver/comm.hpp>
#include <strads/ps/strads-ps.hpp>
#include <mpi.h>
#include <zmq.hpp>
#include <string>
#include <vector>
#include <map>
#include <strads/cyclone/strads-cyclone.hpp>

using namespace std;

eCycloneRole Cyclone::role_ = cycloneUnknown;
int Cyclone::serverCount_ = -1;
int Cyclone::rank_ = -1;

map<int, _ringport *>*Cyclone::sendPortMap_ = NULL;
map<int, _ringport *>*Cyclone::recvPortMap_ = NULL;
int Cyclone::maxasync_ = -1;
int Cyclone::clientCount_ = -1;

void Cyclone::cycloneClientBGThread(Cyclone *Obj){
}

void Cyclone::printCycloneConf(void){
  if(role == cycloneClient){
    strads_msg(ERR, "[ Client rank %d ] -- sendmap.size(%ld) recvmap.size(%ld) \n", rank, sendPortMap.size(), recvPortMap.size());
  }else if(role == cycloneServer){
    strads_msg(ERR, "[ Server rank %d ] -- sendmap.size(%ld) recvmap.size(%ld) \n", rank, sendPortMap.size(), recvPortMap.size());
  }
}

void Cyclone::cycloneServerBGThread(Cyclone *Obj){
}

void *Cyclone::_makeCyclonePacket(void *usrPacket, int usrLen, CyclonePacket *pkt, int sendLen, int srcRank){
  return NULL;
}
void *Cyclone::serialize(std::string &key, std::string &value, int *pLen, int *pServerId){
  return NULL;
}

void Cyclone::deserialize(void *bytes, std::string &key, std::string &value){
}

void Cyclone::cycloneAsyncPutGet(Strads &ctx, std::string &key, std::string &value){

  int len=-1;
  int serverid=-1;
  void *buf = serialize(key, value, &len, &serverid); // convert user bytes into CyclonePacket with meta information
  CyclonePacket *packet = (CyclonePacket *)calloc(sizeof(CyclonePacket) + len, 1);
  void *ubuf = (void *)((uintptr_t)(packet) + sizeof(CyclonePacket));
  assert((uintptr_t)ubuf % sizeof(long) == 0);
  packet->ubuf = ubuf;
  memcpy(ubuf, buf, len);
  packet->len = sizeof(CyclonePacket) + len;
  packet->src = rank;
  packet->cbtype = cycmd_putgetasync;  // don't forget this

  auto ps = sendPortMap[serverid];
  _ringport *sport = ps;
}

void Cyclone::cycloneSyncPut(Strads &ctx, std::string &key, std::string &value){

}

void Cyclone::cycloneSyncGet(Strads &ctx, std::string &key, std::string &value){

}
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2017 Robert Ou <rqou@robertou.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthCoolrunner2Pass : public ScriptPass
{
	SynthCoolrunner2Pass() : ScriptPass("synth_coolrunner2", "synthesis for Xilinx Coolrunner-II CPLDs") { }

	virtual void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_coolrunner2 [options]\n");
		log("\n");
		log("This command runs synthesis for Coolrunner-II CPLDs. This work is experimental.\n");
		log("It is intended to be used with https://github.com/azonenberg/openfpga as the\n");
		log("place-and-route.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module (default='top')\n");
		log("\n");
		log("    -json <file>\n");
		log("        write the design to the specified JSON file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -noflatten\n");
		log("        do not flatten design before synthesis\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with -dff option\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	string top_opt, json_file;
	bool flatten, retime;

	virtual void clear_flags() YS_OVERRIDE
	{
		top_opt = "-auto-top";
		json_file = "";
		flatten = true;
		retime = false;
	}

	virtual void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-json" && argidx+1 < args.size()) {
				json_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-noflatten") {
				flatten = false;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!design->full_selection())
			log_cmd_error("This comannd only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_COOLRUNNER2 pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	virtual void script() YS_OVERRIDE
	{
		if (check_label("begin"))
		{
			run("read_verilog -lib +/coolrunner2/cells_sim.v");
			run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
		}

		if (check_label("flatten", "(unless -noflatten)") && flatten)
		{
			run("proc");
			run("flatten");
			run("tribuf -logic");
		}

		if (check_label("coarse"))
		{
			run("synth -run coarse");
		}

		if (check_label("fine"))
		{
			run("opt -fast -full");
			run("techmap");
			run("techmap -map +/coolrunner2/cells_latch.v");
			run("dfflibmap -prepare -liberty +/coolrunner2/xc2_dff.lib");
		}

		if (check_label("map_tff"))
		{
			// This is quite hacky. By telling abc that it can only use AND and XOR gates, abc will try and use XOR
			// gates "whenever possible." This will hopefully cause toggle flip-flop structures to turn into an XOR
			// connected to a D flip-flop. We then match on these and convert them into XC2 TFF cells.
			run("abc -g AND,XOR");
			run("clean");
			run("extract -map +/coolrunner2/tff_extract.v");
		}

		if (check_label("map_pla"))
		{
			run("abc -sop -I 40 -P 56");
			run("clean");
		}

		if (check_label("map_cells"))
		{
			run("dfflibmap -liberty +/coolrunner2/xc2_dff.lib");
			run("dffinit -ff FDCP Q INIT");
			run("dffinit -ff FDCP_N Q INIT");
			run("dffinit -ff FTCP Q INIT");
			run("dffinit -ff FTCP_N Q INIT");
			run("dffinit -ff LDCP Q INIT");
			run("dffinit -ff LDCP_N Q INIT");
			run("coolrunner2_sop");
			run("iopadmap -bits -inpad IBUF O:I -outpad IOBUFE I:IO -inoutpad IOBUFE O:IO -toutpad IOBUFE E:I:IO -tinoutpad IOBUFE E:O:I:IO");
			run("attrmvcp -attr src -attr LOC t:IOBUFE n:*");
			run("attrmvcp -attr src -attr LOC -driven t:IBUF n:*");
			run("clean");
		}

		if (check_label("check"))
		{
			run("hierarchy -check");
			run("stat");
			run("check -noinit");
		}

		if (check_label("json"))
		{
			if (!json_file.empty() || help_mode)
				run(stringf("write_json %s", help_mode ? "<file-name>" : json_file.c_str()));
		}

		log_pop();
	}
} SynthCoolrunner2Pass;

PRIVATE_NAMESPACE_END
<commit_msg>coolrunner2: Split multi-bit nets<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2017 Robert Ou <rqou@robertou.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthCoolrunner2Pass : public ScriptPass
{
	SynthCoolrunner2Pass() : ScriptPass("synth_coolrunner2", "synthesis for Xilinx Coolrunner-II CPLDs") { }

	virtual void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_coolrunner2 [options]\n");
		log("\n");
		log("This command runs synthesis for Coolrunner-II CPLDs. This work is experimental.\n");
		log("It is intended to be used with https://github.com/azonenberg/openfpga as the\n");
		log("place-and-route.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module (default='top')\n");
		log("\n");
		log("    -json <file>\n");
		log("        write the design to the specified JSON file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -noflatten\n");
		log("        do not flatten design before synthesis\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with -dff option\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	string top_opt, json_file;
	bool flatten, retime;

	virtual void clear_flags() YS_OVERRIDE
	{
		top_opt = "-auto-top";
		json_file = "";
		flatten = true;
		retime = false;
	}

	virtual void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-json" && argidx+1 < args.size()) {
				json_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-noflatten") {
				flatten = false;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!design->full_selection())
			log_cmd_error("This comannd only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_COOLRUNNER2 pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	virtual void script() YS_OVERRIDE
	{
		if (check_label("begin"))
		{
			run("read_verilog -lib +/coolrunner2/cells_sim.v");
			run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
		}

		if (check_label("flatten", "(unless -noflatten)") && flatten)
		{
			run("proc");
			run("flatten");
			run("tribuf -logic");
		}

		if (check_label("coarse"))
		{
			run("synth -run coarse");
		}

		if (check_label("fine"))
		{
			run("opt -fast -full");
			run("techmap");
			run("techmap -map +/coolrunner2/cells_latch.v");
			run("dfflibmap -prepare -liberty +/coolrunner2/xc2_dff.lib");
		}

		if (check_label("map_tff"))
		{
			// This is quite hacky. By telling abc that it can only use AND and XOR gates, abc will try and use XOR
			// gates "whenever possible." This will hopefully cause toggle flip-flop structures to turn into an XOR
			// connected to a D flip-flop. We then match on these and convert them into XC2 TFF cells.
			run("abc -g AND,XOR");
			run("clean");
			run("extract -map +/coolrunner2/tff_extract.v");
		}

		if (check_label("map_pla"))
		{
			run("abc -sop -I 40 -P 56");
			run("clean");
		}

		if (check_label("map_cells"))
		{
			run("dfflibmap -liberty +/coolrunner2/xc2_dff.lib");
			run("dffinit -ff FDCP Q INIT");
			run("dffinit -ff FDCP_N Q INIT");
			run("dffinit -ff FTCP Q INIT");
			run("dffinit -ff FTCP_N Q INIT");
			run("dffinit -ff LDCP Q INIT");
			run("dffinit -ff LDCP_N Q INIT");
			run("coolrunner2_sop");
			run("iopadmap -bits -inpad IBUF O:I -outpad IOBUFE I:IO -inoutpad IOBUFE O:IO -toutpad IOBUFE E:I:IO -tinoutpad IOBUFE E:O:I:IO");
			run("attrmvcp -attr src -attr LOC t:IOBUFE n:*");
			run("attrmvcp -attr src -attr LOC -driven t:IBUF n:*");
			run("splitnets");
			run("clean");
		}

		if (check_label("check"))
		{
			run("hierarchy -check");
			run("stat");
			run("check -noinit");
		}

		if (check_label("json"))
		{
			if (!json_file.empty() || help_mode)
				run(stringf("write_json %s", help_mode ? "<file-name>" : json_file.c_str()));
		}

		log_pop();
	}
} SynthCoolrunner2Pass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "mlir/Dialect/Shape/IR/Shape.h"  // from @llvm-project
#include "mlir/Dialect/StandardOps/IR/Ops.h"  // from @llvm-project
#include "mlir/IR/Dialect.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/import_utils.h"
#include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h"
#include "tensorflow/compiler/tf2xla/tf2xla.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"

namespace tensorflow {

namespace {

// A fake device to simulate the presence of a CPU.
class FakeDevice : public Device {
 public:
  explicit FakeDevice(const DeviceAttributes& device_attributes)
      : Device(nullptr, device_attributes) {}

  Status Sync() override { return errors::Unimplemented("FakeDevice::Sync()"); }
};

// Translates the graph input information from tf2xla:::Config to
// GraphImportConfig.
Status ConvertInputInfo(
    const tf2xla::Config& config,
    const std::unordered_map<std::string, std::string>& feed_name_remap,
    GraphImportConfig* specs) {
  std::vector<std::string> array_names;
  std::vector<std::string> data_types;
  std::vector<std::vector<int>> shapes;
  for (const tf2xla::Feed& feed : config.feed()) {
    std::string place_holder_name =
        feed_name_remap.at(TensorIdToString(feed.id()));
    array_names.push_back(place_holder_name);
    data_types.push_back(
        feed.type() == DT_INVALID ? "" : DataType_Name(feed.type()));
    std::vector<int> dims;
    dims.reserve(feed.shape().dim_size());
    absl::c_for_each(feed.shape().dim(), [&](const TensorShapeProto::Dim d) {
      dims.push_back(d.size());
    });
    shapes.push_back(dims);
  }

  return ParseInputArrayInfo(array_names, data_types, shapes, &specs->inputs);
}

// Translates the graph output information from tf2xla:::Config to
// GraphImportConfig.
Status ConvertOutputInfo(const tf2xla::Config& config,
                         GraphImportConfig* specs) {
  std::vector<std::string> array_names;
  for (const tf2xla::Fetch& fetch : config.fetch()) {
    array_names.push_back(fetch.id().node_name());
  }

  return ParseOutputArrayInfo(array_names, &specs->outputs);
}

}  // namespace

Status ConvertGraphDefToXlaViaMlir(
    GraphDef graph_def, const tf2xla::Config& config,
    xla::XlaComputation* computation, absl::string_view debug_info_filename,
    absl::string_view debug_info_path_begin_marker) {
  // AddPlaceholdersForFeeds prepares for PruneGraphDefInto and serves two
  // purposes: (1) It creates a placeholder node for each feed, so that
  // PruneGraphDefInfo can prune away the node containing the feed. (2) It
  // is also a workaround for b/149029125. It replaces a feed representation
  // with a placeholder node that contains a single output.
  FunctionLibraryDefinition flib_def(OpRegistry::Global(), graph_def.library());
  std::unique_ptr<Graph> graph(new Graph(flib_def));
  std::unordered_map<string, string> feed_name_remap;
  TF_RETURN_IF_ERROR(AddPlaceholdersForFeeds(config, graph->op_registry(),
                                             &feed_name_remap, &graph_def));

  // TODO(b/149024678): remove this workaround after the ticket is fixed.
  //   Prune the GraphDef because MLIR importer doesn't allow unknown ops in
  //   graph nodes even the nodes are not needed for computing the outputs.
  GraphDef pruned_graph_def;
  TF_RETURN_IF_ERROR(PruneGraphDefInto(config, graph_def, &pruned_graph_def));

  GraphImportConfig specs;
  specs.prune_unused_nodes = false;
  specs.convert_legacy_fed_inputs = false;
  specs.graph_as_function = false;
  specs.upgrade_legacy = true;
  TF_RETURN_IF_ERROR(ConvertInputInfo(config, feed_name_remap, &specs));
  TF_RETURN_IF_ERROR(ConvertOutputInfo(config, &specs));

  GraphDebugInfo debug_info;
  if (!debug_info_filename.empty()) {
    TF_RETURN_IF_ERROR(LoadProtoFromFile(debug_info_filename, &debug_info));

    if (!debug_info_path_begin_marker.empty()) {
      for (size_t i = 0, e = debug_info.files_size(); i < e; ++i) {
        std::string* file_name = debug_info.mutable_files(i);
        size_t location =
            file_name->rfind(std::string(debug_info_path_begin_marker));
        if (location != std::string::npos) {
          *file_name = file_name->substr(location +
                                         debug_info_path_begin_marker.length());
        }
      }
    }
  }

  mlir::MLIRContext context;
  TF_ASSIGN_OR_RETURN(
      mlir::OwningModuleRef module,
      ConvertGraphdefToMlir(pruned_graph_def, debug_info, specs, &context));

  // Construct a CPU device and add the device to the operations.
  DeviceSet device_set;
  DeviceAttributes attr;
  attr.set_name("/job:localhost/replica:0/task:0/device:CPU:0");
  attr.set_device_type(DeviceType("CPU").type());
  FakeDevice device(attr);
  device_set.AddDevice(&device);
  AddDevicesToOp(*module, &device_set);

  TF_RETURN_IF_ERROR(mlir::TF::RunBridgeWithStandardPipeline(
      *module, /*enable_logging=*/VLOG_IS_ON(1), /*enable_inliner=*/true));

  // Convert the MLIR module to XLA computation. If the input graph can't be
  // lowered down to a single graph node with a single island by the previous
  // step, this step will return an error.
  return ConvertMLIRToXlaComputation(*module, /*device_type=*/"XLA_CPU_JIT",
                                     computation,
                                     /*use_tuple_args=*/false,
                                     /*always_return_tuple=*/true);
}

}  // namespace tensorflow
<commit_msg>Fix parameter name mismatch.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "mlir/Dialect/Shape/IR/Shape.h"  // from @llvm-project
#include "mlir/Dialect/StandardOps/IR/Ops.h"  // from @llvm-project
#include "mlir/IR/Dialect.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/import_model.h"
#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/compile_mlir_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/import_utils.h"
#include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h"
#include "tensorflow/compiler/tf2xla/tf2xla.h"
#include "tensorflow/compiler/tf2xla/tf2xla_util.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"

namespace tensorflow {

namespace {

// A fake device to simulate the presence of a CPU.
class FakeDevice : public Device {
 public:
  explicit FakeDevice(const DeviceAttributes& device_attributes)
      : Device(nullptr, device_attributes) {}

  Status Sync() override { return errors::Unimplemented("FakeDevice::Sync()"); }
};

// Translates the graph input information from tf2xla:::Config to
// GraphImportConfig.
Status ConvertInputInfo(
    const tf2xla::Config& config,
    const std::unordered_map<std::string, std::string>& feed_name_remap,
    GraphImportConfig* specs) {
  std::vector<std::string> array_names;
  std::vector<std::string> data_types;
  std::vector<std::vector<int>> shapes;
  for (const tf2xla::Feed& feed : config.feed()) {
    std::string place_holder_name =
        feed_name_remap.at(TensorIdToString(feed.id()));
    array_names.push_back(place_holder_name);
    data_types.push_back(
        feed.type() == DT_INVALID ? "" : DataType_Name(feed.type()));
    std::vector<int> dims;
    dims.reserve(feed.shape().dim_size());
    absl::c_for_each(feed.shape().dim(), [&](const TensorShapeProto::Dim d) {
      dims.push_back(d.size());
    });
    shapes.push_back(dims);
  }

  return ParseInputArrayInfo(array_names, data_types, shapes, &specs->inputs);
}

// Translates the graph output information from tf2xla:::Config to
// GraphImportConfig.
Status ConvertOutputInfo(const tf2xla::Config& config,
                         GraphImportConfig* specs) {
  std::vector<std::string> array_names;
  for (const tf2xla::Fetch& fetch : config.fetch()) {
    array_names.push_back(fetch.id().node_name());
  }

  return ParseOutputArrayInfo(array_names, &specs->outputs);
}

}  // namespace

Status ConvertGraphDefToXlaViaMlir(
    GraphDef graph_def, const tf2xla::Config& config,
    xla::XlaComputation* computation, absl::string_view debug_info_filename,
    absl::string_view debug_info_path_begin_marker) {
  // AddPlaceholdersForFeeds prepares for PruneGraphDefInto and serves two
  // purposes: (1) It creates a placeholder node for each feed, so that
  // PruneGraphDefInfo can prune away the node containing the feed. (2) It
  // is also a workaround for b/149029125. It replaces a feed representation
  // with a placeholder node that contains a single output.
  FunctionLibraryDefinition flib_def(OpRegistry::Global(), graph_def.library());
  std::unique_ptr<Graph> graph(new Graph(flib_def));
  std::unordered_map<string, string> feed_name_remap;
  TF_RETURN_IF_ERROR(AddPlaceholdersForFeeds(config, graph->op_registry(),
                                             &feed_name_remap, &graph_def));

  // TODO(b/149024678): remove this workaround after the ticket is fixed.
  //   Prune the GraphDef because MLIR importer doesn't allow unknown ops in
  //   graph nodes even the nodes are not needed for computing the outputs.
  GraphDef pruned_graph_def;
  TF_RETURN_IF_ERROR(PruneGraphDefInto(config, graph_def, &pruned_graph_def));

  GraphImportConfig specs;
  specs.prune_unused_nodes = false;
  specs.convert_legacy_fed_inputs = false;
  specs.graph_as_function = false;
  specs.upgrade_legacy = true;
  TF_RETURN_IF_ERROR(ConvertInputInfo(config, feed_name_remap, &specs));
  TF_RETURN_IF_ERROR(ConvertOutputInfo(config, &specs));

  GraphDebugInfo debug_info;
  if (!debug_info_filename.empty()) {
    TF_RETURN_IF_ERROR(LoadProtoFromFile(debug_info_filename, &debug_info));

    if (!debug_info_path_begin_marker.empty()) {
      for (size_t i = 0, e = debug_info.files_size(); i < e; ++i) {
        std::string* file_name = debug_info.mutable_files(i);
        size_t location =
            file_name->rfind(std::string(debug_info_path_begin_marker));
        if (location != std::string::npos) {
          *file_name = file_name->substr(location +
                                         debug_info_path_begin_marker.length());
        }
      }
    }
  }

  mlir::MLIRContext context;
  TF_ASSIGN_OR_RETURN(
      mlir::OwningModuleRef module,
      ConvertGraphdefToMlir(pruned_graph_def, debug_info, specs, &context));

  // Construct a CPU device and add the device to the operations.
  DeviceSet device_set;
  DeviceAttributes attr;
  attr.set_name("/job:localhost/replica:0/task:0/device:CPU:0");
  attr.set_device_type(DeviceType("CPU").type());
  FakeDevice device(attr);
  device_set.AddDevice(&device);
  AddDevicesToOp(*module, &device_set);

  TF_RETURN_IF_ERROR(mlir::TF::RunBridgeWithStandardPipeline(
      *module, /*enable_logging=*/VLOG_IS_ON(1), /*enable_inliner=*/true));

  // Convert the MLIR module to XLA computation. If the input graph can't be
  // lowered down to a single graph node with a single island by the previous
  // step, this step will return an error.
  return ConvertMLIRToXlaComputation(*module, /*device_type=*/"XLA_CPU_JIT",
                                     computation,
                                     /*use_tuple_args=*/false,
                                     /*return_tuple=*/true);
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/grappler/grappler_item.h"

#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils.h"

namespace tensorflow {
namespace grappler {

GrapplerItem::GrapplerItem(const GrapplerItem& other, GraphDef&& graphDef) {
  id = other.id;
  feed = other.feed;
  fetch = other.fetch;
  init_ops = other.init_ops;
  expected_init_time = other.expected_init_time;
  queue_runners = other.queue_runners;
  graph.Swap(&graphDef);
}

std::vector<const NodeDef*> GrapplerItem::MainOpsFanin() const {
  return ComputeTransitiveFanin(graph, fetch);
}

std::vector<const NodeDef*> GrapplerItem::EnqueueOpsFanin() const {
  std::vector<string> enqueue_ops;
  for (const auto& queue_runner : queue_runners) {
    for (const string& enqueue_op : queue_runner.enqueue_op_name()) {
      enqueue_ops.push_back(enqueue_op);
    }
  }
  return ComputeTransitiveFanin(graph, enqueue_ops);
}

std::vector<const NodeDef*> GrapplerItem::InitOpsFanin() const {
  return ComputeTransitiveFanin(graph, init_ops);
}

std::vector<const NodeDef*> GrapplerItem::MainVariables() const {
  std::vector<const NodeDef*> fanin = ComputeTransitiveFanin(graph, init_ops);
  std::vector<const NodeDef*> vars;
  for (const NodeDef* node : fanin) {
    if (IsVariable(*node)) {
      vars.push_back(node);
    }
  }
  return vars;
}

std::unordered_set<string> GrapplerItem::NodesToPreserve() const {
  std::unordered_set<string> result;
  for (const string& f : fetch) {
    result.insert(NodeName(f));
  }
  for (const auto& f : feed) {
    result.insert(NodeName(f.first));
  }
  for (const auto& node : init_ops) {
    result.insert(NodeName(node));
  }
  for (const auto& queue_runner : queue_runners) {
    for (const string& enqueue_op : queue_runner.enqueue_op_name()) {
      result.insert(NodeName(enqueue_op));
    }
    if (!queue_runner.close_op_name().empty()) {
      result.insert(NodeName(queue_runner.close_op_name()));
    }
    if (!queue_runner.cancel_op_name().empty()) {
      result.insert(NodeName(queue_runner.cancel_op_name()));
    }
  }
  return result;
}

std::vector<const NodeDef*> ComputeTransitiveFanin(
    const GraphDef& graph, const std::vector<string>& terminal_nodes) {
  bool ill_formed = false;
  std::vector<const NodeDef*> result =
      ComputeTransitiveFanin(graph, terminal_nodes, &ill_formed);
  CHECK(!ill_formed);
  return result;
}

std::vector<const NodeDef*> ComputeTransitiveFanin(
    const GraphDef& graph, const std::vector<string>& terminal_nodes,
    bool* ill_formed) {
  *ill_formed = false;
  std::unordered_map<string, const NodeDef*> name_to_node;
  for (const auto& node : graph.node()) {
    name_to_node[node.name()] = &node;
  }

  std::vector<const NodeDef*> queue;
  for (const string& root : terminal_nodes) {
    const NodeDef* node = name_to_node[NodeName(root)];
    if (!node) {
      *ill_formed = true;
      return {};
    }
    queue.push_back(node);
  }

  std::vector<const NodeDef*> result;
  std::unordered_set<const NodeDef*> visited;

  while (!queue.empty()) {
    const NodeDef* node = queue.back();
    queue.pop_back();
    if (!visited.insert(node).second) {
      // The node has already been visited.
      continue;
    }
    result.push_back(node);
    for (const string& input : node->input()) {
      const NodeDef* in = name_to_node[NodeName(input)];
      if (!in) {
        *ill_formed = true;
        return {};
      }
      queue.push_back(in);
    }
  }
  return result;
}

}  // end namespace grappler
}  // end namespace tensorflow
<commit_msg>List the save/restore nodes in the set of nodes to preserve<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/grappler/grappler_item.h"

#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/grappler/op_types.h"
#include "tensorflow/core/grappler/utils.h"

namespace tensorflow {
namespace grappler {

GrapplerItem::GrapplerItem(const GrapplerItem& other, GraphDef&& graphDef) {
  id = other.id;
  feed = other.feed;
  fetch = other.fetch;
  init_ops = other.init_ops;
  expected_init_time = other.expected_init_time;
  queue_runners = other.queue_runners;
  graph.Swap(&graphDef);
}

std::vector<const NodeDef*> GrapplerItem::MainOpsFanin() const {
  return ComputeTransitiveFanin(graph, fetch);
}

std::vector<const NodeDef*> GrapplerItem::EnqueueOpsFanin() const {
  std::vector<string> enqueue_ops;
  for (const auto& queue_runner : queue_runners) {
    for (const string& enqueue_op : queue_runner.enqueue_op_name()) {
      enqueue_ops.push_back(enqueue_op);
    }
  }
  return ComputeTransitiveFanin(graph, enqueue_ops);
}

std::vector<const NodeDef*> GrapplerItem::InitOpsFanin() const {
  return ComputeTransitiveFanin(graph, init_ops);
}

std::vector<const NodeDef*> GrapplerItem::MainVariables() const {
  std::vector<const NodeDef*> fanin = ComputeTransitiveFanin(graph, init_ops);
  std::vector<const NodeDef*> vars;
  for (const NodeDef* node : fanin) {
    if (IsVariable(*node)) {
      vars.push_back(node);
    }
  }
  return vars;
}

std::unordered_set<string> GrapplerItem::NodesToPreserve() const {
  std::unordered_set<string> result;
  for (const string& f : fetch) {
    result.insert(NodeName(f));
  }
  for (const auto& f : feed) {
    result.insert(NodeName(f.first));
  }
  for (const auto& node : init_ops) {
    result.insert(NodeName(node));
  }
  if (!save_op.empty()) {
    result.insert(NodeName(save_op));
  }
  if (!restore_op.empty()) {
    result.insert(NodeName(restore_op));
  }
  if (!save_restore_loc_tensor.empty()) {
    result.insert(NodeName(save_restore_loc_tensor));
  }

  for (const auto& queue_runner : queue_runners) {
    for (const string& enqueue_op : queue_runner.enqueue_op_name()) {
      result.insert(NodeName(enqueue_op));
    }
    if (!queue_runner.close_op_name().empty()) {
      result.insert(NodeName(queue_runner.close_op_name()));
    }
    if (!queue_runner.cancel_op_name().empty()) {
      result.insert(NodeName(queue_runner.cancel_op_name()));
    }
  }
  return result;
}

std::vector<const NodeDef*> ComputeTransitiveFanin(
    const GraphDef& graph, const std::vector<string>& terminal_nodes) {
  bool ill_formed = false;
  std::vector<const NodeDef*> result =
      ComputeTransitiveFanin(graph, terminal_nodes, &ill_formed);
  CHECK(!ill_formed);
  return result;
}

std::vector<const NodeDef*> ComputeTransitiveFanin(
    const GraphDef& graph, const std::vector<string>& terminal_nodes,
    bool* ill_formed) {
  *ill_formed = false;
  std::unordered_map<string, const NodeDef*> name_to_node;
  for (const auto& node : graph.node()) {
    name_to_node[node.name()] = &node;
  }

  std::vector<const NodeDef*> queue;
  for (const string& root : terminal_nodes) {
    const NodeDef* node = name_to_node[NodeName(root)];
    if (!node) {
      *ill_formed = true;
      return {};
    }
    queue.push_back(node);
  }

  std::vector<const NodeDef*> result;
  std::unordered_set<const NodeDef*> visited;

  while (!queue.empty()) {
    const NodeDef* node = queue.back();
    queue.pop_back();
    if (!visited.insert(node).second) {
      // The node has already been visited.
      continue;
    }
    result.push_back(node);
    for (const string& input : node->input()) {
      const NodeDef* in = name_to_node[NodeName(input)];
      if (!in) {
        *ill_formed = true;
        return {};
      }
      queue.push_back(in);
    }
  }
  return result;
}

}  // end namespace grappler
}  // end namespace tensorflow
<|endoftext|>


<commit_before>// Copyright (c) 2014-2015 DiMS dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"

#include <boost/foreach.hpp>

#include "common/actionHandler.h"
#include "common/authenticationProvider.h"

#include "tracker/clientRequestsManager.h"
#include "tracker/getBalanceAction.h"
#include "tracker/trackerNodesManager.h"
#include "tracker/controller.h"
#include "tracker/transactionRecordManager.h"

using namespace common;

namespace tracker
{

class CHandleClientRequestVisitor : public common::CClientRequestVisitorHandlerBase
{
public:
	using CClientRequestVisitorHandlerBase::operator ();

	CHandleClientRequestVisitor(uint256 const & _hash):m_hash( _hash ){};

	void operator()( CTransactionStatusReq const & _transactionStatus ) const
	{
		// shoudn't be handled this way
		CTransaction transaction;
		if ( CTransactionRecordManager::getInstance()->getTransaction( _transactionStatus.m_hash, transaction ) )
		{
			std::vector<unsigned char> signedHash;
			common::CAuthenticationProvider::getInstance()->sign( transaction.GetHash(), signedHash );
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Confirmed, transaction.GetHash(), signedHash ) );
		}
		else
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Unconfirmed, _transactionStatus.m_hash ) );
	}

	void operator()( CTrackerStatsReq const & _trackerStatsReq ) const
	{
		CController * controller = CController::getInstance();
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTrackerSpecificStats( controller->getPrice() ) );
	}

	void operator()( CTransactionMessage const & _transactionMessage ) const
	{
		CTransactionRecordManager::getInstance()->addClientTransaction( _transactionMessage.m_transaction );
	}

	void operator()( CAddressBalanceReq const & _addressBalanceReq ) const
	{
		CKeyID keyId;
		CMnemonicAddress( _addressBalanceReq.m_address ).GetKeyID( keyId );
		common::CActionHandler::getInstance()->executeAction( (common::CAction*)new CGetBalanceAction( keyId, m_hash ) );
	}

	void operator()( CNetworkInfoReq const & _networkInfoReq ) const
	{
		// handle  it through  action  handler??
		std::vector< common::CValidNodeInfo > validNodesInfo;

		BOOST_FOREACH( common::CValidNodeInfo const & validNodeInfo, CTrackerNodesManager::getInstance()->getNodesInfo( common::CRole::Tracker ) )
		{
			validNodesInfo.push_back( validNodeInfo );
		}
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CClientNetworkInfoResult( validNodesInfo, common::CAuthenticationProvider::getInstance()->getMyKey(), common::CRole::Tracker ) );
	}
private:
	uint256 const m_hash;
};

CClientRequestsManager * CClientRequestsManager::ms_instance = NULL;

CClientRequestsManager::CClientRequestsManager()
{

}

CClientRequestsManager*
CClientRequestsManager::getInstance( )
{
	if ( !ms_instance )
	{
		ms_instance = new CClientRequestsManager();
	};
	return ms_instance;
}

CClientRequestsManager::~CClientRequestsManager()
{}

void
CClientRequestsManager::addRequest( NodeRequests const & _nodeRequest, uint256 const & _hash )
{
	boost::lock_guard<boost::mutex> lock( m_requestLock );
	m_getInfoRequest.insert( std::make_pair( _hash, _nodeRequest ) );
}

bool
CClientRequestsManager::getResponse( uint256 const & _token, ClientResponse & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );

	InfoResponseRecord::iterator iterator = m_infoResponseRecord.find( _token );

	if ( iterator != m_infoResponseRecord.end() )
	{
		_clientResponse = iterator->second;
		m_infoResponseRecord.erase( iterator );

		return true;
	}

	return false;
}

void
CClientRequestsManager::setClientResponse( uint256 const & _hash, ClientResponse const & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );
	if ( m_infoResponseRecord.find( _hash ) != m_infoResponseRecord.end() )
		m_infoResponseRecord.erase(_hash);
	m_infoResponseRecord.insert( std::make_pair( _hash, _clientResponse ) );
}

void
CClientRequestsManager::processRequestLoop()
{
	while(1)
	{
		MilliSleep(1000);
		{
			boost::lock_guard<boost::mutex> lock( m_requestLock );

			BOOST_FOREACH( InfoRequestRecord::value_type request, m_getInfoRequest )
			{
				boost::apply_visitor( CHandleClientRequestVisitor( request.first ), request.second );
			}

			m_getInfoRequest.clear();
		}

		boost::this_thread::interruption_point();

	}
}

}
<commit_msg>small fix in tracker<commit_after>// Copyright (c) 2014-2015 DiMS dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"

#include <boost/foreach.hpp>

#include "common/actionHandler.h"
#include "common/authenticationProvider.h"

#include "tracker/clientRequestsManager.h"
#include "tracker/getBalanceAction.h"
#include "tracker/trackerNodesManager.h"
#include "tracker/controller.h"
#include "tracker/transactionRecordManager.h"

using namespace common;

namespace tracker
{

class CHandleClientRequestVisitor : public common::CClientRequestVisitorHandlerBase
{
public:
	using CClientRequestVisitorHandlerBase::operator ();

	CHandleClientRequestVisitor(uint256 const & _hash):m_hash( _hash ){};

	void operator()( CTransactionStatusReq const & _transactionStatus ) const
	{
		// shoudn't be handled this way
		CTransaction transaction;
		if ( CTransactionRecordManager::getInstance()->getTransaction( _transactionStatus.m_hash, transaction ) )
		{
			std::vector<unsigned char> signedHash;
			common::CAuthenticationProvider::getInstance()->sign( transaction.GetHash(), signedHash );
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Confirmed, transaction.GetHash(), signedHash ) );
		}
		else
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Unconfirmed, _transactionStatus.m_hash ) );
	}

	void operator()( CTrackerStatsReq const & _trackerStatsReq ) const
	{
		CController * controller = CController::getInstance();
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTrackerSpecificStats( controller->getPrice() ) );
	}

	void operator()( CTransactionMessage const & _transactionMessage ) const
	{
		CTransactionRecordManager::getInstance()->addClientTransaction( _transactionMessage.m_transaction );
	}

	void operator()( CAddressBalanceReq const & _addressBalanceReq ) const
	{
		CKeyID keyId;
		CMnemonicAddress( _addressBalanceReq.m_address ).GetKeyID( keyId );
		common::CActionHandler::getInstance()->executeAction( (common::CAction*)new CGetBalanceAction( keyId, m_hash ) );
	}

	void operator()( CNetworkInfoReq const & _networkInfoReq ) const
	{
		// handle  it through  action  handler??
		std::vector< common::CValidNodeInfo > validNodesInfo;

		BOOST_FOREACH( common::CValidNodeInfo const & validNodeInfo, CTrackerNodesManager::getInstance()->getNodesInfo( common::CRole::Tracker ) )
		{
			validNodesInfo.push_back( validNodeInfo );
		}

		BOOST_FOREACH( common::CValidNodeInfo const & validNodeInfo, CTrackerNodesManager::getInstance()->getNodesInfo( common::CRole::Monitor ) )
		{
			validNodesInfo.push_back( validNodeInfo );
		}
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CClientNetworkInfoResult( validNodesInfo, common::CAuthenticationProvider::getInstance()->getMyKey(), common::CRole::Tracker ) );
	}
private:
	uint256 const m_hash;
};

CClientRequestsManager * CClientRequestsManager::ms_instance = NULL;

CClientRequestsManager::CClientRequestsManager()
{

}

CClientRequestsManager*
CClientRequestsManager::getInstance( )
{
	if ( !ms_instance )
	{
		ms_instance = new CClientRequestsManager();
	};
	return ms_instance;
}

CClientRequestsManager::~CClientRequestsManager()
{}

void
CClientRequestsManager::addRequest( NodeRequests const & _nodeRequest, uint256 const & _hash )
{
	boost::lock_guard<boost::mutex> lock( m_requestLock );
	m_getInfoRequest.insert( std::make_pair( _hash, _nodeRequest ) );
}

bool
CClientRequestsManager::getResponse( uint256 const & _token, ClientResponse & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );

	InfoResponseRecord::iterator iterator = m_infoResponseRecord.find( _token );

	if ( iterator != m_infoResponseRecord.end() )
	{
		_clientResponse = iterator->second;
		m_infoResponseRecord.erase( iterator );

		return true;
	}

	return false;
}

void
CClientRequestsManager::setClientResponse( uint256 const & _hash, ClientResponse const & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );
	if ( m_infoResponseRecord.find( _hash ) != m_infoResponseRecord.end() )
		m_infoResponseRecord.erase(_hash);
	m_infoResponseRecord.insert( std::make_pair( _hash, _clientResponse ) );
}

void
CClientRequestsManager::processRequestLoop()
{
	while(1)
	{
		MilliSleep(1000);
		{
			boost::lock_guard<boost::mutex> lock( m_requestLock );

			BOOST_FOREACH( InfoRequestRecord::value_type request, m_getInfoRequest )
			{
				boost::apply_visitor( CHandleClientRequestVisitor( request.first ), request.second );
			}

			m_getInfoRequest.clear();
		}

		boost::this_thread::interruption_point();

	}
}

}
<|endoftext|>