<commit_before>//
// Copyright (C) 2000 Stefan Seefeld
// Copyright (C) 2000 Stephen Davies
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//

#ifndef H_SYNOPSIS_CPP_SWALKER
#define H_SYNOPSIS_CPP_SWALKER

#include <Synopsis/PTree.hh>
#include <occ/Walker.hh>
// Stupid occ
#undef Scope

#include <vector>
#include <string>

// Forward declarations
class Builder;
namespace Synopsis {class Buffer;}
class Decoder;
class TypeFormatter;
class LinkStore;
class Lookup;
class FileFilter;

namespace AST
{
class SourceFile;
class Parameter;
class Inheritance;
class Declaration;
class Function;
class Scope;
}
namespace Types
{
class Type;
}

//. A walker that creates an AST. All Translate* methods have been overridden
//. to remove the translation code.
class SWalker : public Walker
{
public:
  //. Constructor
  SWalker(FileFilter*, Builder*, Synopsis::Buffer*);
  virtual ~SWalker();

  //. Sets store links to true.
  //. This will cause the whole ptree to be traversed, and any linkable
  //. identifiers found will be stored
  void set_store_links(LinkStore*);

  //. Get a name from the ptree
  std::string parse_name(PTree::Node *) const;

  //. Get the Buffer object
  Synopsis::Buffer* buffer() { return my_buffer;}
  //. Get the Builder object
  Builder* builder() { return my_builder;}
  //. Get the TypeFormatter object
  TypeFormatter* type_formatter(){ return my_type_formatter;}
#if 0
  //. Returns true if the current filename from the last getLine or
  //. updateLineNumber call is equal to the main source filename
  bool is_main_file() { return (my_filename == my_source);}
#endif

  //. Get the line number of the given Ptree node
  int line_of_ptree(PTree::Node *);
  //. Update the line number
  void update_line_number(PTree::Node *);

  void add_comments(AST::Declaration* decl, PTree::Node *comments);
  void add_comments(AST::Declaration* decl, PTree::CommentedAtom *node);
  void add_comments(AST::Declaration* decl, PTree::Declarator *node);
  void add_comments(AST::Declaration* decl, PTree::Declaration *decl);
  void add_comments(AST::Declaration* decl, PTree::NamespaceSpec *decl);
  //. Traverses left side of tree till it finds a leaf, and if that is a
  //. CommentedAtom then it adds those comments as spans
  void find_comments(PTree::Node * node);

  // Takes the (maybe 0) args list and puts them in my_params
  void translate_function_args(PTree::Node * args);
  void translate_parameters(PTree::Node * p_params, std::vector<AST::Parameter*>& params);
  void translate_function_name(const PTree::Encoding &encname, std::string& realname, Types::Type*& returnType);
  PTree::Node *translate_declarator(PTree::Node *);
  PTree::Node *translate_function_declarator(PTree::Node *, bool is_const);
  PTree::Node *translate_variable_declarator(PTree::Node *, bool is_const);
  void translate_typedef_declarator(PTree::Node *node);
  std::vector<AST::Inheritance*> translate_inheritance_spec(PTree::Node *node);
  //. Returns a formatter string of the parameters. The idea is that this
  //. string will be appended to the function name to form the 'name' of the
  //. function.
  std::string format_parameters(std::vector<AST::Parameter*>& params);

  //. Translates the template parameters and creates the template type.
  void SWalker::translate_template_params(PTree::Node *params);

  //. Overridden to catch exceptions
  void translate(PTree::Node *);

  void visit(PTree::Atom *);
  void visit(PTree::List *);
  void visit(PTree::Typedef *);
  void visit(PTree::TemplateDecl *);
  void visit(PTree::TemplateInstantiation *);
  //virtual PTree::Node * TranslateTemplateInstantiation(PTree::Node *, PTree::Node *, PTree::Node *, Class*);
  void visit(PTree::ExternTemplate *);
  void visit(PTree::CommentedAtom *);
  void visit(PTree::Identifier *node) { translate_variable(node);}
  void visit(PTree::Brace *);
  void visit(PTree::Block *);
  void visit(PTree::ClassBody *node) { visit(static_cast<PTree::Brace *>(node));}
  void visit(PTree::ClassSpec *);
  void visit(PTree::EnumSpec *);
  void visit(PTree::MetaclassDecl *);
  void visit(PTree::LinkageSpec *);
  void visit(PTree::NamespaceSpec *);
  void visit(PTree::UsingDirective *);
  void visit(PTree::Declaration *);
  void visit(PTree::UsingDeclaration *);
  void visit(PTree::Name *node) { translate_variable(node);}
  void visit(PTree::AccessSpec *);
  void visit(PTree::AccessDecl *);
  void visit(PTree::UserAccessSpec *);
  void visit(PTree::IfStatement *);
  void visit(PTree::SwitchStatement *);
  void visit(PTree::WhileStatement *);
  void visit(PTree::DoStatement *);
  void visit(PTree::ForStatement *);
  void visit(PTree::TryStatement *);
  void visit(PTree::BreakStatement *);
  void visit(PTree::ContinueStatement *);
  void visit(PTree::ReturnStatement *);
  void visit(PTree::GotoStatement *);
  void visit(PTree::CaseStatement *);
  void visit(PTree::DefaultStatement *);
  void visit(PTree::LabelStatement *);
  void visit(PTree::ExprStatement *);
  void visit(PTree::Expression *);
  void visit(PTree::AssignExpr *);
  void visit(PTree::CondExpr *);
  void visit(PTree::InfixExpr *);
  void visit(PTree::PmExpr *);
  void visit(PTree::CastExpr *);
  void visit(PTree::UnaryExpr *);
  void visit(PTree::ThrowExpr *);
  void visit(PTree::SizeofExpr *);
  void visit(PTree::NewExpr *);
  void visit(PTree::DeleteExpr *);
  void visit(PTree::Kwd::This *);
  void visit(PTree::FstyleCastExpr *);
  void visit(PTree::ArrayExpr *);
  void visit(PTree::FuncallExpr *); // and fstyle cast
  void visit(PTree::PostfixExpr *);
  void visit(PTree::UserStatementExpr *);
  void visit(PTree::DotMemberExpr *);
  void visit(PTree::ArrowMemberExpr *);
  void visit(PTree::ParenExpr *);
  void visit(PTree::StaticUserStatementExpr *);

  PTree::TemplateDecl *translate_template_class(PTree::TemplateDecl *,
						PTree::ClassSpec *);
  PTree::TemplateDecl *translate_template_function(PTree::TemplateDecl *,
						   PTree::Node *);
  PTree::Node *translate_storage_specifiers(PTree::Node *);
  PTree::Node *translate_declarators(PTree::Node *);
  PTree::Node *translate_arg_decl_list(bool, PTree::Node *, PTree::Node *);
  PTree::Node *translate_initialize_args(PTree::Declarator *, PTree::Node *);
  PTree::Node *translate_assign_initializer(PTree::Declarator *, PTree::Node *);
  PTree::Node *translate_function_implementation(PTree::Node *);
  PTree::Node *translate_function_body(PTree::Node *);
  //virtual PTree::Node * TranslateClassBody(PTree::Node *, PTree::Node *, Class*);

  //virtual Class* MakeClassMetaobject(PTree::Node *, PTree::Node *, PTree::Node *);
  //virtual PTree::Node * TranslateClassSpec(PTree::Node *, PTree::Node *, PTree::Node *, Class*);

  virtual PTree::Node *translate_type_specifier(PTree::Node *);
  virtual PTree::Node *translate_typeof(PTree::Node *, PTree::Node * declarations);
  virtual PTree::Node *translate_new3(PTree::Node *type);
  void translate_variable(PTree::Node *);

  AST::SourceFile* current_file() const { return my_file;}
  int current_lineno() const { return my_lineno;}
  static SWalker *instance() { return g_swalker;}
private:
  // the 'current' walker is a debugging aid.
  static SWalker* g_swalker;

  Builder* my_builder;
  FileFilter* my_filter;
  Synopsis::Buffer* my_buffer;
  Decoder* my_decoder;
  Lookup* my_lookup;

  //. A pointer to the currect declaration ptree, if any, used to get the
  //. return type and modifiers, etc.
  PTree::Node * my_declaration;
  //. A pointer to the current template parameters, if any, used to get the
  //. template parameters and set in the declaration. Should be 0 if not
  //. in a template.
  std::vector<AST::Parameter*>* my_template;
  //. this reflects the filename containing the currently processed node.
  std::string my_filename;
  int my_lineno;
  //. The current file, set by update_line_number
  AST::SourceFile* my_file;

  //. True if should try and extract tail comments before }'s
  bool my_extract_tails;
  //. Storage for links. This is only set if we should be storing links, so
  //. it must be checked before every use
  LinkStore* my_links;
  //. True if this TranslateDeclarator should try to store the decl type
  bool my_store_decl;

  //. A dummy name used for tail comments
  std::vector<std::string> my_dummyname;

  //. An instance of TypeFormatter for formatting types
  TypeFormatter* my_type_formatter;

  //. The current function, if in a function block
  AST::Function* my_function;
  //. The params found before a function block. These may be different from
  //. the ones that are in the original declaration(s), but it is these names
  //. we need for referencing names inside the block, so a reference is stored
  //. here.
  std::vector<AST::Parameter*> my_param_cache;
  //. The types accumulated for function parameters in function calls
  std::vector<Types::Type*> my_params;
  //. The type returned from the expression-type translators
  Types::Type* my_type;
  //. The Scope to use for name lookups, or 0 to use enclosing default
  //. scope rules. This is for when we are at a Variable, and already know it
  //. must be part of a given class (eg, foo->bar .. bar must be in foo's
  //. class)
  AST::Scope* my_scope;

