Hi revane, arielbernal, tareqsiraj,
Unlike the other transform this one is a library since recent changes in the
core allow this. Let me know if it was a bad idea.
The story: https://cpp11-migrate.atlassian.net/browse/CM-55
Note that this transform use the proposed IncludeDirectives class from
http://llvm-reviews.chandlerc.com/D1287
http://llvm-reviews.chandlerc.com/D1342
Files:
cpp11-migrate/CMakeLists.txt
cpp11-migrate/Makefile
cpp11-migrate/PassByValue/CMakeLists.txt
cpp11-migrate/PassByValue/Makefile
cpp11-migrate/PassByValue/PassByValue.cpp
cpp11-migrate/PassByValue/PassByValue.h
cpp11-migrate/PassByValue/PassByValueActions.cpp
cpp11-migrate/PassByValue/PassByValueActions.h
cpp11-migrate/PassByValue/PassByValueMatchers.cpp
cpp11-migrate/PassByValue/PassByValueMatchers.h
cpp11-migrate/tool/CMakeLists.txt
cpp11-migrate/tool/Cpp11Migrate.cpp
cpp11-migrate/tool/Makefile
docs/MigratorUsage.rst
docs/PassByValueTransform.rst
docs/cpp11-migrate.rst
test/cpp11-migrate/PassByValue/basic.cpp
test/cpp11-migrate/PassByValue/basic.h
Index: cpp11-migrate/CMakeLists.txt
===================================================================
--- cpp11-migrate/CMakeLists.txt
+++ cpp11-migrate/CMakeLists.txt
@@ -1,4 +1,7 @@
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
-add_subdirectory(tool)
+# Transforms
+add_subdirectory(PassByValue)
+
add_subdirectory(Core)
+add_subdirectory(tool)
Index: cpp11-migrate/Makefile
===================================================================
--- cpp11-migrate/Makefile
+++ cpp11-migrate/Makefile
@@ -10,6 +10,6 @@
CLANG_LEVEL := ../../..
include $(CLANG_LEVEL)/../../Makefile.config
-DIRS = Core tool
+DIRS = Core tool PassByValue
include $(CLANG_LEVEL)/Makefile
Index: cpp11-migrate/PassByValue/CMakeLists.txt
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/CMakeLists.txt
@@ -0,0 +1,11 @@
+set(LLVM_LINK_COMPONENTS support)
+
+add_clang_library(migratePassByValueTransform
+ PassByValue.cpp
+ PassByValueActions.cpp
+ PassByValueMatchers.cpp
+ )
+
+target_link_libraries(migratePassByValueTransform
+ migrateCore
+ )
Index: cpp11-migrate/PassByValue/Makefile
===================================================================
--- cpp11-migrate/PassByValue/Makefile
+++ cpp11-migrate/PassByValue/Makefile
@@ -1,15 +1,13 @@
-##===- tools/extra/loop-convert/Makefile ----sssss----------*- Makefile -*-===##
+##===- cpp11-migrate/PassByValue/Makefile ------------------*- Makefile -*-===##
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
-CLANG_LEVEL := ../../..
-include $(CLANG_LEVEL)/../../Makefile.config
-
-DIRS = Core tool
+CLANG_LEVEL := ../../../..
+LIBRARYNAME := migratePassByValueTransform
include $(CLANG_LEVEL)/Makefile
Index: cpp11-migrate/PassByValue/PassByValue.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValue.cpp
@@ -0,0 +1,77 @@
+//===-- PassByValue.cpp ---------------------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file provides the implementation of the ReplaceAutoPtrTransform
+/// class.
+///
+//===----------------------------------------------------------------------===//
+
+#include "PassByValue.h"
+#include "PassByValueActions.h"
+#include "PassByValueMatchers.h"
+
+using namespace clang;
+using namespace clang::tooling;
+using namespace clang::ast_matchers;
+
+int PassByValueTransform::apply(
+ FileOverrides &InputStates, const tooling::CompilationDatabase &Database,
+ const std::vector<std::string> &SourcePaths) LLVM_OVERRIDE {
+ ClangTool Tool(Database, SourcePaths);
+ unsigned AcceptedChanges = 0;
+ MatchFinder Finder;
+ ConstructorParamReplacer Replacer(getReplacements(), AcceptedChanges,
+ /*Owner=*/ *this);
+
+ Finder.addMatcher(makePassByValueCtorParamMatcher(), &Replacer);
+
+ // make the replacer available to handleBeginSource()
+ this->Replacer = &Replacer;
+
+ setOverrides(InputStates);
+
+ if (Tool.run(createActionFactory(Finder))) {
+ llvm::errs() << "Error encountered during translation.\n";
+ return 1;
+ }
+
+ setAcceptedChanges(AcceptedChanges);
+ return 0;
+}
+
+bool PassByValueTransform::handleBeginSource(CompilerInstance &CI,
+ llvm::StringRef Filename) {
+ assert(Replacer && "Replacer not set");
+ IncludeManager.reset(new IncludeDirectives(CI));
+ Replacer->setIncludeDirectives(IncludeManager.get());
+ return Transform::handleBeginSource(CI, Filename);
+}
+
+struct PassByValueFactory : TransformFactory {
+ PassByValueFactory() {
+ // Based on the Replace Auto-Ptr Transform that is also using std::move().
+ Since.Clang = Version(3, 0);
+ Since.Gcc = Version(4, 6);
+ Since.Icc = Version(13);
+ Since.Msvc = Version(11);
+ }
+
+ Transform *createTransform(const TransformOptions &Opts) LLVM_OVERRIDE {
+ return new PassByValueTransform(Opts);
+ }
+};
+
+// Register the factory using this statically initialized variable.
+static TransformFactoryRegistry::Add<PassByValueFactory>
+X("pass-by-value", "Pass parameters by value where possible");
+
+// This anchor is used to force the linker to link in the generated object file
+// and thus register the factory.
+volatile int PassByValueTransformAnchorSource = 0;
Index: cpp11-migrate/PassByValue/PassByValue.h
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValue.h
@@ -0,0 +1,69 @@
+//===-- PassByValue.h -------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file provides the declaration of the PassByValueTransform
+/// class.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef CPP11_MIGRATE_PASS_BY_VALUE_H
+#define CPP11_MIGRATE_PASS_BY_VALUE_H
+
+#include "Core/Transform.h"
+#include "Core/IncludeDirectives.h"
+
+class ConstructorParamReplacer;
+
+/// \brief Subclass of Transform that uses pass-by-value semantic where
+/// applicable.
+///
+/// Passing parameters by value is interesting when the object is copied. It can
+/// avoids a temporary by moving the resource of the parameter.
+///
+/// For example, given:
+/// \code
+/// #include <string>
+///
+/// class A {
+/// std::string S;
+/// public:
+/// A(const std::string &S) : S(S) {}
+/// };
+/// \endcode
+/// the code is transformed to:
+/// \code
+/// #include <string>
+///
+/// class A {
+/// std::string S;
+/// public:
+/// A(std::string S) : S(std::move(S)) {}
+/// };
+/// \endcode
+class PassByValueTransform : public Transform {
+public:
+ PassByValueTransform(const TransformOptions &Options)
+ : Transform("PassByValue", Options), Replacer(0) {}
+
+ /// \see Transform::apply().
+ virtual int apply(FileOverrides &InputStates,
+ const clang::tooling::CompilationDatabase &Database,
+ const std::vector<std::string> &SourcePaths) LLVM_OVERRIDE;
+
+private:
+ /// \brief Setups the \c IncludeDirectives for the replacer.
+ virtual bool handleBeginSource(clang::CompilerInstance &CI,
+ llvm::StringRef Filename) LLVM_OVERRIDE;
+
+ llvm::OwningPtr<IncludeDirectives> IncludeManager;
+ ConstructorParamReplacer *Replacer;
+};
+
+#endif // CPP11_MIGRATE_PASS_BY_VALUE_H
Index: cpp11-migrate/PassByValue/PassByValueActions.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValueActions.cpp
@@ -0,0 +1,160 @@
+//===-- PassByValueActions.cpp --------------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file contains the definition of the ASTMatcher callback for the
+/// PassByValue transform.
+///
+//===----------------------------------------------------------------------===//
+
+#include "PassByValueActions.h"
+#include "PassByValueMatchers.h"
+#include "Core/IncludeDirectives.h"
+#include "Core/Transform.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang;
+using namespace clang::tooling;
+using namespace clang::ast_matchers;
+
+namespace {
+/// \brief \c clang::RecursiveASTVisitor that checks that the given
+/// \c ParmVarDecl is used exactly one time.
+///
+/// \see ExactlyOneUsageVisitor::hasExactlyOneUsageIn()
+class ExactlyOneUsageVisitor
+ : public RecursiveASTVisitor<ExactlyOneUsageVisitor> {
+ friend class RecursiveASTVisitor<ExactlyOneUsageVisitor>;
+
+public:
+ ExactlyOneUsageVisitor(const ParmVarDecl *ParamDecl) : ParamDecl(ParamDecl) {}
+
+ /// \brief Whether or not the parameter variable is referred only once in the
+ /// given constructor.
+ bool hasExactlyOneUsageIn(const CXXConstructorDecl *Ctor) {
+ Count = 0;
+ TraverseDecl(const_cast<CXXConstructorDecl *>(Ctor));
+ return Count == 1;
+ }
+
+private:
+ /// \brief Counts the number of references to a variable.
+ ///
+ /// Stops the AST traversal if more than one usage is found.
+ bool VisitDeclRefExpr(DeclRefExpr *D) {
+ if (const ParmVarDecl *To = llvm::dyn_cast<ParmVarDecl>(D->getDecl()))
+ if (To == ParamDecl) {
+ Count++;
+ if (Count > 1)
+ // no need to look further, used more than once
+ return false;
+ }
+ return true;
+ }
+
+ const ParmVarDecl *ParamDecl;
+ unsigned Count;
+};
+} // end anonymous namespace
+
+/// \brief Whether or not \p ParamDecl is used exactly one time in \p Ctor.
+///
+/// Checks both in the init-list and the body of the constructor.
+static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor,
+ const ParmVarDecl *ParamDecl) {
+ ExactlyOneUsageVisitor Visitor(ParamDecl);
+ return Visitor.hasExactlyOneUsageIn(Ctor);
+}
+
+/// \brief Find all references to \p ParmVarDecls accross all of the
+/// constructors redeclarations.
+static void
+collectParamDecls(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl,
+ llvm::SmallVectorImpl<const ParmVarDecl *> &Results) {
+ unsigned ParamIdx = ParamDecl->getFunctionScopeIndex();
+
+ for (CXXConstructorDecl::redecl_iterator I = Ctor->redecls_begin(),
+ E = Ctor->redecls_end();
+ I != E; ++I)
+ Results.push_back((*I)->getParamDecl(ParamIdx));
+}
+
+void ConstructorParamReplacer::run(const MatchFinder::MatchResult &Result) {
+ assert(IncludeManager && "Include directives manager not set.");
+ SourceManager &SM = *Result.SourceManager;
+ const CXXConstructorDecl *Ctor =
+ Result.Nodes.getNodeAs<CXXConstructorDecl>(PassByValueCtorId);
+ const ParmVarDecl *ParamDecl =
+ Result.Nodes.getNodeAs<ParmVarDecl>(PassByValueParamId);
+ const CXXCtorInitializer *Initializer =
+ Result.Nodes.getNodeAs<CXXCtorInitializer>(PassByValueInitializerId);
+ assert(Ctor && ParamDecl && Initializer && "Bad Callback, missing node.");
+
+ // Check this now to avoid unecessary work. The param locations are checked
+ // later.
+ if (!Owner.isFileModifiable(SM, Initializer->getSourceLocation()))
+ return;
+
+ // The parameter will be in an unspecified state after the move, so check if
+ // the parameter is used for anything else other than the copy. If so do not
+ // apply any changes.
+ if (!paramReferredExactlyOnce(Ctor, ParamDecl))
+ return;
+
+ llvm::SmallVector<const ParmVarDecl *, 2> AllParamDecls;
+ collectParamDecls(Ctor, ParamDecl, AllParamDecls);
+
+ // Generate all replacements for the params. If it's impossible to change one
+ // of the parameter (e.g: comes from an unmodifiable header) no transformation
+ // is applied.
+ llvm::SmallVector<Replacement, 2> ParamReplaces(AllParamDecls.size());
+ for (unsigned I = 0, E = AllParamDecls.size(); I != E; ++I) {
+ TypeLoc ConstRefTL = AllParamDecls[I]->getTypeSourceInfo()->getTypeLoc();
+ SourceRange Range(AllParamDecls[I]->getLocStart(), ConstRefTL.getLocEnd());
+ CharSourceRange CharRange = Lexer::makeFileCharRange(
+ CharSourceRange::getTokenRange(Range), SM, LangOptions());
+ TypeLoc ValueTypeLoc = ConstRefTL.getNextTypeLoc();
+ assert(!ValueTypeLoc.isNull() &&
+ "invalid typeloc, ConstRefTL is not a const-ref");
+ llvm::SmallString<32> ValueStr = Lexer::getSourceText(
+ CharSourceRange::getTokenRange(ValueTypeLoc.getSourceRange()), SM,
+ LangOptions());
+
+ if (CharRange.isInvalid() || ValueStr.empty() ||
+ !Owner.isFileModifiable(SM, CharRange.getBegin()))
+ return;
+
+ // 'const Foo ¶m' -> 'Foo param'
+ // ~~~~~~~~~~~ ~~~^
+ ValueStr += ' ';
+ ParamReplaces[I] = Replacement(SM, CharRange, ValueStr);
+ }
+
+ // if needed, include <utility> in the file that uses std::move()
+ const FileEntry *STDMoveFile =
+ SM.getFileEntryForID(SM.getFileID(Initializer->getLParenLoc()));
+ const tooling::Replacement &IncludeReplace =
+ IncludeManager->addAngledInclude(STDMoveFile, "utility");
+ if (IncludeReplace.isApplicable()) {
+ Replaces.insert(IncludeReplace);
+ AcceptedChanges++;
+ }
+
+ // const-ref params becomes values (const Foo & -> Foo)
+ Replaces.insert(ParamReplaces.begin(), ParamReplaces.end());
+ AcceptedChanges += ParamReplaces.size();
+
+ // move the value in the init-list
+ Replaces.insert(Replacement(
+ SM, Initializer->getLParenLoc().getLocWithOffset(1), 0, "std::move("));
+ Replaces.insert(Replacement(SM, Initializer->getRParenLoc(), 0, ")"));
+ AcceptedChanges += 2;
+}
Index: cpp11-migrate/PassByValue/PassByValueActions.h
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValueActions.h
@@ -0,0 +1,74 @@
+//===-- PassByValueActions.h ------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file contains the declaration of the ASTMatcher callback for the
+/// PassByValue transform.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef CPP11_MIGRATE_PASS_BY_VALUE_ACTIONS_H
+#define CPP11_MIGRATE_PASS_BY_VALUE_ACTIONS_H
+
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/Refactoring.h"
+
+class Transform;
+class IncludeDirectives;
+
+/// \brief Callback that replaces const-ref parameters in constructors to use
+/// pass-by-value semantic where applicable.
+///
+/// Modifications done by the callback:
+/// - \#include \<utility\> is added if necessary for the definition of
+/// \c std::move() to be available.
+/// - The parameter type is changed from const-ref to value-type.
+/// - In the init-list the parameter is moved.
+///
+/// Example:
+/// \code
+/// + #include <utility>
+///
+/// class Foo(const std::string &S) {
+/// public:
+/// - Foo(const std::string &S) : S(S) {}
+/// + Foo(std::string S) : S(std::move(S)) {}
+///
+/// private:
+/// std::string S;
+/// };
+/// \endcode
+///
+/// \note Since an include may be added by this matcher it's necessary to call
+/// \c setIncludeDirectives() with an up-to-date \c IncludeDirectives. This is
+/// typically done by overloading \c Transform::handleBeginSource().
+class ConstructorParamReplacer
+ : public clang::ast_matchers::MatchFinder::MatchCallback {
+public:
+ ConstructorParamReplacer(clang::tooling::Replacements &Replaces,
+ unsigned &AcceptedChanges, const Transform &Owner)
+ : Replaces(Replaces), AcceptedChanges(AcceptedChanges), Owner(Owner),
+ IncludeManager(0) {}
+
+ void setIncludeDirectives(IncludeDirectives *Includes) {
+ IncludeManager = Includes;
+ }
+
+private:
+ /// \brief Entry point to the callback called when matches are made.
+ virtual void run(const clang::ast_matchers::MatchFinder::MatchResult &Result)
+ LLVM_OVERRIDE;
+
+ clang::tooling::Replacements &Replaces;
+ unsigned &AcceptedChanges;
+ const Transform &Owner;
+ IncludeDirectives *IncludeManager;
+};
+
+#endif // CPP11_MIGRATE_PASS_BY_VALUE_ACTIONS_H
Index: cpp11-migrate/PassByValue/PassByValueMatchers.cpp
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValueMatchers.cpp
@@ -0,0 +1,76 @@
+//===-- PassByValueMatchers.cpp -------------------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file contains the definitions for matcher-generating functions
+/// and names for bound nodes found by AST matchers.
+///
+//===----------------------------------------------------------------------===//
+
+#include "PassByValueMatchers.h"
+
+const char *PassByValueCtorId = "Ctor";
+const char *PassByValueParamId = "Param";
+const char *PassByValueInitializerId = "Initializer";
+
+namespace clang {
+namespace ast_matchers {
+
+/// \brief Matches move constructible classes.
+///
+/// Given
+/// \code
+/// // POD types are trivially move constructible
+/// struct Foo { int a; };
+///
+/// struct Bar {
+/// Bar(Bar &&) = deleted;
+/// int a;
+/// };
+/// \endcode
+/// recordDecl(isMoveConstructible())
+/// matches "Foo".
+AST_MATCHER(CXXRecordDecl, isMoveConstructible) {
+ for (CXXRecordDecl::ctor_iterator I = Node.ctor_begin(), E = Node.ctor_end(); I != E; ++I) {
+ const CXXConstructorDecl *Ctor = *I;
+ if (Ctor->isMoveConstructor() && !Ctor->isDeleted())
+ return true;
+ }
+ return false;
+}
+
+/// \brief Matches non-deleted copy constructors.
+///
+/// Given
+/// \code
+/// struct Foo { Foo(const Foo &) = default; };
+/// struct Bar { Bar(const Bar &) = deleted; };
+/// \endcode
+/// constructorDecl(isNonDeletedCopyConstructor())
+/// matches "Foo(const Foo &)".
+AST_MATCHER(CXXConstructorDecl, isNonDeletedCopyConstructor) {
+ return Node.isCopyConstructor() && !Node.isDeleted();
+}
+} // namespace ast_matchers
+} // namespace clang
+
+using namespace clang;
+using namespace clang::ast_matchers;
+
+DeclarationMatcher makePassByValueCtorParamMatcher() {
+ return constructorDecl(
+ forEachConstructorInitializer(ctorInitializer(
+ withInitializer(constructExpr(
+ has(declRefExpr(to(parmVarDecl().bind(PassByValueParamId)))),
+ hasDeclaration(constructorDecl(
+ isNonDeletedCopyConstructor(),
+ hasDeclContext(recordDecl(isMoveConstructible())))))))
+ .bind(PassByValueInitializerId)))
+ .bind(PassByValueCtorId);
+}
Index: cpp11-migrate/PassByValue/PassByValueMatchers.h
===================================================================
--- /dev/null
+++ cpp11-migrate/PassByValue/PassByValueMatchers.h
@@ -0,0 +1,44 @@
+//===-- PassByValueMatchers.h -----------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file contains the declarations for matcher-generating functions
+/// and names for bound nodes found by AST matchers.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef CPP11_MIGRATE_REPLACE_AUTO_PTR_MATCHERS_H
+#define CPP11_MIGRATE_REPLACE_AUTO_PTR_MATCHERS_H
+
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+/// \name Names to bind with matched expressions
+/// @{
+extern const char *PassByValueCtorId;
+extern const char *PassByValueParamId;
+extern const char *PassByValueInitializerId;
+/// @}
+
+/// \brief Creates a matcher that finds class field initializations that can
+/// benefit from using the move constructor.
+///
+/// \code
+/// class A {
+/// public:
+/// A(const std::string &S) : S(S) {}
+/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PassByValueCtorId
+/// ~~~~~~~~~~~~~~~~~~~~ PassByValueParamId
+/// ~ PassByValueInitializerId
+/// private:
+/// std::string S;
+/// };
+/// \endcode
+clang::ast_matchers::DeclarationMatcher makePassByValueCtorParamMatcher();
+
+#endif // CPP11_MIGRATE_REPLACE_AUTO_PTR_MATCHERS_H
Index: cpp11-migrate/tool/CMakeLists.txt
===================================================================
--- cpp11-migrate/tool/CMakeLists.txt
+++ cpp11-migrate/tool/CMakeLists.txt
@@ -32,6 +32,7 @@
target_link_libraries(cpp11-migrate
migrateCore
+ migratePassByValueTransform
)
install(TARGETS cpp11-migrate
Index: cpp11-migrate/tool/Cpp11Migrate.cpp
===================================================================
--- cpp11-migrate/tool/Cpp11Migrate.cpp
+++ cpp11-migrate/tool/Cpp11Migrate.cpp
@@ -350,13 +350,15 @@
// These anchors are used to force the linker to link the transforms
extern volatile int AddOverrideTransformAnchorSource;
extern volatile int LoopConvertTransformAnchorSource;
+extern volatile int PassByValueTransformAnchorSource;
extern volatile int ReplaceAutoPtrTransformAnchorSource;
extern volatile int UseAutoTransformAnchorSource;
extern volatile int UseNullptrTransformAnchorSource;
static int TransformsAnchorsDestination[] = {
AddOverrideTransformAnchorSource,
LoopConvertTransformAnchorSource,
+ PassByValueTransformAnchorSource,
ReplaceAutoPtrTransformAnchorSource,
UseAutoTransformAnchorSource,
UseNullptrTransformAnchorSource
Index: cpp11-migrate/tool/Makefile
===================================================================
--- cpp11-migrate/tool/Makefile
+++ cpp11-migrate/tool/Makefile
@@ -37,7 +37,8 @@
USEDLIBS = migrateCore.a clangFormat.a clangTooling.a clangFrontend.a \
clangSerialization.a clangDriver.a clangRewriteFrontend.a \
clangRewriteCore.a clangParse.a clangSema.a clangAnalysis.a \
- clangAST.a clangASTMatchers.a clangEdit.a clangLex.a clangBasic.a
+ clangAST.a clangASTMatchers.a clangEdit.a clangLex.a clangBasic.a \
+ migratePassByValueTransform.a
include $(CLANG_LEVEL)/Makefile
Index: docs/MigratorUsage.rst
===================================================================
--- docs/MigratorUsage.rst
+++ docs/MigratorUsage.rst
@@ -137,6 +137,7 @@
=============== ===== === ==== ====
AddOverride (1) 3.0 4.7 14 8
LoopConvert 3.0 4.6 13 11
+ PassByValue 3.0 4.6 13 11
ReplaceAutoPtr 3.0 4.6 13 11
UseAuto 2.9 4.4 12 10
UseNullptr 3.0 4.6 12.1 10
@@ -222,6 +223,12 @@
projects that use such macros to maintain build compatibility with non-C++11
code.
+.. option:: -pass-by-value
+
+ Replace const-reference parameters by values in situations where it can be
+ beneficial.
+ See :doc:`PassByValueTransform`.
+
.. option:: -replace-auto_ptr
Replace ``std::auto_ptr`` (deprecated in C++11) by ``std::unique_ptr`` and
Index: docs/PassByValueTransform.rst
===================================================================
--- /dev/null
+++ docs/PassByValueTransform.rst
@@ -0,0 +1,67 @@
+.. index:: Pass-By-Value Transform
+
+=======================
+Pass-By-Value Transform
+=======================
+
+The Pass-By-Value Transform replaces the uses of const-references constructor
+parameters that are copied into class fields by values. The value parameter is
+then moved into the class field.
+
+Migration example (note that `std::string` is move constructible):
+
+.. code-block:: c++
+
+ #include <string>
+
+ class Foo {
+ public:
+ - Foo(const std::string &Copied, const std::string &ReadOnly)
+ - : Copied(Copied), ReadOnly(ReadOnly)
+ + Foo(std::string Copied, const std::string &ReadOnly)
+ + : Copied(std::move(Copied)), ReadOnly(ReadOnly)
+ {}
+
+ private:
+ std::string Copied;
+ const std::string &ReadOnly;
+ };
+
+ std::string get_cwd();
+
+ void f(const std::string &Path) {
+ // get_cwd() returns an xvalue, by using pass-by-value in Foo constructor
+ // we managed to avoid a copy.
+ Foo foo(get_cwd(), Path);
+ }
+
+Note that since `std::move()` is a library function declared in `<utility>` it
+may be necessary to add this include. The transform will make the insertion as
+necessary.
+
+This transform won't do anything if the parameter is used more than once. Moved
+objects are in an undefined state. This mean code like this won't be
+transformed:
+
+.. code-block:: c++
+
+ #include <string>
+
+ void pass(const std::string &S);
+
+ class Foo {
+ public:
+ Foo(const std::string &S) : Str(S) {
+ pass(S);
+ }
+
+ private:
+ std::string Str;
+ };
+
+.. seealso::
+
+ For more information about this idiom, read: `Want Speed? Pass by Value`_.
+
+ .. _Want Speed? Pass by Value: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
+
Index: docs/cpp11-migrate.rst
===================================================================
--- docs/cpp11-migrate.rst
+++ docs/cpp11-migrate.rst
@@ -11,6 +11,7 @@
UseNullptrTransform
LoopConvertTransform
AddOverrideTransform
+ PassByValueTransform
ReplaceAutoPtrTransform
MigratorUsage
@@ -115,4 +116,6 @@
* :doc:`AddOverrideTransform`
+* :doc:`PassByValueTransform`
+
* :doc:`ReplaceAutoPtrTransform`
Index: test/cpp11-migrate/PassByValue/basic.cpp
===================================================================
--- /dev/null
+++ test/cpp11-migrate/PassByValue/basic.cpp
@@ -0,0 +1,101 @@
+// RUN: grep -Ev "// *[A-Z-]+:" %s > %t.cpp
+// RUN: cpp11-migrate -pass-by-value %t.cpp -- -std=c++11 -I %S
+// RUN: FileCheck -input-file=%t.cpp %s
+
+#include "basic.h"
+// CHECK: #include <utility>
+
+// Test that when the class declaration can't be modified we won't modify the
+// definition either.
+UnmodifiableClass::UnmodifiableClass(const Movable &M) : M(M) {}
+// CHECK: UnmodifiableClass::UnmodifiableClass(const Movable &M) : M(M) {}
+
+struct A {
+ A(const Movable &M) : M(M) {}
+ // CHECK: A(Movable M) : M(std::move(M)) {}
+ Movable M;
+};
+
+// Test that we aren't modifying other things than a parameter
+Movable GlobalObj;
+struct B {
+ B(const Movable &M) : M(GlobalObj) {}
+ // CHECK: B(const Movable &M) : M(GlobalObj) {}
+ Movable M;
+};
+
+// Test that a parameter with more than one reference to it won't be changed.
+struct C {
+ // Tests extra-reference in body
+ C(const Movable &M) : M(M) { this->i = M.a; }
+ // CHECK: C(const Movable &M) : M(M) { this->i = M.a; }
+
+ // Tests extra-reference in init-list
+ C(const Movable &M, int) : M(M), i(M.a) {}
+ // CHECK: C(const Movable &M, int) : M(M), i(M.a) {}
+ Movable M;
+ int i;
+};
+
+// Test that both declaration and definition are updated
+struct D {
+ D(const Movable &M);
+ // CHECK: D(Movable M);
+ Movable M;
+};
+D::D(const Movable &M) : M(M) {}
+// CHECK: D::D(Movable M) : M(std::move(M)) {}
+
+// Test with default parameter
+struct E {
+ E(const Movable &M = Movable()) : M(M) {}
+ // CHECK: E(Movable M = Movable()) : M(std::move(M)) {}
+ Movable M;
+};
+
+// Test with object that can't be moved
+struct F {
+ F(const NotMovable &NM) : NM(NM) {}
+ // CHECK: F(const NotMovable &NM) : NM(NM) {}
+ NotMovable NM;
+};
+
+// Test unnamed parameter in declaration
+struct G {
+ G(const Movable &);
+ // CHECK: G(Movable );
+ Movable M;
+};
+G::G(const Movable &M) : M(M) {}
+// CHECK: G::G(Movable M) : M(std::move(M)) {}
+
+// Test parameter with and without qualifier
+namespace ns_H {
+typedef ::Movable HMovable;
+}
+struct H {
+ H(const ns_H::HMovable &M);
+ // CHECK: H(ns_H::HMovable M);
+ ns_H::HMovable M;
+};
+using namespace ns_H;
+H::H(const HMovable &M) : M(M) {}
+// CHECK: H(HMovable M) : M(std::move(M)) {}
+
+// Try messing up with macros
+#define MOVABLE_PARAM(Name) const Movable & Name
+struct I {
+ I(MOVABLE_PARAM(M)) : M(M) {}
+ // CHECK: I(MOVABLE_PARAM(M)) : M(M) {}
+ Movable M;
+};
+#undef MOVABLE_PARAM
+
+// Test that templates aren't modified
+template <typename T> struct J {
+ J(const T &M) : M(M) {}
+ // CHECK: J(const T &M) : M(M) {}
+ T M;
+};
+J<Movable> j1(Movable());
+J<NotMovable> j2(NotMovable());
Index: test/cpp11-migrate/PassByValue/basic.h
===================================================================
--- /dev/null
+++ test/cpp11-migrate/PassByValue/basic.h
@@ -0,0 +1,21 @@
+#ifndef BASIC_H
+#define BASIC_H
+
+// POD types are trivially move constructible
+struct Movable {
+ int a, b, c;
+};
+
+struct NotMovable {
+ NotMovable() = default;
+ NotMovable(const NotMovable &) = default;
+ NotMovable(NotMovable &&) = delete;
+ int a, b, c;
+};
+
+struct UnmodifiableClass {
+ UnmodifiableClass(const Movable &M);
+ Movable M;
+};
+
+#endif // BASIC_H
_______________________________________________
cfe-commits mailing list
[email protected]
http://lists.cs.uiuc.edu/mailman/listinfo/cfe-commits