[PATCH] D18230: [SimplifyLibCalls] Simplify strlen to a subtraction for certain cases

David Majnemer via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 16 17:08:51 PDT 2016


majnemer added a subscriber: majnemer.

================
Comment at: lib/Transforms/Utils/SimplifyLibCalls.cpp:538-558
@@ -537,1 +537,23 @@
 
+  // If s is a constant pointer pointing to a string literal, we can fold
+  // strlen(s + x) to strlen(s) - x, when x is known to be in the range 
+  // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
+  if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
+    if (GEP->getNumOperands() != 3)
+      return nullptr; 
+    
+    // We only try to simplify strlen when the pointer s points to an array 
+    // of i8. Otherwise, we would need to scale the offset x before doing the
+    // subtraction. This will make the optimization more complex, and it's not 
+    // very useful because calling strlen for a pointer of other types is 
+    // very uncommon.
+    PointerType *PT = cast<PointerType>(GEP->getOperand(0)->getType());
+    ArrayType *AT = dyn_cast<ArrayType>(PT->getElementType());
+    if (!AT || !AT->getElementType()->isIntegerTy(8))
+      return nullptr;
+
+    // First index should be 0.
+    const ConstantInt *FirstIdx = dyn_cast<ConstantInt>(GEP->getOperand(1));
+    if (!FirstIdx || !FirstIdx->isZero())
+      return nullptr;
+
----------------
Have you tried using something like `GetPointerBaseWithConstantOffset`?  You might be able to replace this code with that.


http://reviews.llvm.org/D18230





More information about the llvm-commits mailing list