  //. The state of postfix translation. This is needed for constructs like
  //. foo->var versus var or foo->var(). The function call resolution needs
  //. to be done in the final TranslateVariable, since that's where the last
  //. name (which is to be linked) is handled.
  enum Postfix_Flag
  {
    Postfix_Var, //.< Lookup as a variable
    Postfix_Func, //.< Lookup as a function, using my_params for parameters
  } my_postfix_flag;

  //. Info about one stored function impl. Function impls must be stored
  //. till the end of a class.
  struct FuncImplCache
  {
    AST::Function* func;
    std::vector<AST::Parameter*> params;
    PTree::Node * body;
  };
  //. A vector of function impls
  typedef std::vector<FuncImplCache> FuncImplVec;
  //. A stack of function impl vectors
  typedef std::vector<FuncImplVec> FuncImplStack;
  //. The stack of function impl vectors
  FuncImplStack my_func_impl_stack;
  void SWalker::translate_func_impl_cache(const FuncImplCache &cache);

  //. Finds the column given the start ptr and the current position. The
  //. derived column number is processed with the macro call dictionary
  //. from the current file before returning,
  //. so -1 may be returned to indicate "inside macro".
  int find_col(const char* start, const char* find);
};

#endif // header guard
<commit_msg>various fixes and enhancements from Luke Petre<commit_after>//
// Copyright (C) 2000 Stefan Seefeld
// Copyright (C) 2000 Stephen Davies
// All rights reserved.
// Licensed to the public under the terms of the GNU LGPL (>= 2),
// see the file COPYING for details.
//

#ifndef H_SYNOPSIS_CPP_SWALKER
#define H_SYNOPSIS_CPP_SWALKER

#include <Synopsis/PTree.hh>
#include <occ/Walker.hh>
// Stupid occ
#undef Scope

#include <vector>
#include <string>

// Forward declarations
class Builder;
namespace Synopsis {class Buffer;}
class Decoder;
class TypeFormatter;
class LinkStore;
class Lookup;
class FileFilter;

namespace AST
{
class SourceFile;
class Parameter;
class Inheritance;
class Declaration;
class Function;
class Scope;
}
namespace Types
{
class Type;
}

//. A walker that creates an AST. All Translate* methods have been overridden
//. to remove the translation code.
class SWalker : public Walker
{
public:
  //. Constructor
  SWalker(FileFilter*, Builder*, Synopsis::Buffer*);
  virtual ~SWalker();

  //. Sets store links to true.
  //. This will cause the whole ptree to be traversed, and any linkable
  //. identifiers found will be stored
  void set_store_links(LinkStore*);

  //. Get a name from the ptree
  std::string parse_name(PTree::Node *) const;

  //. Get the Buffer object
  Synopsis::Buffer* buffer() { return my_buffer;}
  //. Get the Builder object
  Builder* builder() { return my_builder;}
  //. Get the TypeFormatter object
  TypeFormatter* type_formatter(){ return my_type_formatter;}
#if 0
  //. Returns true if the current filename from the last getLine or
  //. updateLineNumber call is equal to the main source filename
  bool is_main_file() { return (my_filename == my_source);}
#endif

  //. Get the line number of the given Ptree node
  int line_of_ptree(PTree::Node *);
  //. Update the line number
  void update_line_number(PTree::Node *);

  void add_comments(AST::Declaration* decl, PTree::Node *comments);
  void add_comments(AST::Declaration* decl, PTree::CommentedAtom *node);
  void add_comments(AST::Declaration* decl, PTree::Declarator *node);
  void add_comments(AST::Declaration* decl, PTree::Declaration *node);
  void add_comments(AST::Declaration* decl, PTree::NamespaceSpec *node);
  //. Traverses left side of tree till it finds a leaf, and if that is a
  //. CommentedAtom then it adds those comments as spans
  void find_comments(PTree::Node * node);

  // Takes the (maybe 0) args list and puts them in my_params
  void translate_function_args(PTree::Node * args);
  void translate_parameters(PTree::Node * p_params, std::vector<AST::Parameter*>& params);
  void translate_function_name(const PTree::Encoding &encname, std::string& realname, Types::Type*& returnType);
  PTree::Node *translate_declarator(PTree::Node *);
  PTree::Node *translate_function_declarator(PTree::Node *, bool is_const);
  PTree::Node *translate_variable_declarator(PTree::Node *, bool is_const);
  void translate_typedef_declarator(PTree::Node *node);
  std::vector<AST::Inheritance*> translate_inheritance_spec(PTree::Node *node);
  //. Returns a formatter string of the parameters. The idea is that this
  //. string will be appended to the function name to form the 'name' of the
  //. function.
  std::string format_parameters(std::vector<AST::Parameter*>& params);

  //. Translates the template parameters and creates the template type.
  void SWalker::translate_template_params(PTree::Node *params);

  //. Overridden to catch exceptions
  void translate(PTree::Node *);

  void visit(PTree::Atom *);
  void visit(PTree::List *);
  void visit(PTree::Typedef *);
  void visit(PTree::TemplateDecl *);
  void visit(PTree::TemplateInstantiation *);
  //virtual PTree::Node * TranslateTemplateInstantiation(PTree::Node *, PTree::Node *, PTree::Node *, Class*);
  void visit(PTree::ExternTemplate *);
  void visit(PTree::CommentedAtom *);
  void visit(PTree::Identifier *node) { translate_variable(node);}
  void visit(PTree::Brace *);
  void visit(PTree::Block *);
  void visit(PTree::ClassBody *node) { visit(static_cast<PTree::Brace *>(node));}
  void visit(PTree::ClassSpec *);
  void visit(PTree::EnumSpec *);
  void visit(PTree::MetaclassDecl *);
  void visit(PTree::LinkageSpec *);
  void visit(PTree::NamespaceSpec *);
  void visit(PTree::UsingDirective *);
  void visit(PTree::Declaration *);
  void visit(PTree::UsingDeclaration *);
  void visit(PTree::Name *node) { translate_variable(node);}
  void visit(PTree::AccessSpec *);
  void visit(PTree::AccessDecl *);
  void visit(PTree::UserAccessSpec *);
  void visit(PTree::IfStatement *);
  void visit(PTree::SwitchStatement *);
  void visit(PTree::WhileStatement *);
  void visit(PTree::DoStatement *);
  void visit(PTree::ForStatement *);
  void visit(PTree::TryStatement *);
  void visit(PTree::BreakStatement *);
  void visit(PTree::ContinueStatement *);
  void visit(PTree::ReturnStatement *);
  void visit(PTree::GotoStatement *);
  void visit(PTree::CaseStatement *);
  void visit(PTree::DefaultStatement *);
  void visit(PTree::LabelStatement *);
  void visit(PTree::ExprStatement *);
  void visit(PTree::Expression *);
  void visit(PTree::AssignExpr *);
  void visit(PTree::CondExpr *);
  void visit(PTree::InfixExpr *);
  void visit(PTree::PmExpr *);
  void visit(PTree::CastExpr *);
  void visit(PTree::UnaryExpr *);
  void visit(PTree::ThrowExpr *);
  void visit(PTree::SizeofExpr *);
  void visit(PTree::NewExpr *);
  void visit(PTree::DeleteExpr *);
  void visit(PTree::Kwd::This *);
  void visit(PTree::FstyleCastExpr *);
  void visit(PTree::ArrayExpr *);
  void visit(PTree::FuncallExpr *); // and fstyle cast
  void visit(PTree::PostfixExpr *);
  void visit(PTree::UserStatementExpr *);
  void visit(PTree::DotMemberExpr *);
  void visit(PTree::ArrowMemberExpr *);
  void visit(PTree::ParenExpr *);
  void visit(PTree::StaticUserStatementExpr *);

  PTree::TemplateDecl *translate_template_class(PTree::TemplateDecl *,
						PTree::ClassSpec *);
  PTree::TemplateDecl *translate_template_function(PTree::TemplateDecl *,
						   PTree::Node *);
  PTree::Node *translate_storage_specifiers(PTree::Node *);
  PTree::Node *translate_declarators(PTree::Node *);
  PTree::Node *translate_arg_decl_list(bool, PTree::Node *, PTree::Node *);
  PTree::Node *translate_initialize_args(PTree::Declarator *, PTree::Node *);
  PTree::Node *translate_assign_initializer(PTree::Declarator *, PTree::Node *);
  PTree::Node *translate_function_implementation(PTree::Node *);
  PTree::Node *translate_function_body(PTree::Node *);
  //virtual PTree::Node * TranslateClassBody(PTree::Node *, PTree::Node *, Class*);

  //virtual Class* MakeClassMetaobject(PTree::Node *, PTree::Node *, PTree::Node *);
  //virtual PTree::Node * TranslateClassSpec(PTree::Node *, PTree::Node *, PTree::Node *, Class*);

  virtual PTree::Node *translate_type_specifier(PTree::Node *);
  virtual PTree::Node *translate_typeof(PTree::Node *, PTree::Node * declarations);
  virtual PTree::Node *translate_new3(PTree::Node *type);
  void translate_variable(PTree::Node *);

