[InstSimplify] Fold trunc([zs]ext(%V)) -> %V

Truncates can completely cancel out a zext or sext instruction.

llvm-svn: 276604
diff --git a/llvm/lib/Analysis/InstructionSimplify.cpp b/llvm/lib/Analysis/InstructionSimplify.cpp
index c7e1724..981fb97 100644
--- a/llvm/lib/Analysis/InstructionSimplify.cpp
+++ b/llvm/lib/Analysis/InstructionSimplify.cpp
@@ -3790,9 +3790,15 @@
 }
 
 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
-  if (Constant *C = dyn_cast<Constant>(Op))
+  if (auto *C = dyn_cast<Constant>(Op))
     return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
 
+  // trunc([zs]ext(x)) -> x if the trunc undoes the work of the [zs]ext.
+  if (auto *CI = dyn_cast<CastInst>(Op))
+    if (isa<ZExtInst>(CI) || isa<SExtInst>(CI))
+      if (CI->getOperand(0)->getType() == Ty)
+        return CI->getOperand(0);
+
   return nullptr;
 }