]> granicus.if.org Git - clang/commitdiff
Patch to optimize away copy constructor call when
authorFariborz Jahanian <fjahanian@apple.com>
Thu, 6 Aug 2009 01:02:49 +0000 (01:02 +0000)
committerFariborz Jahanian <fjahanian@apple.com>
Thu, 6 Aug 2009 01:02:49 +0000 (01:02 +0000)
appropriate.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@78267 91177308-0d34-0410-b5e6-96231b3b80d8

lib/CodeGen/CGCXX.cpp
test/CodeGenCXX/copy-constructor-elim.cpp [new file with mode: 0644]

index 5324cc622f733dbd81174b242da705aced3bd5f7..0f76266acc2964c79c3b518479e4f85e325ddfe0 100644 (file)
@@ -255,7 +255,20 @@ CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest,
   cast<CXXRecordDecl>(E->getType()->getAs<RecordType>()->getDecl());
   if (RD->hasTrivialConstructor())
     return;
-  
+
+  // Code gen optimization to eliminate copy constructor and return 
+  // its first argument instead.
+  const CXXConstructorDecl *CDecl = E->getConstructor();
+  if (E->getNumArgs() == 1 &&
+      CDecl->isCopyConstructor(getContext())) {
+    CXXConstructExpr::const_arg_iterator i = E->arg_begin();
+    const Expr *SubExpr = (*i);
+    // FIXME. Any other cases can be optimized away?
+    if (isa<CallExpr>(SubExpr) || isa<CXXTemporaryObjectExpr>(SubExpr)) {
+      EmitAggExpr(SubExpr, Dest, false);
+      return;
+    }
+  }
   // Call the constructor.
   EmitCXXConstructorCall(E->getConstructor(), Ctor_Complete, Dest, 
                          E->arg_begin(), E->arg_end());
diff --git a/test/CodeGenCXX/copy-constructor-elim.cpp b/test/CodeGenCXX/copy-constructor-elim.cpp
new file mode 100644 (file)
index 0000000..5a1109d
--- /dev/null
@@ -0,0 +1,31 @@
+// RUN: clang-cc -emit-llvm -o %t %s &&
+// RUN: grep "_ZN1CC1ERK1C" %t | count 0
+
+extern "C" int printf(...);
+
+
+struct C {
+       C() : iC(6) {printf("C()\n"); }
+       C(const C& c) { printf("C(const C& c)\n"); }
+       int iC;
+};
+
+C foo() {
+  return C();
+};
+
+class X { // ...
+public: 
+       X(int) {}
+       X(const X&, int i = 1, int j = 2, C c = foo()) {
+               printf("X(const X&, %d, %d, %d)\n", i, j, c.iC);
+       }
+};
+
+int main()
+{
+       X a(1);
+       X b(a, 2);
+       X c = b;
+       X d(a, 5, 6);
+}