  AST::SourceFile* current_file() const { return my_file;}
  int current_lineno() const { return my_lineno;}
  static SWalker *instance() { return g_swalker;}
private:
  // the 'current' walker is a debugging aid.
  static SWalker* g_swalker;

  Builder* my_builder;
  FileFilter* my_filter;
  Synopsis::Buffer* my_buffer;
  Decoder* my_decoder;
  Lookup* my_lookup;

  //. A pointer to the currect declaration ptree, if any, used to get the
  //. return type and modifiers, etc.
  PTree::Node * my_declaration;
  //. A pointer to the current template parameters, if any, used to get the
  //. template parameters and set in the declaration. Should be 0 if not
  //. in a template.
  std::vector<AST::Parameter*>* my_template;
  //. this reflects the filename containing the currently processed node.
  std::string my_filename;
  int my_lineno;
  //. The current file, set by update_line_number
  AST::SourceFile* my_file;

  //. True if should try and extract tail comments before }'s
  bool my_extract_tails;
  //. Storage for links. This is only set if we should be storing links, so
  //. it must be checked before every use
  LinkStore* my_links;
  //. True if this TranslateDeclarator should try to store the decl type
  bool my_store_decl;

  //. A dummy name used for tail comments
  std::vector<std::string> my_dummyname;

  //. An instance of TypeFormatter for formatting types
  TypeFormatter* my_type_formatter;

  //. The current function, if in a function block
  AST::Function* my_function;
  //. The params found before a function block. These may be different from
  //. the ones that are in the original declaration(s), but it is these names
  //. we need for referencing names inside the block, so a reference is stored
  //. here.
  std::vector<AST::Parameter*> my_param_cache;
  //. The types accumulated for function parameters in function calls
  std::vector<Types::Type*> my_params;
  //. The type returned from the expression-type translators
  Types::Type* my_type;
  //. The Scope to use for name lookups, or 0 to use enclosing default
  //. scope rules. This is for when we are at a Variable, and already know it
  //. must be part of a given class (eg, foo->bar .. bar must be in foo's
  //. class)
  AST::Scope* my_scope;

  //. The state of postfix translation. This is needed for constructs like
  //. foo->var versus var or foo->var(). The function call resolution needs
  //. to be done in the final TranslateVariable, since that's where the last
  //. name (which is to be linked) is handled.
  enum Postfix_Flag
  {
    Postfix_Var, //.< Lookup as a variable
    Postfix_Func, //.< Lookup as a function, using my_params for parameters
  } my_postfix_flag;

  //. Info about one stored function impl. Function impls must be stored
  //. till the end of a class.
  struct FuncImplCache
  {
    AST::Function* func;
    std::vector<AST::Parameter*> params;
    PTree::Node * body;
  };
  //. A vector of function impls
  typedef std::vector<FuncImplCache> FuncImplVec;
  //. A stack of function impl vectors
  typedef std::vector<FuncImplVec> FuncImplStack;
  //. The stack of function impl vectors
  FuncImplStack my_func_impl_stack;
  void SWalker::translate_func_impl_cache(const FuncImplCache &cache);

  //. Finds the column given the start ptr and the current position. The
  //. derived column number is processed with the macro call dictionary
  //. from the current file before returning,
  //. so -1 may be returned to indicate "inside macro".
  int find_col(const char* start, const char* find);
};

#endif // header guard
<|endoftext|>


<commit_before>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <memory>
#include <new>

#include "BitFunnel/Exceptions.h"
#include "LoggerInterfaces/Logging.h"
#include "PrivateHeapAllocator.h"

namespace BitFunnel
{
    PrivateHeapAllocator::PrivateHeapAllocator()
    {
        Initialize(1024 * 1024);
    }

    PrivateHeapAllocator::PrivateHeapAllocator(size_t bufferSize)
    {
        Initialize(bufferSize);
    }

    // Free memory and recycle the heap so it can be reused
    void PrivateHeapAllocator::Reset()
    {
        m_start = m_next = m_buffer.get();
    }

    // Allocate a block of memory of specified size from an heap allocator,
    // or from overflow allocator if the size is greater than maxArenaAlloc.
    void* PrivateHeapAllocator::Allocate(size_t size)
    {
        if (m_next + size >= m_end)
        {
            RecoverableError error("PrivateHeapAllocator::Allocate: out of space.");
            throw error;
        }

        void* p = m_next;
        m_next += size;
        return p;
    }

    // "Free" memory allocated by the allocator.
    void PrivateHeapAllocator::Deallocate(void* /*p*/)
    {
        // Intentional nop.
    }

    size_t PrivateHeapAllocator::MaxSize() const
    {
        return m_end - m_start;
    }

    void PrivateHeapAllocator::Initialize(size_t bufferSize)
    {
        m_buffer.reset(new char[bufferSize]);
        m_end = m_start + bufferSize;
        Reset();
    }

    //PrivateHeapAllocatorFactory::~PrivateHeapAllocatorFactory()
    //{
    //    for (unsigned i = 0 ; i < m_freeAllocators.size(); ++i)
    //    {
    //        delete m_freeAllocators[i];
    //    }
    //}

    //Allocators::IAllocator& PrivateHeapAllocatorFactory::CreateAllocator()
    //{
    //    std::lock_guard<std::mutex> lock(m_lock);
    //    if (m_freeAllocators.size() > 0)
    //    {
    //        Allocators::IAllocator* allocator = m_freeAllocators.back();
    //        m_freeAllocators.pop_back();
    //        return *allocator;
    //    }
    //    else
    //    {
    //        Allocators::IAllocator* allocator = new PrivateHeapAllocator();
    //        return *allocator;
    //    }
    //}

    //void PrivateHeapAllocatorFactory::ReleaseAllocator(Allocators::IAllocator& allocator)
    //{
    //    std::lock_guard<std::mutex> lock(m_lock);
    //    m_freeAllocators.push_back(&allocator);
    //}
}
<commit_msg>Fix use of unitialized address in PrivateHeapAllocator. Fixes #184.<commit_after>// The MIT License (MIT)

// Copyright (c) 2016, Microsoft

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include <memory>
#include <new>

#include "BitFunnel/Exceptions.h"
#include "LoggerInterfaces/Logging.h"
#include "PrivateHeapAllocator.h"

namespace BitFunnel
{
    PrivateHeapAllocator::PrivateHeapAllocator()
    {
        Initialize(1024 * 1024);
    }

    PrivateHeapAllocator::PrivateHeapAllocator(size_t bufferSize)
    {
        Initialize(bufferSize);
    }

    // Free memory and recycle the heap so it can be reused
    void PrivateHeapAllocator::Reset()
    {
        m_start = m_next = m_buffer.get();
    }

    // Allocate a block of memory of specified size from an heap allocator,
    // or from overflow allocator if the size is greater than maxArenaAlloc.
    void* PrivateHeapAllocator::Allocate(size_t size)
    {
        if (m_next + size >= m_end)
        {
            RecoverableError error("PrivateHeapAllocator::Allocate: out of space.");
            throw error;
        }

        void* p = m_next;
        m_next += size;
        return p;
    }

    // "Free" memory allocated by the allocator.
    void PrivateHeapAllocator::Deallocate(void* /*p*/)
    {
        // Intentional nop.
    }

    size_t PrivateHeapAllocator::MaxSize() const
    {
        return m_end - m_start;
    }

    void PrivateHeapAllocator::Initialize(size_t bufferSize)
    {
        m_buffer.reset(new char[bufferSize]);
        Reset();
        m_end = m_start + bufferSize;
    }

    //PrivateHeapAllocatorFactory::~PrivateHeapAllocatorFactory()
    //{
    //    for (unsigned i = 0 ; i < m_freeAllocators.size(); ++i)
    //    {
    //        delete m_freeAllocators[i];
    //    }
    //}

    //Allocators::IAllocator& PrivateHeapAllocatorFactory::CreateAllocator()
    //{
    //    std::lock_guard<std::mutex> lock(m_lock);
    //    if (m_freeAllocators.size() > 0)
    //    {
    //        Allocators::IAllocator* allocator = m_freeAllocators.back();
    //        m_freeAllocators.pop_back();
    //        return *allocator;
    //    }
    //    else
    //    {
    //        Allocators::IAllocator* allocator = new PrivateHeapAllocator();
    //        return *allocator;
    //    }
    //}

    //void PrivateHeapAllocatorFactory::ReleaseAllocator(Allocators::IAllocator& allocator)
    //{
    //    std::lock_guard<std::mutex> lock(m_lock);
    //    m_freeAllocators.push_back(&allocator);
    //}
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qserialportinfo.h"
#include "qserialportinfo_p.h"
#include "qttylocker_unix_p.h"
#include "qserialport_unix_p.h"
#include <QtCore/qfile.h>

#ifndef Q_OS_MAC

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)
extern "C"
{
#include <libudev.h>
}
#else
#include <QtCore/qdir.h>
#include <QtCore/qstringlist.h>
#endif

#endif // Q_OS_MAC

QT_BEGIN_NAMESPACE

#ifndef Q_OS_MAC

#if !(defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV))

static inline const QStringList& filtersOfDevices()
{
    static const QStringList deviceFileNameFilterList = QStringList()

#  ifdef Q_OS_LINUX
    << QLatin1String("ttyS*")    // Standart UART 8250 and etc.
    << QLatin1String("ttyUSB*")  // Usb/serial converters PL2303 and etc.
    << QLatin1String("ttyACM*")  // CDC_ACM converters (i.e. Mobile Phones).
    << QLatin1String("ttyGS*")   // Gadget serial device (i.e. Mobile Phones with gadget serial driver).
    << QLatin1String("ttyMI*")   // MOXA pci/serial converters.
    << QLatin1String("ttymxc*")  // Motorola IMX serial ports (i.e. Freescale i.MX).
    << QLatin1String("ttyAMA*")  // AMBA serial device for embedded platform on ARM (i.e. Raspberry Pi).
    << QLatin1String("rfcomm*")  // Bluetooth serial device.
    << QLatin1String("ircomm*"); // IrDA serial device.
#  elif defined (Q_OS_FREEBSD)
    << QLatin1String("cu*");
#  else
    ; // Here for other *nix OS.
#  endif

    return deviceFileNameFilterList;
}

#endif

QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
{
    QList<QSerialPortInfo> serialPortInfoList;

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

    // White list for devices without a parent
    static const QString rfcommDeviceName(QLatin1String("rfcomm"));

    struct ::udev *udev = ::udev_new();
    if (udev) {

        struct ::udev_enumerate *enumerate =
                ::udev_enumerate_new(udev);

        if (enumerate) {

            ::udev_enumerate_add_match_subsystem(enumerate, "tty");
            ::udev_enumerate_scan_devices(enumerate);

            struct ::udev_list_entry *devices =
                    ::udev_enumerate_get_list_entry(enumerate);

            struct ::udev_list_entry *dev_list_entry;
            udev_list_entry_foreach(dev_list_entry, devices) {

                struct ::udev_device *dev =
                        ::udev_device_new_from_syspath(udev,
                                                       ::udev_list_entry_get_name(dev_list_entry));

                if (dev) {

                    QSerialPortInfo serialPortInfo;

                    serialPortInfo.d_ptr->device =
                            QLatin1String(::udev_device_get_devnode(dev));
                    serialPortInfo.d_ptr->portName =
                            QLatin1String(::udev_device_get_sysname(dev));

                    struct ::udev_device *parentdev = ::udev_device_get_parent(dev);

                    bool canAppendToList = true;

                    if (parentdev) {

                        QLatin1String subsys(::udev_device_get_subsystem(parentdev));

                        if (subsys == QLatin1String("usb-serial")
                                || subsys == QLatin1String("usb")) { // USB bus type
                            // Append this devices and try get additional information about them.
                            serialPortInfo.d_ptr->description = QString(
                                    QLatin1String(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL"))).replace('_', ' ');
                            serialPortInfo.d_ptr->manufacturer = QString(
                                    QLatin1String(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR"))).replace('_', ' ');

                            serialPortInfo.d_ptr->vendorIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                "ID_VENDOR_ID")).toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16);

                            serialPortInfo.d_ptr->productIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                "ID_MODEL_ID")).toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16);

                        } else if (subsys == QLatin1String("pnp")) { // PNP bus type
                            // Append this device.
                            // FIXME: How to get additional information about serial devices
                            // with this subsystem?
                        } else if (subsys == QLatin1String("platform")) { // Platform 'pseudo' bus for legacy device.
                            // Skip this devices because this type of subsystem does
                            // not include a real physical serial device.
                            canAppendToList = false;
                        } else { // Others types of subsystems.
                            // Append this devices because we believe that any other types of
                            // subsystems provide a real serial devices. For example, for devices
                            // such as ttyGSx, its driver provide an empty subsystem name, but it
                            // devices is a real physical serial devices.
                            // FIXME: How to get additional information about serial devices
                            // with this subsystems?
                        }
                    } else { // Devices without a parent
                        if (serialPortInfo.d_ptr->portName.startsWith(rfcommDeviceName)) { // Bluetooth device
                            bool ok;
                            // Check for an unsigned decimal integer at the end of the device name: "rfcomm0", "rfcomm15"
                            // devices with negative and invalid numbers in the name are rejected
                            int portNumber = serialPortInfo.d_ptr->portName.mid(rfcommDeviceName.length()).toInt(&ok);

                            if (!ok || (portNumber < 0) || (portNumber > 255)) {
                                canAppendToList = false;
                            }
                        } else {
                            canAppendToList = false;
                        }
                    }

                    if (canAppendToList)
                        serialPortInfoList.append(serialPortInfo);

                    ::udev_device_unref(dev);
                }

            }

            ::udev_enumerate_unref(enumerate);
        }

        ::udev_unref(udev);
    }

#elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB)
    // TODO: Implement me.
#else

    QDir devDir(QLatin1String("/dev"));
    if (devDir.exists()) {

        devDir.setNameFilters(filtersOfDevices());
        devDir.setFilter(QDir::Files | QDir::System | QDir::NoSymLinks);

        QStringList foundDevices; // Found devices list.

        foreach (const QFileInfo &deviceFileInfo, devDir.entryInfoList()) {
            QString deviceFilePath = deviceFileInfo.absoluteFilePath();
            if (!foundDevices.contains(deviceFilePath)) {
                foundDevices.append(deviceFilePath);

                QSerialPortInfo serialPortInfo;

                serialPortInfo.d_ptr->device = deviceFilePath;
                serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(deviceFilePath);

                // Get description, manufacturer, vendor identifier, product
                // identifier are not supported.

                serialPortInfoList.append(serialPortInfo);

            }
        }
    }

#endif

    return serialPortInfoList;
}

#endif // Q_OS_MAC

// common part

QList<qint32> QSerialPortInfo::standardBaudRates()
{
    return QSerialPortPrivate::standardBaudRates();
}

bool QSerialPortInfo::isBusy() const
{
    bool currentPid = false;
    return QTtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid);
}

bool QSerialPortInfo::isValid() const
{
    QFile f(systemLocation());
    return f.exists();
}

QT_END_NAMESPACE
<commit_msg>Linux: Are added the missed QLatin1Char into libudev implementation<commit_after>/****************************************************************************
**
** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com>
** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com>
** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qserialportinfo.h"
#include "qserialportinfo_p.h"
#include "qttylocker_unix_p.h"
#include "qserialport_unix_p.h"
#include <QtCore/qfile.h>

#ifndef Q_OS_MAC

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)
extern "C"
{
#include <libudev.h>
}
#else
#include <QtCore/qdir.h>
#include <QtCore/qstringlist.h>
#endif

#endif // Q_OS_MAC

QT_BEGIN_NAMESPACE

#ifndef Q_OS_MAC

#if !(defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV))

static inline const QStringList& filtersOfDevices()
{
    static const QStringList deviceFileNameFilterList = QStringList()

#  ifdef Q_OS_LINUX
    << QLatin1String("ttyS*")    // Standart UART 8250 and etc.
    << QLatin1String("ttyUSB*")  // Usb/serial converters PL2303 and etc.
    << QLatin1String("ttyACM*")  // CDC_ACM converters (i.e. Mobile Phones).
    << QLatin1String("ttyGS*")   // Gadget serial device (i.e. Mobile Phones with gadget serial driver).
    << QLatin1String("ttyMI*")   // MOXA pci/serial converters.
    << QLatin1String("ttymxc*")  // Motorola IMX serial ports (i.e. Freescale i.MX).
    << QLatin1String("ttyAMA*")  // AMBA serial device for embedded platform on ARM (i.e. Raspberry Pi).
    << QLatin1String("rfcomm*")  // Bluetooth serial device.
    << QLatin1String("ircomm*"); // IrDA serial device.
#  elif defined (Q_OS_FREEBSD)
    << QLatin1String("cu*");
#  else
    ; // Here for other *nix OS.
#  endif

    return deviceFileNameFilterList;
}

#endif

QList<QSerialPortInfo> QSerialPortInfo::availablePorts()
{
    QList<QSerialPortInfo> serialPortInfoList;

#if defined (Q_OS_LINUX) && defined (HAVE_LIBUDEV)

    // White list for devices without a parent
    static const QString rfcommDeviceName(QLatin1String("rfcomm"));

    struct ::udev *udev = ::udev_new();
    if (udev) {

        struct ::udev_enumerate *enumerate =
                ::udev_enumerate_new(udev);

        if (enumerate) {

            ::udev_enumerate_add_match_subsystem(enumerate, "tty");
            ::udev_enumerate_scan_devices(enumerate);

            struct ::udev_list_entry *devices =
                    ::udev_enumerate_get_list_entry(enumerate);

            struct ::udev_list_entry *dev_list_entry;
            udev_list_entry_foreach(dev_list_entry, devices) {

                struct ::udev_device *dev =
                        ::udev_device_new_from_syspath(udev,
                                                       ::udev_list_entry_get_name(dev_list_entry));

                if (dev) {

                    QSerialPortInfo serialPortInfo;

                    serialPortInfo.d_ptr->device =
                            QLatin1String(::udev_device_get_devnode(dev));
                    serialPortInfo.d_ptr->portName =
                            QLatin1String(::udev_device_get_sysname(dev));

                    struct ::udev_device *parentdev = ::udev_device_get_parent(dev);

                    bool canAppendToList = true;

                    if (parentdev) {

                        QLatin1String subsys(::udev_device_get_subsystem(parentdev));

                        if (subsys == QLatin1String("usb-serial")
                                || subsys == QLatin1String("usb")) { // USB bus type
                            // Append this devices and try get additional information about them.
                            serialPortInfo.d_ptr->description = QString(
                                    QLatin1String(::udev_device_get_property_value(dev,
                                                                                "ID_MODEL"))).replace(QLatin1Char('_'), QLatin1Char(' '));
                            serialPortInfo.d_ptr->manufacturer = QString(
                                    QLatin1String(::udev_device_get_property_value(dev,
                                                                                "ID_VENDOR"))).replace(QLatin1Char('_'), QLatin1Char(' '));

                            serialPortInfo.d_ptr->vendorIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                "ID_VENDOR_ID")).toInt(&serialPortInfo.d_ptr->hasVendorIdentifier, 16);

                            serialPortInfo.d_ptr->productIdentifier =
                                    QString::fromLatin1(::udev_device_get_property_value(dev,
                                                "ID_MODEL_ID")).toInt(&serialPortInfo.d_ptr->hasProductIdentifier, 16);

                        } else if (subsys == QLatin1String("pnp")) { // PNP bus type
                            // Append this device.
                            // FIXME: How to get additional information about serial devices
                            // with this subsystem?
                        } else if (subsys == QLatin1String("platform")) { // Platform 'pseudo' bus for legacy device.
                            // Skip this devices because this type of subsystem does
                            // not include a real physical serial device.
                            canAppendToList = false;
                        } else { // Others types of subsystems.
                            // Append this devices because we believe that any other types of
                            // subsystems provide a real serial devices. For example, for devices
                            // such as ttyGSx, its driver provide an empty subsystem name, but it
                            // devices is a real physical serial devices.
                            // FIXME: How to get additional information about serial devices
                            // with this subsystems?
                        }
                    } else { // Devices without a parent
                        if (serialPortInfo.d_ptr->portName.startsWith(rfcommDeviceName)) { // Bluetooth device
                            bool ok;
                            // Check for an unsigned decimal integer at the end of the device name: "rfcomm0", "rfcomm15"
                            // devices with negative and invalid numbers in the name are rejected
                            int portNumber = serialPortInfo.d_ptr->portName.mid(rfcommDeviceName.length()).toInt(&ok);

                            if (!ok || (portNumber < 0) || (portNumber > 255)) {
                                canAppendToList = false;
                            }
                        } else {
                            canAppendToList = false;
                        }
                    }

                    if (canAppendToList)
                        serialPortInfoList.append(serialPortInfo);

                    ::udev_device_unref(dev);
                }

            }

            ::udev_enumerate_unref(enumerate);
        }

        ::udev_unref(udev);
    }

#elif defined (Q_OS_FREEBSD) && defined (HAVE_LIBUSB)
    // TODO: Implement me.
#else

    QDir devDir(QLatin1String("/dev"));
    if (devDir.exists()) {

        devDir.setNameFilters(filtersOfDevices());
        devDir.setFilter(QDir::Files | QDir::System | QDir::NoSymLinks);

        QStringList foundDevices; // Found devices list.

        foreach (const QFileInfo &deviceFileInfo, devDir.entryInfoList()) {
            QString deviceFilePath = deviceFileInfo.absoluteFilePath();
            if (!foundDevices.contains(deviceFilePath)) {
                foundDevices.append(deviceFilePath);

                QSerialPortInfo serialPortInfo;

                serialPortInfo.d_ptr->device = deviceFilePath;
                serialPortInfo.d_ptr->portName = QSerialPortPrivate::portNameFromSystemLocation(deviceFilePath);

                // Get description, manufacturer, vendor identifier, product
                // identifier are not supported.

                serialPortInfoList.append(serialPortInfo);

            }
        }
    }

#endif

    return serialPortInfoList;
}

#endif // Q_OS_MAC

// common part

QList<qint32> QSerialPortInfo::standardBaudRates()
{
    return QSerialPortPrivate::standardBaudRates();
}

bool QSerialPortInfo::isBusy() const
{
    bool currentPid = false;
    return QTtyLocker::isLocked(portName().toLocal8Bit().constData(), &currentPid);
}

bool QSerialPortInfo::isValid() const
{
    QFile f(systemLocation());
    return f.exists();
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <stdio.h>

#include <gtest/gtest.h>

#include "env.h"
#include "logger.h"

int main(int argc, char* argv[]) {
  // tell ENV the path between the cwd and the cyclus executable
  using cyclus::Env;
  using cyclus::Logger;
  std::string path = Env::PathBase(argv[0]);
  Env::SetCyclusRelPath(path);
  Logger::ReportLevel() = cyclus::LEV_ERROR;

  std::string module_path = Env::ModuleEnvVarName() + "=" +
                            Env::GetBuildPath();
  putenv(const_cast<char *>(module_path.c_str()));

  for ( int i = 0; i < argc; i++ ) {
    std::string arg = argv[i];
    if ( arg == "--help" ) {
      std::cout << "GTest flags" << std::endl;
      std::cout << "\t--gtest_list_tests List the tests" << std::endl;
      std::cout << "\t--gtest_repeat Number of times to repeat each test" << std::endl;
      std::cout << "\t--gtest_filter Glob filter of test name" << std::endl;
      std::cout << "\t--gtest_print_time Time required to run" << std::endl;
      std::cout << "\nBy default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the GTEST_FILTER environment variable or the --gtest_filter flag to a filter string, Google Test will only run the tests whose full names (in the form of TestCaseName.TestName) match the filter.\n"
        "The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.\n"
        "A pattern may contain '*' (matches any string) or '?' (matches any single character). For convenience, the filter '*-NegativePatterns' can be also written as '-NegativePatterns'.\n"
        "For example:\n\n"
        " * ./foo_test Has no flag, and thus runs all its tests.\n"
        " * ./foo_test --gtest_filter=* Also runs everything, due to the single match-everything * value.\n"
        " * ./foo_test --gtest_filter=FooTest.* Runs everything in test case FooTest.\n"
        " * ./foo_test --gtest_filter=*Null*:*Constructor* Runs any test whose full name contains either \"Null\" or \"Constructor\".\n"
        " * ./foo_test --gtest_filter=-*DeathTest.* Runs all non-death tests.\n"
        " * ./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in test case FooTest except FooTest.Bar. " << std::endl;
      return 0;
    }
  }
  testing::InitGoogleTest ( &argc, argv );
  return RUN_ALL_TESTS();
}
<commit_msg>adjusted env var setting to append the current var if it was set<commit_after>#include <iostream>
#include <string>
#include <stdio.h>

#include <gtest/gtest.h>

#include "env.h"
#include "logger.h"

int main(int argc, char* argv[]) {
  // tell ENV the path between the cwd and the cyclus executable
  using cyclus::Env;
  using cyclus::Logger;
  std::string path = Env::PathBase(argv[0]);
  Env::SetCyclusRelPath(path);
  Logger::ReportLevel() = cyclus::LEV_ERROR;

  // add the build path to the environment for testing
  std::string test_env = Env::ModuleEnvVarName() + "=" + Env::GetBuildPath();
  std::string curr_var = Env::ModuleEnvVar();
  std::string new_var = "";
  if (curr_var != "") {
    test_env += ":" + curr_var;
  }
  putenv(const_cast<char *>(test_env.c_str()));

  for ( int i = 0; i < argc; i++ ) {
    std::string arg = argv[i];
    if ( arg == "--help" ) {
      std::cout << "GTest flags" << std::endl;
      std::cout << "\t--gtest_list_tests List the tests" << std::endl;
      std::cout << "\t--gtest_repeat Number of times to repeat each test" << std::endl;
      std::cout << "\t--gtest_filter Glob filter of test name" << std::endl;
      std::cout << "\t--gtest_print_time Time required to run" << std::endl;
      std::cout << "\nBy default, a Google Test program runs all tests the user has defined. Sometimes, you want to run only a subset of the tests (e.g. for debugging or quickly verifying a change). If you set the GTEST_FILTER environment variable or the --gtest_filter flag to a filter string, Google Test will only run the tests whose full names (in the form of TestCaseName.TestName) match the filter.\n"
        "The format of a filter is a ':'-separated list of wildcard patterns (called the positive patterns) optionally followed by a '-' and another ':'-separated pattern list (called the negative patterns). A test matches the filter if and only if it matches any of the positive patterns but does not match any of the negative patterns.\n"
        "A pattern may contain '*' (matches any string) or '?' (matches any single character). For convenience, the filter '*-NegativePatterns' can be also written as '-NegativePatterns'.\n"
        "For example:\n\n"
        " * ./foo_test Has no flag, and thus runs all its tests.\n"
        " * ./foo_test --gtest_filter=* Also runs everything, due to the single match-everything * value.\n"
        " * ./foo_test --gtest_filter=FooTest.* Runs everything in test case FooTest.\n"
        " * ./foo_test --gtest_filter=*Null*:*Constructor* Runs any test whose full name contains either \"Null\" or \"Constructor\".\n"
        " * ./foo_test --gtest_filter=-*DeathTest.* Runs all non-death tests.\n"
        " * ./foo_test --gtest_filter=FooTest.*-FooTest.Bar Runs everything in test case FooTest except FooTest.Bar. " << std::endl;
      return 0;
    }
  }
  testing::InitGoogleTest ( &argc, argv );
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2015,
 Dan Bethell, Johannes Saam, Vahan Sosoyan.
 All rights reserved. See Copyright.txt for more details.
 */

#include "Server.h"
#include "Client.h"
#include <boost/lexical_cast.hpp>
#include <vector>
#include <iostream>
#include <stdexcept>

using namespace aton;
using boost::asio::ip::tcp;

Server::Server() :
        mPort(0),
        mSocket( mIoService ),
        mAcceptor( mIoService )
{
}

Server::Server( int port ) :
        mPort(0),
        mSocket( mIoService ),
        mAcceptor( mIoService )
{
    connect( port );
}

Server::~Server()
{
    if ( mAcceptor.is_open() )
        mAcceptor.close();
}

void Server::connect( int port, bool search )
{
    // disconnect if necessary
    if ( mAcceptor.is_open() )
        mAcceptor.close();

    // reconnect at specified port
    int start_port = port;
    while (!mAcceptor.is_open() && port < start_port + 99)
    {
        try
        {
            tcp::endpoint endpoint( boost::asio::ip::tcp::v4(), port );
            mAcceptor.open(endpoint.protocol());
            mAcceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));
            mAcceptor.bind(endpoint);
            mAcceptor.listen();
            mPort = port;
        }
        catch (...)
        {
            mAcceptor.close();
            if (!search)
                break;
            else
                port++;
        }
    }

    // handle failed connection
    if ( !mAcceptor.is_open() )
    {
        char buffer[32];
        sprintf(buffer, "port: %d", start_port);
        if (search)
            sprintf(buffer, "port: %d-%d", start_port, start_port + 99);
        std::string error = "Failed to connect to port ";
        error += buffer;
        throw std::runtime_error( error.c_str() );
    }
}

void Server::quit()
{
    std::string hostname("localhost");
    aton::Client client(hostname, mPort);
    client.quit();
}

void Server::accept()
{
    if ( mSocket.is_open() )
        mSocket.close();
    mAcceptor.accept(mSocket);
}

Data Server::listen()
{
    Data d;

    // read the key from the incoming data
    try
    {
        int key = -1;
        boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)) );

        switch( key )
        {
            case 0: // open image
            {
                // send back an image id
                int image_id = 1;
                boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int) ) );

                // get width & height
                int width, height, rArea, version;
                float currentFrame;

                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&width), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&height), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&rArea), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&version), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&currentFrame), sizeof(int)) );

                // create data object
                d.mType = key;
                d.mWidth = width;
                d.mHeight = height;
                d.mRArea = rArea;
                d.mVersion = version;
                d.mCurrentFrame = currentFrame;
                break;
            }
            case 1: // image data
            {
                d.mType = key;

                // receive image id
                int image_id;
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int)) );

                // get data info
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mX), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mY), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mWidth), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mHeight), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mRArea), sizeof(long long)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mVersion), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mCurrentFrame), sizeof(float)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mSpp), sizeof(int)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mRam), sizeof(long long)) );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mTime), sizeof(int)) );

                // get aov name's size
                size_t aov_size=0;
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t)) );

                // get aov name
                d.mAovName = new char[aov_size];
                boost::asio::read( mSocket, boost::asio::buffer(d.mAovName, aov_size));

                // get pixels
                int num_samples = d.width() * d.height() * d.spp();
                d.mPixelStore.resize( num_samples );
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mPixelStore[0]), sizeof(float)*num_samples ) ) ;
                break;
            }
            case 2: // close image
            {
                int image_id;
                d.mType = key;
                boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int)) );
                mSocket.close();
                break;
            }
            case 9: // quit
            {
                d.mType = 9;

                //debug Closing socket
                std::cout << "Socket closed" << std::endl;

                mSocket.close();

                // This fixes all nuke destructor issues on windows
                mAcceptor.close();
                break;
            }
        }
    }
    catch( ... )
    {
        mSocket.close();
        throw std::runtime_error( "Could not read from socket!" );
    }

    return d;
}
<commit_msg>Polish<commit_after>/*
 Copyright (c) 2015,
 Dan Bethell, Johannes Saam, Vahan Sosoyan.
 All rights reserved. See Copyright.txt for more details.
 */

#include "Server.h"
#include "Client.h"
#include <boost/lexical_cast.hpp>
#include <vector>
#include <iostream>
#include <stdexcept>

using namespace aton;
using boost::asio::ip::tcp;

Server::Server() :
        mPort(0),
        mSocket(mIoService),
        mAcceptor(mIoService)
{
}

Server::Server(int port) :
        mPort(0),
        mSocket(mIoService),
        mAcceptor(mIoService)
{
    connect(port);
}

Server::~Server()
{
    if (mAcceptor.is_open())
        mAcceptor.close();
}

void Server::connect(int port, bool search)
{
    // disconnect if necessary
    if (mAcceptor.is_open())
        mAcceptor.close();

    // reconnect at specified port
    int start_port = port;
    while (!mAcceptor.is_open() && port < start_port + 99)
    {
        try
        {
            tcp::endpoint endpoint( boost::asio::ip::tcp::v4(), port );
            mAcceptor.open(endpoint.protocol());
            mAcceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(false));
            mAcceptor.bind(endpoint);
            mAcceptor.listen();
            mPort = port;
        }
        catch (...)
        {
            mAcceptor.close();
            if (!search)
                break;
            else
                port++;
        }
    }

    // handle failed connection
    if (!mAcceptor.is_open())
    {
        char buffer[32];
        sprintf(buffer, "port: %d", start_port);
        if (search)
            sprintf(buffer, "port: %d-%d", start_port, start_port + 99);
        std::string error = "Failed to connect to port ";
        error += buffer;
        throw std::runtime_error( error.c_str() );
    }
}

void Server::quit()
{
    std::string hostname("localhost");
    aton::Client client(hostname, mPort);
    client.quit();
}

void Server::accept()
{
    if (mSocket.is_open())
        mSocket.close();
    mAcceptor.accept(mSocket);
}

Data Server::listen()
{
    Data d;

    // read the key from the incoming data
    try
    {
        int key = -1;
        boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)));

        switch( key )
        {
            case 0: // open image
            {
                // send back an image id
                int image_id = 1;
                boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int)));

                // get width & height
                int width, height, rArea, version;
                float currentFrame;

                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&width), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&height), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&rArea), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&version), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&currentFrame), sizeof(int)));

                // create data object
                d.mType = key;
                d.mWidth = width;
                d.mHeight = height;
                d.mRArea = rArea;
                d.mVersion = version;
                d.mCurrentFrame = currentFrame;
                break;
            }
            case 1: // image data
            {
                d.mType = key;

                // receive image id
                int image_id;
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int)) );

                // get data info
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mX), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mY), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mWidth), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mHeight), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mRArea), sizeof(long long)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mVersion), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mCurrentFrame), sizeof(float)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mSpp), sizeof(int)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mRam), sizeof(long long)));
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mTime), sizeof(int)));

                // get aov name's size
                size_t aov_size=0;
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t)));

                // get aov name
                d.mAovName = new char[aov_size];
                boost::asio::read(mSocket, boost::asio::buffer(d.mAovName, aov_size));

                // get pixels
                int num_samples = d.width() * d.height() * d.spp();
                d.mPixelStore.resize(num_samples);
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&d.mPixelStore[0]), sizeof(float)*num_samples)) ;
                break;
            }
            case 2: // close image
            {
                int image_id;
                d.mType = key;
                boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&image_id), sizeof(int)));
                mSocket.close();
                break;
            }
            case 9: // quit
            {
                d.mType = 9;

                //debug Closing socket
                std::cout << "Socket closed" << std::endl;

                mSocket.close();

                // This fixes all nuke destructor issues on windows
                mAcceptor.close();
                break;
            }
        }
    }
    catch( ... )
    {
        mSocket.close();
        throw std::runtime_error("Could not read from socket!");
    }
    return d;
}
<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iree/compiler/Conversion/HLOToLinalg/Passes.h"

#include "iree/compiler/Conversion/Common/Attributes.h"
#include "iree/compiler/Conversion/Common/Passes.h"
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/LinalgToLLVM/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/StandardOps/Transforms/Passes.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/Passes.h"

namespace mlir {
namespace iree_compiler {

void addLinalgToLLVMPasses(OpPassManager &passManager,
                           LLVMCodegenOptions options) {
  OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(
      createLinalgTileAndVectorizeWorkgroupsPass());

  nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass());

  // Linalg -> SCF
  nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass());
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(createCSEPass());

  // SCF -> STD
  nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass());
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(createCSEPass());

  // Handled tensor-type constants.
  nestedModulePM.addPass(createTensorConstantBufferizePass());
  nestedModulePM.addPass(createFoldTensorExtractOpPass());

  // (HAL, IREE, Linalg, STD) -> LLVM
  nestedModulePM.addPass(createConvertToLLVMPass(options));

  nestedModulePM.addPass(createCanonicalizerPass());
  nestedModulePM.addPass(createCSEPass());
}

void buildLLVMTransformPassPipeline(OpPassManager &passManager,
                                    LLVMCodegenOptions options) {
  if (options.usingLinalgOnTensors) {
    passManager.addPass(createMaterializeCPULaunchConfigurationPass());
    OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
    nestedModulePM.addPass(createInlinerPass());
    // TODO(ataei): We want to enable when tensor -> vector pass is fully
    // supported which requires first moving vector-tiling before this step.
    if (options.useLinalgOnTensorsToVectors) {
      nestedModulePM.addNestedPass<FuncOp>(createLinalgVectorizePass());
    }
    // Use stack allocation on CPU side.
    WorkgroupMemoryAllocationFn allocationFn =
        [](OpBuilder &builder, Location loc, ArrayRef<int64_t> staticShape,
           Type elementType, ArrayRef<Value> dynamicSizes) {
          MemRefType allocType = MemRefType::get(staticShape, elementType);
          return builder.create<memref::AllocaOp>(loc, allocType, dynamicSizes);
        };
    addLinalgBufferizePasses(nestedModulePM, allocationFn);
    nestedModulePM.addPass(createPromoteBuffersToStackPass(1 << 10, 64, 10));
  } else {
    // Distribute linalg op among a 3d grid of parallel threads. Tile each
    // workgroup thread memory then vectorize the linalg op.
    OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
    nestedModulePM.addPass(createInlinerPass());
    passManager.addPass(createLinalgTileAndDistributePass());
    // Propagates dynamic shapes computation on tensors.
    nestedModulePM.addNestedPass<FuncOp>(Shape::createTieDynamicShapesPass());
    nestedModulePM.addNestedPass<FuncOp>(
        Shape::createMaterializeShapeCalculationsPass());
    nestedModulePM.addNestedPass<FuncOp>(
        Shape::createHoistShapeCalculationsPass());
    nestedModulePM.addNestedPass<FuncOp>(createConvert1x1ConvToDotPass());
    nestedModulePM.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
    addHLOToLinalgOnBuffersPasses(nestedModulePM);
  }
  // Linalg -> LLVM passes.
  addLinalgToLLVMPasses(passManager, options);
}

static PassPipelineRegistration<> linalgLLVMVPipeline(
    "iree-codegen-linalg-to-llvm-pipeline",
    "Runs the progressive lowering pipeline from Linalg to LLVM",
    [](OpPassManager &passManager) {
      buildLLVMTransformPassPipeline(passManager,
                                     getLLVMCodegenOptionsFromClOptions());
    });

static PassPipelineRegistration<> hloToLinalgLLVMVPipeline(
    "iree-codegen-hlo-to-llvm-pipeline",
    "Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM",
    [](OpPassManager &passManager) {
      buildLLVMTransformPassPipeline(passManager,
                                     getLLVMCodegenOptionsFromClOptions());
    });

}  // namespace iree_compiler
}  // namespace mlir
<commit_msg>Remove inliner from linalg on tensors pass (#5489)<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iree/compiler/Conversion/HLOToLinalg/Passes.h"

#include "iree/compiler/Conversion/Common/Attributes.h"
#include "iree/compiler/Conversion/Common/Passes.h"
#include "iree/compiler/Conversion/HLOToHLO/Passes.h"
#include "iree/compiler/Conversion/LinalgToLLVM/Passes.h"
#include "iree/compiler/Dialect/Shape/Transforms/Passes.h"
#include "mlir/Conversion/SCFToStandard/SCFToStandard.h"
#include "mlir/Dialect/Linalg/Passes.h"
#include "mlir/Dialect/StandardOps/Transforms/Passes.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/Passes.h"

namespace mlir {
namespace iree_compiler {

void addLinalgToLLVMPasses(OpPassManager &passManager,
                           LLVMCodegenOptions options) {
  OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(
      createLinalgTileAndVectorizeWorkgroupsPass());

  nestedModulePM.addNestedPass<FuncOp>(createPlanConvLoopOrderPass());

  // Linalg -> SCF
  nestedModulePM.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass());
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(createCSEPass());

  // SCF -> STD
  nestedModulePM.addNestedPass<FuncOp>(createLowerToCFGPass());
  nestedModulePM.addNestedPass<FuncOp>(createCanonicalizerPass());
  nestedModulePM.addNestedPass<FuncOp>(createCSEPass());

  // Handled tensor-type constants.
  nestedModulePM.addPass(createTensorConstantBufferizePass());
  nestedModulePM.addPass(createFoldTensorExtractOpPass());

  // (HAL, IREE, Linalg, STD) -> LLVM
  nestedModulePM.addPass(createConvertToLLVMPass(options));

  nestedModulePM.addPass(createCanonicalizerPass());
  nestedModulePM.addPass(createCSEPass());
}

void buildLLVMTransformPassPipeline(OpPassManager &passManager,
                                    LLVMCodegenOptions options) {
  if (options.usingLinalgOnTensors) {
    passManager.addPass(createMaterializeCPULaunchConfigurationPass());
    OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
    // TODO(ataei): We want to enable when tensor -> vector pass is fully
    // supported which requires first moving vector-tiling before this step.
    if (options.useLinalgOnTensorsToVectors) {
      nestedModulePM.addNestedPass<FuncOp>(createLinalgVectorizePass());
    }
    // Use stack allocation on CPU side.
    WorkgroupMemoryAllocationFn allocationFn =
        [](OpBuilder &builder, Location loc, ArrayRef<int64_t> staticShape,
           Type elementType, ArrayRef<Value> dynamicSizes) {
          MemRefType allocType = MemRefType::get(staticShape, elementType);
          return builder.create<memref::AllocaOp>(loc, allocType, dynamicSizes);
        };
    addLinalgBufferizePasses(nestedModulePM, allocationFn);
    nestedModulePM.addPass(createPromoteBuffersToStackPass(1 << 10, 64, 10));
  } else {
    // Distribute linalg op among a 3d grid of parallel threads. Tile each
    // workgroup thread memory then vectorize the linalg op.
    OpPassManager &nestedModulePM = passManager.nest<ModuleOp>();
    nestedModulePM.addPass(createInlinerPass());
    passManager.addPass(createLinalgTileAndDistributePass());
    // Propagates dynamic shapes computation on tensors.
    nestedModulePM.addNestedPass<FuncOp>(Shape::createTieDynamicShapesPass());
    nestedModulePM.addNestedPass<FuncOp>(
        Shape::createMaterializeShapeCalculationsPass());
    nestedModulePM.addNestedPass<FuncOp>(
        Shape::createHoistShapeCalculationsPass());
    nestedModulePM.addNestedPass<FuncOp>(createConvert1x1ConvToDotPass());
    nestedModulePM.addNestedPass<FuncOp>(createDecomposeHLOClampPass());
    addHLOToLinalgOnBuffersPasses(nestedModulePM);
  }
  // Linalg -> LLVM passes.
  addLinalgToLLVMPasses(passManager, options);
}

static PassPipelineRegistration<> linalgLLVMVPipeline(
    "iree-codegen-linalg-to-llvm-pipeline",
    "Runs the progressive lowering pipeline from Linalg to LLVM",
    [](OpPassManager &passManager) {
      buildLLVMTransformPassPipeline(passManager,
                                     getLLVMCodegenOptionsFromClOptions());
    });

static PassPipelineRegistration<> hloToLinalgLLVMVPipeline(
    "iree-codegen-hlo-to-llvm-pipeline",
    "Runs the progressive lowering pipeline from XLA HLO to Linalg to LLVM",
    [](OpPassManager &passManager) {
      buildLLVMTransformPassPipeline(passManager,
                                     getLLVMCodegenOptionsFromClOptions());
    });

}  // namespace iree_compiler
}  // namespace mlir
<|endoftext|>


<commit_before>/********************************************************************
* Description: cmsdiag.hh
*
*   Derived from a work by Fred Proctor & Will Shackleford
*
* Author:
* License: LGPL Version 2
* System: Linux
*
* Copyright (c) 2004 All rights reserved.
*
* Last change:
********************************************************************/

#ifndef CMSDIAG_HH
#define CMSDIAG_HH

#include "cms.hh"
class LinkedList;

class CMS_DIAG_STATIC_PROC_INFO {
  public:
    char name[16];		// process name
    char host_sysinfo[32];
    long pid;			/* Process, Thread or Task Id. */
    double rcslib_ver;		/* Version of the rcslib used by this
				   component. */
};

class CMS_DIAG_PROC_INFO:public CMS_DIAG_STATIC_PROC_INFO {
  public:
    CMS_INTERNAL_ACCESS_TYPE access_type;	/* access type of last
						   operation */
    long msg_id;		/* id of the message written or at time of
				   read. */
    long msg_size;		/* size of the message written or at time of
				   read. */
    long msg_type;		/* id of the message written or at time of
				   read. */
    long number_of_accesses;
    long number_of_new_messages;
    double bytes_moved;
    double bytes_moved_across_socket;
    double last_access_time;
    double first_access_time;
    double max_difference;
    double min_difference;
};

class CMS_DIAG_HEADER {
  public:
    long last_writer;
    long last_reader;
};

class CMS_DIAGNOSTICS_INFO:public CMS_DIAG_HEADER {
  public:
    CMS_DIAGNOSTICS_INFO();
    virtual ~ CMS_DIAGNOSTICS_INFO();
    CMS_DIAG_PROC_INFO *last_writer_dpi;
    CMS_DIAG_PROC_INFO *last_reader_dpi;
    LinkedList *dpis;
};

extern double cmsdiag_timebias;
extern int cmsdiag_timebias_set;

#endif
<commit_msg>ensure derived class destructor is called<commit_after>/********************************************************************
* Description: cmsdiag.hh
*
*   Derived from a work by Fred Proctor & Will Shackleford
*
* Author:
* License: LGPL Version 2
* System: Linux
*
* Copyright (c) 2004 All rights reserved.
*
* Last change:
********************************************************************/

#ifndef CMSDIAG_HH
#define CMSDIAG_HH

#include "cms.hh"
class LinkedList;

class CMS_DIAG_STATIC_PROC_INFO {
  public:
    char name[16];		// process name
    char host_sysinfo[32];
    long pid;			/* Process, Thread or Task Id. */
    double rcslib_ver;		/* Version of the rcslib used by this
				   component. */
};

class CMS_DIAG_PROC_INFO:public CMS_DIAG_STATIC_PROC_INFO {
  public:
    CMS_INTERNAL_ACCESS_TYPE access_type;	/* access type of last
						   operation */
    long msg_id;		/* id of the message written or at time of
				   read. */
    long msg_size;		/* size of the message written or at time of
				   read. */
    long msg_type;		/* id of the message written or at time of
				   read. */
    long number_of_accesses;
    long number_of_new_messages;
    double bytes_moved;
    double bytes_moved_across_socket;
    double last_access_time;
    double first_access_time;
    double max_difference;
    double min_difference;
};

class CMS_DIAG_HEADER {
  public:
    virtual ~CMS_DIAG_HEADER() {}
    long last_writer;
    long last_reader;
};

class CMS_DIAGNOSTICS_INFO:public CMS_DIAG_HEADER {
  public:
    CMS_DIAGNOSTICS_INFO();
    virtual ~ CMS_DIAGNOSTICS_INFO();
    CMS_DIAG_PROC_INFO *last_writer_dpi;
    CMS_DIAG_PROC_INFO *last_reader_dpi;
    LinkedList *dpis;
};

extern double cmsdiag_timebias;
extern int cmsdiag_timebias_set;

#endif
<|endoftext|>


<commit_before>/*************************************************
* X.509 CRL Source File                          *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/x509_crl.h>
#include <botan/x509_ext.h>
#include <botan/ber_dec.h>
#include <botan/parsing.h>
#include <botan/bigint.h>
#include <botan/config.h>
#include <botan/oids.h>

namespace Botan {

/*************************************************
* Load a X.509 CRL                               *
*************************************************/
X509_CRL::X509_CRL(DataSource& in) : X509_Object(in, "X509 CRL/CRL")
   {
   do_decode();
   }

/*************************************************
* Load a X.509 CRL                               *
*************************************************/
X509_CRL::X509_CRL(const std::string& in) : X509_Object(in, "CRL/X509 CRL")
   {
   do_decode();
   }

/*************************************************
* Decode the TBSCertList data                    *
*************************************************/
void X509_CRL::force_decode()
   {
   BER_Decoder tbs_crl(tbs_bits);

   u32bit version;
   tbs_crl.decode_optional(version, INTEGER, UNIVERSAL);

   if(version != 0 && version != 1)
      throw X509_CRL_Error("Unknown X.509 CRL version " +
                           to_string(version+1));

   AlgorithmIdentifier sig_algo_inner;
   tbs_crl.decode(sig_algo_inner);

   if(sig_algo != sig_algo_inner)
      throw X509_CRL_Error("Algorithm identifier mismatch");

   X509_DN dn_issuer;
   X509_Time start, end;

   tbs_crl.decode(dn_issuer);
   tbs_crl.decode(start);
   tbs_crl.decode(end);

   info.add(dn_issuer.contents());
   info.add("X509.CRL.start", start.readable_string());
   info.add("X509.CRL.end", end.readable_string());

   BER_Object next = tbs_crl.get_next_object();

   if(next.type_tag == SEQUENCE && next.class_tag == CONSTRUCTED)
      {
      BER_Decoder cert_list(next.value);

      while(cert_list.more_items())
         {
         CRL_Entry entry;
         cert_list.decode(entry);
         revoked.push_back(entry);
         }
      next = tbs_crl.get_next_object();
      }

   if(next.type_tag == 0 &&
      next.class_tag == ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))
      {
      BER_Decoder crl_options(next.value);

      std::string action = global_config().option("x509/crl/unknown_critical");
      if(action != "throw" && action != "ignore")
         throw Invalid_Argument("Bad value of x509/crl/unknown_critical: "
                                + action);

      Extensions extensions(action == "throw");

      crl_options.decode(extensions).verify_end();

      extensions.contents_to(info, info);

      next = tbs_crl.get_next_object();
      }

   if(next.type_tag != NO_OBJECT)
      throw X509_CRL_Error("Unknown tag in CRL");

   tbs_crl.verify_end();
   }

/*************************************************
* Return the list of revoked certificates        *
*************************************************/
std::vector<CRL_Entry> X509_CRL::get_revoked() const
   {
   return revoked;
   }

/*************************************************
* Return the distinguished name of the issuer    *
*************************************************/
X509_DN X509_CRL::issuer_dn() const
   {
   return create_dn(info);
   }

/*************************************************
* Return the key identifier of the issuer        *
*************************************************/
MemoryVector<byte> X509_CRL::authority_key_id() const
   {
   return info.get1_memvec("X509v3.AuthorityKeyIdentifier");
   }

/*************************************************
* Return the CRL number of this CRL              *
*************************************************/
u32bit X509_CRL::crl_number() const
   {
   return info.get1_u32bit("X509v3.CRLNumber");
   }

/*************************************************
* Return the issue data of the CRL               *
*************************************************/
X509_Time X509_CRL::this_update() const
   {
   return info.get1("X509.CRL.start");
   }

/*************************************************
* Return the date when a new CRL will be issued  *
*************************************************/
X509_Time X509_CRL::next_update() const
   {
   return info.get1("X509.CRL.end");
   }

}
<commit_msg>Improve readability slightly in the code handling CRL decoding.<commit_after>/*************************************************
* X.509 CRL Source File                          *
* (C) 1999-2007 The Botan Project                *
*************************************************/

#include <botan/x509_crl.h>
#include <botan/x509_ext.h>
#include <botan/ber_dec.h>
#include <botan/parsing.h>
#include <botan/bigint.h>
#include <botan/config.h>
#include <botan/oids.h>

namespace Botan {

/*************************************************
* Load a X.509 CRL                               *
*************************************************/
X509_CRL::X509_CRL(DataSource& in) : X509_Object(in, "X509 CRL/CRL")
   {
   do_decode();
   }

/*************************************************
* Load a X.509 CRL                               *
*************************************************/
X509_CRL::X509_CRL(const std::string& in) : X509_Object(in, "CRL/X509 CRL")
   {
   do_decode();
   }

/*************************************************
* Decode the TBSCertList data                    *
*************************************************/
void X509_CRL::force_decode()
   {
   BER_Decoder tbs_crl(tbs_bits);

   u32bit version;
   tbs_crl.decode_optional(version, INTEGER, UNIVERSAL);

   if(version != 0 && version != 1)
      throw X509_CRL_Error("Unknown X.509 CRL version " +
                           to_string(version+1));

   AlgorithmIdentifier sig_algo_inner;
   tbs_crl.decode(sig_algo_inner);

   if(sig_algo != sig_algo_inner)
      throw X509_CRL_Error("Algorithm identifier mismatch");

   X509_DN dn_issuer;
   tbs_crl.decode(dn_issuer);
   info.add(dn_issuer.contents());

   X509_Time start, end;
   tbs_crl.decode(start).decode(end);
   info.add("X509.CRL.start", start.readable_string());
   info.add("X509.CRL.end", end.readable_string());

   BER_Object next = tbs_crl.get_next_object();

   if(next.type_tag == SEQUENCE && next.class_tag == CONSTRUCTED)
      {
      BER_Decoder cert_list(next.value);

      while(cert_list.more_items())
         {
         CRL_Entry entry;
         cert_list.decode(entry);
         revoked.push_back(entry);
         }
      next = tbs_crl.get_next_object();
      }

   if(next.type_tag == 0 &&
      next.class_tag == ASN1_Tag(CONSTRUCTED | CONTEXT_SPECIFIC))
      {
      BER_Decoder crl_options(next.value);

      std::string action = global_config().option("x509/crl/unknown_critical");
      if(action != "throw" && action != "ignore")
         throw Invalid_Argument("Bad value of x509/crl/unknown_critical: "
                                + action);

      Extensions extensions(action == "throw");

      crl_options.decode(extensions).verify_end();

      extensions.contents_to(info, info);

      next = tbs_crl.get_next_object();
      }

   if(next.type_tag != NO_OBJECT)
      throw X509_CRL_Error("Unknown tag in CRL");

   tbs_crl.verify_end();
   }

/*************************************************
* Return the list of revoked certificates        *
*************************************************/
std::vector<CRL_Entry> X509_CRL::get_revoked() const
   {
   return revoked;
   }

/*************************************************
* Return the distinguished name of the issuer    *
*************************************************/
X509_DN X509_CRL::issuer_dn() const
   {
   return create_dn(info);
   }

/*************************************************
* Return the key identifier of the issuer        *
*************************************************/
MemoryVector<byte> X509_CRL::authority_key_id() const
   {
   return info.get1_memvec("X509v3.AuthorityKeyIdentifier");
   }

/*************************************************
* Return the CRL number of this CRL              *
*************************************************/
u32bit X509_CRL::crl_number() const
   {
   return info.get1_u32bit("X509v3.CRLNumber");
   }

/*************************************************
* Return the issue data of the CRL               *
*************************************************/
X509_Time X509_CRL::this_update() const
   {
   return info.get1("X509.CRL.start");
   }

/*************************************************
* Return the date when a new CRL will be issued  *
*************************************************/
X509_Time X509_CRL::next_update() const
   {
   return info.get1("X509.CRL.end");
   }

}
<|endoftext|>