Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1 | //===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass performs various transformations related to eliminating memcpy |
| 11 | // calls, or transforming sets of stores into memset's. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 15 | #include "llvm/ADT/DenseSet.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/iterator_range.h" |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/SmallVector.h" |
| 18 | #include "llvm/ADT/Statistic.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/STLExtras.h" |
| 20 | #include "llvm/Analysis/AssumptionCache.h" |
| 21 | #include "llvm/Analysis/GlobalsModRef.h" |
| 22 | #include "llvm/Analysis/MemoryDependenceAnalysis.h" |
| 23 | #include "llvm/Analysis/MemoryLocation.h" |
| 24 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Chris Lattner | 9cb1035 | 2010-12-26 20:15:01 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ValueTracking.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Argument.h" |
| 27 | #include "llvm/IR/Constants.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 28 | #include "llvm/IR/DataLayout.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 29 | #include "llvm/IR/DerivedTypes.h" |
| 30 | #include "llvm/IR/Dominators.h" |
| 31 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 32 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/GlobalVariable.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 34 | #include "llvm/IR/InstrTypes.h" |
| 35 | #include "llvm/IR/Instruction.h" |
| 36 | #include "llvm/IR/Instructions.h" |
| 37 | #include "llvm/IR/IntrinsicInst.h" |
| 38 | #include "llvm/IR/Intrinsics.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/IRBuilder.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 40 | #include "llvm/IR/LLVMContext.h" |
| 41 | #include "llvm/IR/Module.h" |
| 42 | #include "llvm/IR/Operator.h" |
| 43 | #include "llvm/IR/Type.h" |
| 44 | #include "llvm/IR/User.h" |
| 45 | #include "llvm/IR/Value.h" |
| 46 | #include "llvm/Pass.h" |
| 47 | #include "llvm/Support/Casting.h" |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 48 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 49 | #include "llvm/Support/MathExtras.h" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 50 | #include "llvm/Support/raw_ostream.h" |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/Scalar.h" |
| 52 | #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 53 | #include "llvm/Transforms/Utils/Local.h" |
Nick Lewycky | f836c89 | 2015-07-21 21:56:26 +0000 | [diff] [blame] | 54 | #include <algorithm> |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 55 | #include <cassert> |
| 56 | #include <cstdint> |
| 57 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 58 | using namespace llvm; |
| 59 | |
Chandler Carruth | 964daaa | 2014-04-22 02:55:47 +0000 | [diff] [blame] | 60 | #define DEBUG_TYPE "memcpyopt" |
| 61 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 62 | STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted"); |
| 63 | STATISTIC(NumMemSetInfer, "Number of memsets inferred"); |
Duncan Sands | 0edc710 | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 64 | STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy"); |
Benjamin Kramer | ea9152e | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 65 | STATISTIC(NumCpyToSet, "Number of memcpys converted to memset"); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 66 | |
Benjamin Kramer | 15a257d | 2012-09-13 16:29:49 +0000 | [diff] [blame] | 67 | static int64_t GetOffsetFromIndex(const GEPOperator *GEP, unsigned Idx, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 68 | bool &VariableIdxFound, |
| 69 | const DataLayout &DL) { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 70 | // Skip over the first indices. |
| 71 | gep_type_iterator GTI = gep_type_begin(GEP); |
| 72 | for (unsigned i = 1; i != Idx; ++i, ++GTI) |
| 73 | /*skip along*/; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 74 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 75 | // Compute the offset implied by the rest of the indices. |
| 76 | int64_t Offset = 0; |
| 77 | for (unsigned i = Idx, e = GEP->getNumOperands(); i != e; ++i, ++GTI) { |
| 78 | ConstantInt *OpC = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 79 | if (!OpC) |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 80 | return VariableIdxFound = true; |
| 81 | if (OpC->isZero()) continue; // No offset. |
| 82 | |
| 83 | // Handle struct indices, which add their field offset to the pointer. |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 84 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 85 | Offset += DL.getStructLayout(STy)->getElementOffset(OpC->getZExtValue()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 86 | continue; |
| 87 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 88 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 89 | // Otherwise, we have a sequential type like an array or vector. Multiply |
| 90 | // the index by the ElementSize. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 91 | uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 92 | Offset += Size*OpC->getSExtValue(); |
| 93 | } |
| 94 | |
| 95 | return Offset; |
| 96 | } |
| 97 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 98 | /// Return true if Ptr1 is provably equal to Ptr2 plus a constant offset, and |
| 99 | /// return that constant offset. For example, Ptr1 might be &A[42], and Ptr2 |
| 100 | /// might be &A[40]. In this case offset would be -8. |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 101 | static bool IsPointerOffset(Value *Ptr1, Value *Ptr2, int64_t &Offset, |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 102 | const DataLayout &DL) { |
Chris Lattner | fa7c29d | 2011-01-12 01:43:46 +0000 | [diff] [blame] | 103 | Ptr1 = Ptr1->stripPointerCasts(); |
| 104 | Ptr2 = Ptr2->stripPointerCasts(); |
Benjamin Kramer | 3ef5e46 | 2014-03-10 21:05:13 +0000 | [diff] [blame] | 105 | |
| 106 | // Handle the trivial case first. |
| 107 | if (Ptr1 == Ptr2) { |
| 108 | Offset = 0; |
| 109 | return true; |
| 110 | } |
| 111 | |
Benjamin Kramer | 15a257d | 2012-09-13 16:29:49 +0000 | [diff] [blame] | 112 | GEPOperator *GEP1 = dyn_cast<GEPOperator>(Ptr1); |
| 113 | GEPOperator *GEP2 = dyn_cast<GEPOperator>(Ptr2); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 114 | |
Chris Lattner | 5120ebf | 2011-01-08 21:07:56 +0000 | [diff] [blame] | 115 | bool VariableIdxFound = false; |
| 116 | |
| 117 | // If one pointer is a GEP and the other isn't, then see if the GEP is a |
| 118 | // constant offset from the base, as in "P" and "gep P, 1". |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 119 | if (GEP1 && !GEP2 && GEP1->getOperand(0)->stripPointerCasts() == Ptr2) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 120 | Offset = -GetOffsetFromIndex(GEP1, 1, VariableIdxFound, DL); |
Chris Lattner | 5120ebf | 2011-01-08 21:07:56 +0000 | [diff] [blame] | 121 | return !VariableIdxFound; |
| 122 | } |
| 123 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 124 | if (GEP2 && !GEP1 && GEP2->getOperand(0)->stripPointerCasts() == Ptr1) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 125 | Offset = GetOffsetFromIndex(GEP2, 1, VariableIdxFound, DL); |
Chris Lattner | 5120ebf | 2011-01-08 21:07:56 +0000 | [diff] [blame] | 126 | return !VariableIdxFound; |
| 127 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 128 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 129 | // Right now we handle the case when Ptr1/Ptr2 are both GEPs with an identical |
| 130 | // base. After that base, they may have some number of common (and |
| 131 | // potentially variable) indices. After that they handle some constant |
| 132 | // offset, which determines their offset from each other. At this point, we |
| 133 | // handle no other case. |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 134 | if (!GEP1 || !GEP2 || GEP1->getOperand(0) != GEP2->getOperand(0)) |
| 135 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 136 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 137 | // Skip any common indices and track the GEP types. |
| 138 | unsigned Idx = 1; |
| 139 | for (; Idx != GEP1->getNumOperands() && Idx != GEP2->getNumOperands(); ++Idx) |
| 140 | if (GEP1->getOperand(Idx) != GEP2->getOperand(Idx)) |
| 141 | break; |
| 142 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 143 | int64_t Offset1 = GetOffsetFromIndex(GEP1, Idx, VariableIdxFound, DL); |
| 144 | int64_t Offset2 = GetOffsetFromIndex(GEP2, Idx, VariableIdxFound, DL); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 145 | if (VariableIdxFound) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 146 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 147 | Offset = Offset2-Offset1; |
| 148 | return true; |
| 149 | } |
| 150 | |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 151 | namespace { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 152 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 153 | /// Represents a range of memset'd bytes with the ByteVal value. |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 154 | /// This allows us to analyze stores like: |
| 155 | /// store 0 -> P+1 |
| 156 | /// store 0 -> P+0 |
| 157 | /// store 0 -> P+3 |
| 158 | /// store 0 -> P+2 |
| 159 | /// which sometimes happens with stores to arrays of structs etc. When we see |
| 160 | /// the first store, we make a range [1, 2). The second store extends the range |
| 161 | /// to [0, 2). The third makes a new range [2, 3). The fourth store joins the |
| 162 | /// two ranges into [0, 3) which is memset'able. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 163 | struct MemsetRange { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 164 | // Start/End - A semi range that describes the span that this range covers. |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 165 | // The range is closed at the start and open at the end: [Start, End). |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 166 | int64_t Start, End; |
| 167 | |
| 168 | /// StartPtr - The getelementptr instruction that points to the start of the |
| 169 | /// range. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 170 | Value *StartPtr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 171 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 172 | /// Alignment - The known alignment of the first store. |
| 173 | unsigned Alignment; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 174 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 175 | /// TheStores - The actual stores that make up this range. |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 176 | SmallVector<Instruction*, 16> TheStores; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 177 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 178 | bool isProfitableToUseMemset(const DataLayout &DL) const; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 179 | }; |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 180 | |
| 181 | } // end anonymous namespace |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 182 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 183 | bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const { |
| 184 | // If we found more than 4 stores to merge or 16 bytes, use memset. |
Chad Rosier | 19446a0 | 2011-12-05 22:37:00 +0000 | [diff] [blame] | 185 | if (TheStores.size() >= 4 || End-Start >= 16) return true; |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 186 | |
| 187 | // If there is nothing to merge, don't do anything. |
| 188 | if (TheStores.size() < 2) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 189 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 190 | // If any of the stores are a memset, then it is always good to extend the |
| 191 | // memset. |
Craig Topper | e325e38 | 2015-11-20 07:18:48 +0000 | [diff] [blame] | 192 | for (Instruction *SI : TheStores) |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 193 | if (!isa<StoreInst>(SI)) |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 194 | return true; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 195 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 196 | // Assume that the code generator is capable of merging pairs of stores |
| 197 | // together if it wants to. |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 198 | if (TheStores.size() == 2) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 199 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 200 | // If we have fewer than 8 stores, it can still be worthwhile to do this. |
| 201 | // For example, merging 4 i8 stores into an i32 store is useful almost always. |
| 202 | // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the |
| 203 | // memset will be split into 2 32-bit stores anyway) and doing so can |
| 204 | // pessimize the llvm optimizer. |
| 205 | // |
| 206 | // Since we don't have perfect knowledge here, make some assumptions: assume |
Matt Arsenault | 899f7d2 | 2013-09-16 22:43:16 +0000 | [diff] [blame] | 207 | // the maximum GPR width is the same size as the largest legal integer |
| 208 | // size. If so, check to see whether we will end up actually reducing the |
| 209 | // number of stores used. |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 210 | unsigned Bytes = unsigned(End-Start); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 211 | unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8; |
Matt Arsenault | 899f7d2 | 2013-09-16 22:43:16 +0000 | [diff] [blame] | 212 | if (MaxIntSize == 0) |
| 213 | MaxIntSize = 1; |
| 214 | unsigned NumPointerStores = Bytes / MaxIntSize; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 215 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 216 | // Assume the remaining bytes if any are done a byte at a time. |
Craig Topper | a5ea528 | 2015-11-21 17:44:42 +0000 | [diff] [blame] | 217 | unsigned NumByteStores = Bytes % MaxIntSize; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 218 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 219 | // If we will reduce the # stores (according to this heuristic), do the |
| 220 | // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32 |
| 221 | // etc. |
| 222 | return TheStores.size() > NumPointerStores+NumByteStores; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 223 | } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 224 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 225 | namespace { |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 226 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 227 | class MemsetRanges { |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 228 | /// A sorted list of the memset ranges. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 229 | SmallVector<MemsetRange, 8> Ranges; |
| 230 | typedef SmallVectorImpl<MemsetRange>::iterator range_iterator; |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 231 | const DataLayout &DL; |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 232 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 233 | public: |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 234 | MemsetRanges(const DataLayout &DL) : DL(DL) {} |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 235 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 236 | typedef SmallVectorImpl<MemsetRange>::const_iterator const_iterator; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 237 | const_iterator begin() const { return Ranges.begin(); } |
| 238 | const_iterator end() const { return Ranges.end(); } |
| 239 | bool empty() const { return Ranges.empty(); } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 240 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 241 | void addInst(int64_t OffsetFromFirst, Instruction *Inst) { |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 242 | if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) |
| 243 | addStore(OffsetFromFirst, SI); |
| 244 | else |
| 245 | addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst)); |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 246 | } |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 247 | |
| 248 | void addStore(int64_t OffsetFromFirst, StoreInst *SI) { |
Rafael Espindola | 37dc9e1 | 2014-02-21 00:06:31 +0000 | [diff] [blame] | 249 | int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 250 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 251 | addRange(OffsetFromFirst, StoreSize, |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 252 | SI->getPointerOperand(), SI->getAlignment(), SI); |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 253 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 254 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 255 | void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) { |
| 256 | int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue(); |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 257 | addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getAlignment(), MSI); |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 258 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 259 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 260 | void addRange(int64_t Start, int64_t Size, Value *Ptr, |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 261 | unsigned Alignment, Instruction *Inst); |
| 262 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 263 | }; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 264 | |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 265 | } // end anonymous namespace |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 266 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 267 | /// Add a new store to the MemsetRanges data structure. This adds a |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 268 | /// new range for the specified store at the specified offset, merging into |
| 269 | /// existing ranges as appropriate. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 270 | void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr, |
| 271 | unsigned Alignment, Instruction *Inst) { |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 272 | int64_t End = Start+Size; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 273 | |
Nick Lewycky | f836c89 | 2015-07-21 21:56:26 +0000 | [diff] [blame] | 274 | range_iterator I = std::lower_bound(Ranges.begin(), Ranges.end(), Start, |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 275 | [](const MemsetRange &LHS, int64_t RHS) { return LHS.End < RHS; }); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 276 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 277 | // We now know that I == E, in which case we didn't find anything to merge |
| 278 | // with, or that Start <= I->End. If End < I->Start or I == E, then we need |
| 279 | // to insert a new range. Handle this now. |
Nick Lewycky | f836c89 | 2015-07-21 21:56:26 +0000 | [diff] [blame] | 280 | if (I == Ranges.end() || End < I->Start) { |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 281 | MemsetRange &R = *Ranges.insert(I, MemsetRange()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 282 | R.Start = Start; |
| 283 | R.End = End; |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 284 | R.StartPtr = Ptr; |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 285 | R.Alignment = Alignment; |
| 286 | R.TheStores.push_back(Inst); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 287 | return; |
| 288 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 289 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 290 | // This store overlaps with I, add it. |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 291 | I->TheStores.push_back(Inst); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 292 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 293 | // At this point, we may have an interval that completely contains our store. |
| 294 | // If so, just add it to the interval and return. |
| 295 | if (I->Start <= Start && I->End >= End) |
| 296 | return; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 297 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 298 | // Now we know that Start <= I->End and End >= I->Start so the range overlaps |
| 299 | // but is not entirely contained within the range. |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 300 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 301 | // See if the range extends the start of the range. In this case, it couldn't |
| 302 | // possibly cause it to join the prior range, because otherwise we would have |
| 303 | // stopped on *it*. |
| 304 | if (Start < I->Start) { |
| 305 | I->Start = Start; |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 306 | I->StartPtr = Ptr; |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 307 | I->Alignment = Alignment; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 308 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 309 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 310 | // Now we know that Start <= I->End and Start >= I->Start (so the startpoint |
| 311 | // is in or right at the end of I), and that End >= I->Start. Extend I out to |
| 312 | // End. |
| 313 | if (End > I->End) { |
| 314 | I->End = End; |
Nick Lewycky | bfd4ad6 | 2009-03-19 05:51:39 +0000 | [diff] [blame] | 315 | range_iterator NextI = I; |
Nick Lewycky | f836c89 | 2015-07-21 21:56:26 +0000 | [diff] [blame] | 316 | while (++NextI != Ranges.end() && End >= NextI->Start) { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 317 | // Merge the range in. |
| 318 | I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end()); |
| 319 | if (NextI->End > I->End) |
| 320 | I->End = NextI->End; |
| 321 | Ranges.erase(NextI); |
| 322 | NextI = I; |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | //===----------------------------------------------------------------------===// |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 328 | // MemCpyOptLegacyPass Pass |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 329 | //===----------------------------------------------------------------------===// |
| 330 | |
| 331 | namespace { |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 332 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 333 | class MemCpyOptLegacyPass : public FunctionPass { |
| 334 | MemCpyOptPass Impl; |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 335 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 336 | public: |
| 337 | static char ID; // Pass identification, replacement for typeid |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 338 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 339 | MemCpyOptLegacyPass() : FunctionPass(ID) { |
| 340 | initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry()); |
| 341 | } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 342 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 343 | bool runOnFunction(Function &F) override; |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 344 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 345 | private: |
| 346 | // This transformation requires dominator postdominator info |
| 347 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
| 348 | AU.setPreservesCFG(); |
| 349 | AU.addRequired<AssumptionCacheTracker>(); |
| 350 | AU.addRequired<DominatorTreeWrapperPass>(); |
| 351 | AU.addRequired<MemoryDependenceWrapperPass>(); |
| 352 | AU.addRequired<AAResultsWrapperPass>(); |
| 353 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
| 354 | AU.addPreserved<GlobalsAAWrapperPass>(); |
| 355 | AU.addPreserved<MemoryDependenceWrapperPass>(); |
| 356 | } |
| 357 | }; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 358 | |
George Burgess IV | ecb95f5 | 2017-03-08 21:28:19 +0000 | [diff] [blame] | 359 | char MemCpyOptLegacyPass::ID = 0; |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 360 | |
| 361 | } // end anonymous namespace |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 362 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 363 | /// The public interface to this file... |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 364 | FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 365 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 366 | INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", |
Owen Anderson | 8ac477f | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 367 | false, false) |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 368 | INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 369 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
Chandler Carruth | 61440d2 | 2016-03-10 00:55:30 +0000 | [diff] [blame] | 370 | INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass) |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 371 | INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) |
Chandler Carruth | 7b560d4 | 2015-09-09 17:55:00 +0000 | [diff] [blame] | 372 | INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) |
| 373 | INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass) |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 374 | INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization", |
Owen Anderson | 8ac477f | 2010-10-12 19:48:12 +0000 | [diff] [blame] | 375 | false, false) |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 376 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 377 | /// When scanning forward over instructions, we look for some other patterns to |
| 378 | /// fold away. In particular, this looks for stores to neighboring locations of |
| 379 | /// memory. If it sees enough consecutive ones, it attempts to merge them |
| 380 | /// together into a memcpy/memset. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 381 | Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst, |
| 382 | Value *StartPtr, |
| 383 | Value *ByteVal) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 384 | const DataLayout &DL = StartInst->getModule()->getDataLayout(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 385 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 386 | // Okay, so we now have a single store that can be splatable. Scan to find |
| 387 | // all subsequent stores of the same value to offset from the same pointer. |
| 388 | // Join these together into ranges, so we can decide whether contiguous blocks |
| 389 | // are stored. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 390 | MemsetRanges Ranges(DL); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 391 | |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 392 | BasicBlock::iterator BI(StartInst); |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 393 | for (++BI; !isa<TerminatorInst>(BI); ++BI) { |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 394 | if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) { |
| 395 | // If the instruction is readnone, ignore it, otherwise bail out. We |
| 396 | // don't even allow readonly here because we don't want something like: |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 397 | // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A). |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 398 | if (BI->mayWriteToMemory() || BI->mayReadFromMemory()) |
| 399 | break; |
| 400 | continue; |
| 401 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 402 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 403 | if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) { |
| 404 | // If this is a store, see if we can merge it in. |
Eli Friedman | 9a46815 | 2011-08-17 22:22:24 +0000 | [diff] [blame] | 405 | if (!NextStore->isSimple()) break; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 406 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 407 | // Check to see if this stored value is of the same byte-splattable value. |
| 408 | if (ByteVal != isBytewiseValue(NextStore->getOperand(0))) |
| 409 | break; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 410 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 411 | // Check to see if this store is to a constant offset from the start ptr. |
| 412 | int64_t Offset; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 413 | if (!IsPointerOffset(StartPtr, NextStore->getPointerOperand(), Offset, |
| 414 | DL)) |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 415 | break; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 416 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 417 | Ranges.addStore(Offset, NextStore); |
| 418 | } else { |
| 419 | MemSetInst *MSI = cast<MemSetInst>(BI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 420 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 421 | if (MSI->isVolatile() || ByteVal != MSI->getValue() || |
| 422 | !isa<ConstantInt>(MSI->getLength())) |
| 423 | break; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 424 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 425 | // Check to see if this store is to a constant offset from the start ptr. |
| 426 | int64_t Offset; |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 427 | if (!IsPointerOffset(StartPtr, MSI->getDest(), Offset, DL)) |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 428 | break; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 429 | |
Chris Lattner | 4dc1fd9 | 2011-01-08 20:54:51 +0000 | [diff] [blame] | 430 | Ranges.addMemSet(Offset, MSI); |
| 431 | } |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 432 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 433 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 434 | // If we have no ranges, then we just had a single store with nothing that |
| 435 | // could be merged in. This is a very common case of course. |
| 436 | if (Ranges.empty()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 437 | return nullptr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 438 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 439 | // If we had at least one store that could be merged in, add the starting |
| 440 | // store as well. We try to avoid this unless there is at least something |
| 441 | // interesting as a small compile-time optimization. |
| 442 | Ranges.addInst(0, StartInst); |
| 443 | |
| 444 | // If we create any memsets, we put it right before the first instruction that |
| 445 | // isn't part of the memset block. This ensure that the memset is dominated |
| 446 | // by any addressing instruction needed by the start of the block. |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 447 | IRBuilder<> Builder(&*BI); |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 448 | |
| 449 | // Now that we have full information about ranges, loop over the ranges and |
| 450 | // emit memset's for anything big enough to be worthwhile. |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 451 | Instruction *AMemSet = nullptr; |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 452 | for (const MemsetRange &Range : Ranges) { |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 453 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 454 | if (Range.TheStores.size() == 1) continue; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 455 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 456 | // If it is profitable to lower this range to memset, do so now. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 457 | if (!Range.isProfitableToUseMemset(DL)) |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 458 | continue; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 459 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 460 | // Otherwise, we do want to transform this! Create a new memset. |
| 461 | // Get the starting pointer of the block. |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 462 | StartPtr = Range.StartPtr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 463 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 464 | // Determine alignment |
| 465 | unsigned Alignment = Range.Alignment; |
| 466 | if (Alignment == 0) { |
| 467 | Type *EltType = |
| 468 | cast<PointerType>(StartPtr->getType())->getElementType(); |
| 469 | Alignment = DL.getABITypeAlignment(EltType); |
| 470 | } |
| 471 | |
| 472 | AMemSet = |
| 473 | Builder.CreateMemSet(StartPtr, ByteVal, Range.End-Range.Start, Alignment); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 474 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 475 | DEBUG(dbgs() << "Replace stores:\n"; |
Craig Topper | e325e38 | 2015-11-20 07:18:48 +0000 | [diff] [blame] | 476 | for (Instruction *SI : Range.TheStores) |
| 477 | dbgs() << *SI << '\n'; |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 478 | dbgs() << "With: " << *AMemSet << '\n'); |
Devang Patel | c7e4fa7 | 2011-05-04 21:58:58 +0000 | [diff] [blame] | 479 | |
| 480 | if (!Range.TheStores.empty()) |
| 481 | AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc()); |
| 482 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 483 | // Zap all the stores. |
Craig Topper | e325e38 | 2015-11-20 07:18:48 +0000 | [diff] [blame] | 484 | for (Instruction *SI : Range.TheStores) { |
| 485 | MD->removeInstruction(SI); |
| 486 | SI->eraseFromParent(); |
Chris Lattner | 7d6433a | 2011-01-08 22:19:21 +0000 | [diff] [blame] | 487 | } |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 488 | ++NumMemSetInfer; |
| 489 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 490 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 491 | return AMemSet; |
| 492 | } |
| 493 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 494 | static unsigned findCommonAlignment(const DataLayout &DL, const StoreInst *SI, |
| 495 | const LoadInst *LI) { |
| 496 | unsigned StoreAlign = SI->getAlignment(); |
| 497 | if (!StoreAlign) |
| 498 | StoreAlign = DL.getABITypeAlignment(SI->getOperand(0)->getType()); |
| 499 | unsigned LoadAlign = LI->getAlignment(); |
| 500 | if (!LoadAlign) |
| 501 | LoadAlign = DL.getABITypeAlignment(LI->getType()); |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 502 | |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 503 | return std::min(StoreAlign, LoadAlign); |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 504 | } |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 505 | |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 506 | // This method try to lift a store instruction before position P. |
| 507 | // It will lift the store and its argument + that anything that |
David Majnemer | d99068d | 2016-05-26 19:24:24 +0000 | [diff] [blame] | 508 | // may alias with these. |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 509 | // The method returns true if it was successful. |
Bryant Wong | 7cb7446 | 2016-12-27 17:58:12 +0000 | [diff] [blame] | 510 | static bool moveUp(AliasAnalysis &AA, StoreInst *SI, Instruction *P, |
| 511 | const LoadInst *LI) { |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 512 | // If the store alias this position, early bail out. |
| 513 | MemoryLocation StoreLoc = MemoryLocation::get(SI); |
| 514 | if (AA.getModRefInfo(P, StoreLoc) != MRI_NoModRef) |
| 515 | return false; |
| 516 | |
| 517 | // Keep track of the arguments of all instruction we plan to lift |
| 518 | // so we can make sure to lift them as well if apropriate. |
| 519 | DenseSet<Instruction*> Args; |
| 520 | if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand())) |
| 521 | if (Ptr->getParent() == SI->getParent()) |
| 522 | Args.insert(Ptr); |
| 523 | |
| 524 | // Instruction to lift before P. |
| 525 | SmallVector<Instruction*, 8> ToLift; |
| 526 | |
| 527 | // Memory locations of lifted instructions. |
Bryant Wong | 7cb7446 | 2016-12-27 17:58:12 +0000 | [diff] [blame] | 528 | SmallVector<MemoryLocation, 8> MemLocs{StoreLoc}; |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 529 | |
| 530 | // Lifted callsites. |
| 531 | SmallVector<ImmutableCallSite, 8> CallSites; |
| 532 | |
Bryant Wong | 7cb7446 | 2016-12-27 17:58:12 +0000 | [diff] [blame] | 533 | const MemoryLocation LoadLoc = MemoryLocation::get(LI); |
| 534 | |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 535 | for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) { |
| 536 | auto *C = &*I; |
| 537 | |
| 538 | bool MayAlias = AA.getModRefInfo(C) != MRI_NoModRef; |
| 539 | |
| 540 | bool NeedLift = false; |
| 541 | if (Args.erase(C)) |
| 542 | NeedLift = true; |
| 543 | else if (MayAlias) { |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 544 | NeedLift = llvm::any_of(MemLocs, [C, &AA](const MemoryLocation &ML) { |
David Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 545 | return AA.getModRefInfo(C, ML); |
| 546 | }); |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 547 | |
| 548 | if (!NeedLift) |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 549 | NeedLift = |
| 550 | llvm::any_of(CallSites, [C, &AA](const ImmutableCallSite &CS) { |
| 551 | return AA.getModRefInfo(C, CS); |
| 552 | }); |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 553 | } |
| 554 | |
| 555 | if (!NeedLift) |
| 556 | continue; |
| 557 | |
| 558 | if (MayAlias) { |
Bryant Wong | 7cb7446 | 2016-12-27 17:58:12 +0000 | [diff] [blame] | 559 | // Since LI is implicitly moved downwards past the lifted instructions, |
| 560 | // none of them may modify its source. |
| 561 | if (AA.getModRefInfo(C, LoadLoc) & MRI_Mod) |
| 562 | return false; |
| 563 | else if (auto CS = ImmutableCallSite(C)) { |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 564 | // If we can't lift this before P, it's game over. |
| 565 | if (AA.getModRefInfo(P, CS) != MRI_NoModRef) |
| 566 | return false; |
| 567 | |
| 568 | CallSites.push_back(CS); |
| 569 | } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) { |
| 570 | // If we can't lift this before P, it's game over. |
| 571 | auto ML = MemoryLocation::get(C); |
| 572 | if (AA.getModRefInfo(P, ML) != MRI_NoModRef) |
| 573 | return false; |
| 574 | |
| 575 | MemLocs.push_back(ML); |
| 576 | } else |
| 577 | // We don't know how to lift this instruction. |
| 578 | return false; |
| 579 | } |
| 580 | |
| 581 | ToLift.push_back(C); |
| 582 | for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k) |
| 583 | if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) |
| 584 | if (A->getParent() == SI->getParent()) |
| 585 | Args.insert(A); |
| 586 | } |
| 587 | |
| 588 | // We made it, we need to lift |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 589 | for (auto *I : llvm::reverse(ToLift)) { |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 590 | DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n"); |
| 591 | I->moveBefore(P); |
| 592 | } |
| 593 | |
| 594 | return true; |
| 595 | } |
| 596 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 597 | bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) { |
Eli Friedman | 9a46815 | 2011-08-17 22:22:24 +0000 | [diff] [blame] | 598 | if (!SI->isSimple()) return false; |
Andrea Di Biagio | 99493df | 2015-10-09 10:53:41 +0000 | [diff] [blame] | 599 | |
| 600 | // Avoid merging nontemporal stores since the resulting |
| 601 | // memcpy/memset would not be able to preserve the nontemporal hint. |
| 602 | // In theory we could teach how to propagate the !nontemporal metadata to |
| 603 | // memset calls. However, that change would force the backend to |
| 604 | // conservatively expand !nontemporal memset calls back to sequences of |
| 605 | // store instructions (effectively undoing the merging). |
| 606 | if (SI->getMetadata(LLVMContext::MD_nontemporal)) |
| 607 | return false; |
| 608 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 609 | const DataLayout &DL = SI->getModule()->getDataLayout(); |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 610 | |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 611 | // Load to store forwarding can be interpreted as memcpy. |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 612 | if (LoadInst *LI = dyn_cast<LoadInst>(SI->getOperand(0))) { |
Eli Friedman | 9a46815 | 2011-08-17 22:22:24 +0000 | [diff] [blame] | 613 | if (LI->isSimple() && LI->hasOneUse() && |
Eli Friedman | e8bbc10 | 2011-06-15 01:25:56 +0000 | [diff] [blame] | 614 | LI->getParent() == SI->getParent()) { |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 615 | |
| 616 | auto *T = LI->getType(); |
| 617 | if (T->isAggregateType()) { |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 618 | AliasAnalysis &AA = LookupAliasAnalysis(); |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 619 | MemoryLocation LoadLoc = MemoryLocation::get(LI); |
| 620 | |
| 621 | // We use alias analysis to check if an instruction may store to |
| 622 | // the memory we load from in between the load and the store. If |
Amaury Sechet | d3b2c0f | 2016-01-06 09:30:39 +0000 | [diff] [blame] | 623 | // such an instruction is found, we try to promote there instead |
| 624 | // of at the store position. |
| 625 | Instruction *P = SI; |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 626 | for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) { |
| 627 | if (AA.getModRefInfo(&I, LoadLoc) & MRI_Mod) { |
| 628 | P = &I; |
| 629 | break; |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 630 | } |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 631 | } |
Amaury Sechet | d3b2c0f | 2016-01-06 09:30:39 +0000 | [diff] [blame] | 632 | |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 633 | // We found an instruction that may write to the loaded memory. |
| 634 | // We can try to promote at this position instead of the store |
| 635 | // position if nothing alias the store memory after this and the store |
| 636 | // destination is not in the range. |
| 637 | if (P && P != SI) { |
Bryant Wong | 7cb7446 | 2016-12-27 17:58:12 +0000 | [diff] [blame] | 638 | if (!moveUp(AA, SI, P, LI)) |
Amaury Sechet | bdb261b | 2016-03-14 22:52:27 +0000 | [diff] [blame] | 639 | P = nullptr; |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 640 | } |
| 641 | |
Amaury Sechet | d3b2c0f | 2016-01-06 09:30:39 +0000 | [diff] [blame] | 642 | // If a valid insertion position is found, then we can promote |
| 643 | // the load/store pair to a memcpy. |
| 644 | if (P) { |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 645 | // If we load from memory that may alias the memory we store to, |
| 646 | // memmove must be used to preserve semantic. If not, memcpy can |
| 647 | // be used. |
| 648 | bool UseMemMove = false; |
| 649 | if (!AA.isNoAlias(MemoryLocation::get(SI), LoadLoc)) |
| 650 | UseMemMove = true; |
| 651 | |
| 652 | unsigned Align = findCommonAlignment(DL, SI, LI); |
| 653 | uint64_t Size = DL.getTypeStoreSize(T); |
| 654 | |
Amaury Sechet | d3b2c0f | 2016-01-06 09:30:39 +0000 | [diff] [blame] | 655 | IRBuilder<> Builder(P); |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 656 | Instruction *M; |
| 657 | if (UseMemMove) |
| 658 | M = Builder.CreateMemMove(SI->getPointerOperand(), |
| 659 | LI->getPointerOperand(), Size, |
| 660 | Align, SI->isVolatile()); |
| 661 | else |
| 662 | M = Builder.CreateMemCpy(SI->getPointerOperand(), |
| 663 | LI->getPointerOperand(), Size, |
| 664 | Align, SI->isVolatile()); |
| 665 | |
| 666 | DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI |
| 667 | << " => " << *M << "\n"); |
| 668 | |
| 669 | MD->removeInstruction(SI); |
| 670 | SI->eraseFromParent(); |
| 671 | MD->removeInstruction(LI); |
| 672 | LI->eraseFromParent(); |
| 673 | ++NumMemCpyInstr; |
| 674 | |
| 675 | // Make sure we do not invalidate the iterator. |
| 676 | BBI = M->getIterator(); |
| 677 | return true; |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | // Detect cases where we're performing call slot forwarding, but |
| 682 | // happen to be using a load-store pair to implement it, rather than |
| 683 | // a memcpy. |
Eli Friedman | 5da0ff4 | 2011-06-02 21:24:42 +0000 | [diff] [blame] | 684 | MemDepResult ldep = MD->getDependency(LI); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 685 | CallInst *C = nullptr; |
Eli Friedman | 5da0ff4 | 2011-06-02 21:24:42 +0000 | [diff] [blame] | 686 | if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst())) |
| 687 | C = dyn_cast<CallInst>(ldep.getInst()); |
| 688 | |
| 689 | if (C) { |
| 690 | // Check that nothing touches the dest of the "copy" between |
| 691 | // the call and the store. |
David Majnemer | d99068d | 2016-05-26 19:24:24 +0000 | [diff] [blame] | 692 | Value *CpyDest = SI->getPointerOperand()->stripPointerCasts(); |
| 693 | bool CpyDestIsLocal = isa<AllocaInst>(CpyDest); |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 694 | AliasAnalysis &AA = LookupAliasAnalysis(); |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 695 | MemoryLocation StoreLoc = MemoryLocation::get(SI); |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 696 | for (BasicBlock::iterator I = --SI->getIterator(), E = C->getIterator(); |
| 697 | I != E; --I) { |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 698 | if (AA.getModRefInfo(&*I, StoreLoc) != MRI_NoModRef) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 699 | C = nullptr; |
Eli Friedman | e8bbc10 | 2011-06-15 01:25:56 +0000 | [diff] [blame] | 700 | break; |
| 701 | } |
David Majnemer | d99068d | 2016-05-26 19:24:24 +0000 | [diff] [blame] | 702 | // The store to dest may never happen if an exception can be thrown |
| 703 | // between the load and the store. |
| 704 | if (I->mayThrow() && !CpyDestIsLocal) { |
| 705 | C = nullptr; |
| 706 | break; |
| 707 | } |
Eli Friedman | 5da0ff4 | 2011-06-02 21:24:42 +0000 | [diff] [blame] | 708 | } |
| 709 | } |
| 710 | |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 711 | if (C) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 712 | bool changed = performCallSlotOptzn( |
| 713 | LI, SI->getPointerOperand()->stripPointerCasts(), |
| 714 | LI->getPointerOperand()->stripPointerCasts(), |
| 715 | DL.getTypeStoreSize(SI->getOperand(0)->getType()), |
Amaury Sechet | a0c242c | 2016-01-05 20:17:48 +0000 | [diff] [blame] | 716 | findCommonAlignment(DL, SI, LI), C); |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 717 | if (changed) { |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 718 | MD->removeInstruction(SI); |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 719 | SI->eraseFromParent(); |
Chris Lattner | caf5c0d | 2011-01-09 19:26:10 +0000 | [diff] [blame] | 720 | MD->removeInstruction(LI); |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 721 | LI->eraseFromParent(); |
| 722 | ++NumMemCpyInstr; |
| 723 | return true; |
| 724 | } |
| 725 | } |
| 726 | } |
| 727 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 728 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 729 | // There are two cases that are interesting for this code to handle: memcpy |
| 730 | // and memset. Right now we only handle memset. |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 731 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 732 | // Ensure that the value being stored is something that can be memset'able a |
| 733 | // byte at a time like "0" or "-1" or any width, as well as things like |
| 734 | // 0xA0A0A0A0 and 0.0. |
Amaury Sechet | 3235c08 | 2016-01-06 19:47:24 +0000 | [diff] [blame] | 735 | auto *V = SI->getOperand(0); |
| 736 | if (Value *ByteVal = isBytewiseValue(V)) { |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 737 | if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(), |
| 738 | ByteVal)) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 739 | BBI = I->getIterator(); // Don't invalidate iterator. |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 740 | return true; |
Mon P Wang | c576ee9 | 2010-04-04 03:10:48 +0000 | [diff] [blame] | 741 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 742 | |
Amaury Sechet | 3235c08 | 2016-01-06 19:47:24 +0000 | [diff] [blame] | 743 | // If we have an aggregate, we try to promote it to memset regardless |
| 744 | // of opportunity for merging as it can expose optimization opportunities |
| 745 | // in subsequent passes. |
| 746 | auto *T = V->getType(); |
| 747 | if (T->isAggregateType()) { |
| 748 | uint64_t Size = DL.getTypeStoreSize(T); |
| 749 | unsigned Align = SI->getAlignment(); |
| 750 | if (!Align) |
| 751 | Align = DL.getABITypeAlignment(T); |
| 752 | IRBuilder<> Builder(SI); |
| 753 | auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, |
| 754 | Size, Align, SI->isVolatile()); |
| 755 | |
| 756 | DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n"); |
| 757 | |
| 758 | MD->removeInstruction(SI); |
| 759 | SI->eraseFromParent(); |
| 760 | NumMemSetInfer++; |
| 761 | |
| 762 | // Make sure we do not invalidate the iterator. |
| 763 | BBI = M->getIterator(); |
| 764 | return true; |
| 765 | } |
| 766 | } |
| 767 | |
Chris Lattner | c638147 | 2011-01-08 20:24:01 +0000 | [diff] [blame] | 768 | return false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 769 | } |
| 770 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 771 | bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) { |
Chris Lattner | 9a1d63b | 2011-01-08 21:19:19 +0000 | [diff] [blame] | 772 | // See if there is another memset or store neighboring this memset which |
| 773 | // allows us to widen out the memset to do a single larger store. |
Chris Lattner | ff6ed2a | 2011-01-08 22:11:56 +0000 | [diff] [blame] | 774 | if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile()) |
| 775 | if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(), |
| 776 | MSI->getValue())) { |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 777 | BBI = I->getIterator(); // Don't invalidate iterator. |
Chris Lattner | ff6ed2a | 2011-01-08 22:11:56 +0000 | [diff] [blame] | 778 | return true; |
| 779 | } |
Chris Lattner | 9a1d63b | 2011-01-08 21:19:19 +0000 | [diff] [blame] | 780 | return false; |
| 781 | } |
| 782 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 783 | /// Takes a memcpy and a call that it depends on, |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 784 | /// and checks for the possibility of a call slot optimization by having |
| 785 | /// the call write its result directly into the destination of the memcpy. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 786 | bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpy, Value *cpyDest, |
| 787 | Value *cpySrc, uint64_t cpyLen, |
| 788 | unsigned cpyAlign, CallInst *C) { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 789 | // The general transformation to keep in mind is |
| 790 | // |
| 791 | // call @func(..., src, ...) |
| 792 | // memcpy(dest, src, ...) |
| 793 | // |
| 794 | // -> |
| 795 | // |
| 796 | // memcpy(dest, src, ...) |
| 797 | // call @func(..., dest, ...) |
| 798 | // |
| 799 | // Since moving the memcpy is technically awkward, we additionally check that |
| 800 | // src only holds uninitialized values at the moment of the call, meaning that |
| 801 | // the memcpy can be discarded rather than moved. |
| 802 | |
Tim Shen | 7aa0ad6 | 2016-06-08 19:42:32 +0000 | [diff] [blame] | 803 | // Lifetime marks shouldn't be operated on. |
| 804 | if (Function *F = C->getCalledFunction()) |
| 805 | if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start) |
| 806 | return false; |
| 807 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 808 | // Deliberately get the source and destination with bitcasts stripped away, |
| 809 | // because we'll need to do type comparisons based on the underlying type. |
Gabor Greif | 62f0aac | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 810 | CallSite CS(C); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 811 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 812 | // Require that src be an alloca. This simplifies the reasoning considerably. |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 813 | AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 814 | if (!srcAlloca) |
| 815 | return false; |
| 816 | |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 817 | ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 818 | if (!srcArraySize) |
| 819 | return false; |
| 820 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 821 | const DataLayout &DL = cpy->getModule()->getDataLayout(); |
| 822 | uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) * |
| 823 | srcArraySize->getZExtValue(); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 824 | |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 825 | if (cpyLen < srcSize) |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 826 | return false; |
| 827 | |
| 828 | // Check that accessing the first srcSize bytes of dest will not cause a |
| 829 | // trap. Otherwise the transform is invalid since it might cause a trap |
| 830 | // to occur earlier than it otherwise would. |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 831 | if (AllocaInst *A = dyn_cast<AllocaInst>(cpyDest)) { |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 832 | // The destination is an alloca. Check it is larger than srcSize. |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 833 | ConstantInt *destArraySize = dyn_cast<ConstantInt>(A->getArraySize()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 834 | if (!destArraySize) |
| 835 | return false; |
| 836 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 837 | uint64_t destSize = DL.getTypeAllocSize(A->getAllocatedType()) * |
| 838 | destArraySize->getZExtValue(); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 839 | |
| 840 | if (destSize < srcSize) |
| 841 | return false; |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 842 | } else if (Argument *A = dyn_cast<Argument>(cpyDest)) { |
David Majnemer | d99068d | 2016-05-26 19:24:24 +0000 | [diff] [blame] | 843 | // The store to dest may never happen if the call can throw. |
| 844 | if (C->mayThrow()) |
| 845 | return false; |
| 846 | |
Bjorn Steinbrink | d20816f | 2014-10-16 19:43:08 +0000 | [diff] [blame] | 847 | if (A->getDereferenceableBytes() < srcSize) { |
| 848 | // If the destination is an sret parameter then only accesses that are |
| 849 | // outside of the returned struct type can trap. |
| 850 | if (!A->hasStructRetAttr()) |
| 851 | return false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 852 | |
Bjorn Steinbrink | d20816f | 2014-10-16 19:43:08 +0000 | [diff] [blame] | 853 | Type *StructTy = cast<PointerType>(A->getType())->getElementType(); |
| 854 | if (!StructTy->isSized()) { |
| 855 | // The call may never return and hence the copy-instruction may never |
| 856 | // be executed, and therefore it's not safe to say "the destination |
| 857 | // has at least <cpyLen> bytes, as implied by the copy-instruction", |
| 858 | return false; |
| 859 | } |
| 860 | |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 861 | uint64_t destSize = DL.getTypeAllocSize(StructTy); |
Bjorn Steinbrink | d20816f | 2014-10-16 19:43:08 +0000 | [diff] [blame] | 862 | if (destSize < srcSize) |
| 863 | return false; |
Shuxin Yang | 140d592 | 2013-06-08 04:56:05 +0000 | [diff] [blame] | 864 | } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 865 | } else { |
| 866 | return false; |
| 867 | } |
| 868 | |
Duncan Sands | 933db77 | 2012-10-05 07:29:46 +0000 | [diff] [blame] | 869 | // Check that dest points to memory that is at least as aligned as src. |
| 870 | unsigned srcAlign = srcAlloca->getAlignment(); |
| 871 | if (!srcAlign) |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 872 | srcAlign = DL.getABITypeAlignment(srcAlloca->getAllocatedType()); |
Duncan Sands | 933db77 | 2012-10-05 07:29:46 +0000 | [diff] [blame] | 873 | bool isDestSufficientlyAligned = srcAlign <= cpyAlign; |
| 874 | // If dest is not aligned enough and we can't increase its alignment then |
| 875 | // bail out. |
| 876 | if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest)) |
| 877 | return false; |
| 878 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 879 | // Check that src is not accessed except via the call and the memcpy. This |
| 880 | // guarantees that it holds only undefined values when passed in (so the final |
| 881 | // memcpy can be dropped), that it is not read or written between the call and |
| 882 | // the memcpy, and that writing beyond the end of it is undefined. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 883 | SmallVector<User*, 8> srcUseList(srcAlloca->user_begin(), |
| 884 | srcAlloca->user_end()); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 885 | while (!srcUseList.empty()) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 886 | User *U = srcUseList.pop_back_val(); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 887 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 888 | if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) { |
| 889 | for (User *UU : U->users()) |
| 890 | srcUseList.push_back(UU); |
Chandler Carruth | 18cee1d | 2014-09-01 10:09:18 +0000 | [diff] [blame] | 891 | continue; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 892 | } |
Chandler Carruth | 18cee1d | 2014-09-01 10:09:18 +0000 | [diff] [blame] | 893 | if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) { |
| 894 | if (!G->hasAllZeroIndices()) |
| 895 | return false; |
| 896 | |
| 897 | for (User *UU : U->users()) |
| 898 | srcUseList.push_back(UU); |
| 899 | continue; |
| 900 | } |
| 901 | if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U)) |
| 902 | if (IT->getIntrinsicID() == Intrinsic::lifetime_start || |
| 903 | IT->getIntrinsicID() == Intrinsic::lifetime_end) |
| 904 | continue; |
| 905 | |
| 906 | if (U != C && U != cpy) |
| 907 | return false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 908 | } |
| 909 | |
Nick Lewycky | 703e488 | 2014-07-14 18:52:02 +0000 | [diff] [blame] | 910 | // Check that src isn't captured by the called function since the |
| 911 | // transformation can cause aliasing issues in that case. |
| 912 | for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) |
| 913 | if (CS.getArgument(i) == cpySrc && !CS.doesNotCapture(i)) |
| 914 | return false; |
| 915 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 916 | // Since we're changing the parameter to the callsite, we need to make sure |
| 917 | // that what would be the new parameter dominates the callsite. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 918 | DominatorTree &DT = LookupDomTree(); |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 919 | if (Instruction *cpyDestInst = dyn_cast<Instruction>(cpyDest)) |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 920 | if (!DT.dominates(cpyDestInst, C)) |
| 921 | return false; |
| 922 | |
| 923 | // In addition to knowing that the call does not access src in some |
| 924 | // unexpected manner, for example via a global, which we deduce from |
| 925 | // the use analysis, we also need to know that it does not sneakily |
| 926 | // access dest. We rely on AA to figure this out for us. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 927 | AliasAnalysis &AA = LookupAliasAnalysis(); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 928 | ModRefInfo MR = AA.getModRefInfo(C, cpyDest, srcSize); |
Chad Rosier | a968caf | 2012-05-14 20:35:04 +0000 | [diff] [blame] | 929 | // If necessary, perform additional analysis. |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 930 | if (MR != MRI_NoModRef) |
Chad Rosier | a968caf | 2012-05-14 20:35:04 +0000 | [diff] [blame] | 931 | MR = AA.callCapturesBefore(C, cpyDest, srcSize, &DT); |
Chandler Carruth | 194f59c | 2015-07-22 23:15:57 +0000 | [diff] [blame] | 932 | if (MR != MRI_NoModRef) |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 933 | return false; |
| 934 | |
Fiona Glaser | a9bd572 | 2017-03-14 22:37:38 +0000 | [diff] [blame] | 935 | // We can't create address space casts here because we don't know if they're |
| 936 | // safe for the target. |
| 937 | if (cpySrc->getType()->getPointerAddressSpace() != |
| 938 | cpyDest->getType()->getPointerAddressSpace()) |
| 939 | return false; |
| 940 | for (unsigned i = 0; i < CS.arg_size(); ++i) |
| 941 | if (CS.getArgument(i)->stripPointerCasts() == cpySrc && |
| 942 | cpySrc->getType()->getPointerAddressSpace() != |
| 943 | CS.getArgument(i)->getType()->getPointerAddressSpace()) |
| 944 | return false; |
| 945 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 946 | // All the checks have passed, so do the transformation. |
Owen Anderson | d071a87 | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 947 | bool changedArgument = false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 948 | for (unsigned i = 0; i < CS.arg_size(); ++i) |
Owen Anderson | 38099c1 | 2008-06-01 22:26:26 +0000 | [diff] [blame] | 949 | if (CS.getArgument(i)->stripPointerCasts() == cpySrc) { |
Duncan Sands | a6d2001 | 2012-10-04 13:53:21 +0000 | [diff] [blame] | 950 | Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest |
| 951 | : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(), |
| 952 | cpyDest->getName(), C); |
Owen Anderson | d071a87 | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 953 | changedArgument = true; |
Duncan Sands | a6d2001 | 2012-10-04 13:53:21 +0000 | [diff] [blame] | 954 | if (CS.getArgument(i)->getType() == Dest->getType()) |
| 955 | CS.setArgument(i, Dest); |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 956 | else |
Duncan Sands | a6d2001 | 2012-10-04 13:53:21 +0000 | [diff] [blame] | 957 | CS.setArgument(i, CastInst::CreatePointerCast(Dest, |
| 958 | CS.getArgument(i)->getType(), Dest->getName(), C)); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 959 | } |
| 960 | |
Owen Anderson | d071a87 | 2008-06-01 21:52:16 +0000 | [diff] [blame] | 961 | if (!changedArgument) |
| 962 | return false; |
| 963 | |
Duncan Sands | c6ada69 | 2012-10-04 10:54:40 +0000 | [diff] [blame] | 964 | // If the destination wasn't sufficiently aligned then increase its alignment. |
| 965 | if (!isDestSufficientlyAligned) { |
| 966 | assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!"); |
| 967 | cast<AllocaInst>(cpyDest)->setAlignment(srcAlign); |
| 968 | } |
| 969 | |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 970 | // Drop any cached information about the call, because we may have changed |
| 971 | // its dependence information by changing its parameter. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 972 | MD->removeInstruction(C); |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 973 | |
Bjorn Steinbrink | 71bf3b8 | 2015-02-07 17:54:36 +0000 | [diff] [blame] | 974 | // Update AA metadata |
| 975 | // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be |
| 976 | // handled here, but combineMetadata doesn't support them yet |
Piotr Padlewski | dc9b2cf | 2015-10-02 22:12:22 +0000 | [diff] [blame] | 977 | unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope, |
| 978 | LLVMContext::MD_noalias, |
| 979 | LLVMContext::MD_invariant_group}; |
Bjorn Steinbrink | 71bf3b8 | 2015-02-07 17:54:36 +0000 | [diff] [blame] | 980 | combineMetadata(C, cpy, KnownIDs); |
| 981 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 982 | // Remove the memcpy. |
| 983 | MD->removeInstruction(cpy); |
Dan Gohman | d2d1ae1 | 2010-06-22 15:08:57 +0000 | [diff] [blame] | 984 | ++NumMemCpyInstr; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 985 | |
| 986 | return true; |
| 987 | } |
| 988 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 989 | /// We've found that the (upward scanning) memory dependence of memcpy 'M' is |
| 990 | /// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 991 | bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M, |
| 992 | MemCpyInst *MDep) { |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 993 | // We can only transforms memcpy's where the dest of one is the source of the |
| 994 | // other. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 995 | if (M->getSource() != MDep->getDest() || MDep->isVolatile()) |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 996 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 997 | |
Chris Lattner | fd51c52 | 2010-12-09 07:39:50 +0000 | [diff] [blame] | 998 | // If dep instruction is reading from our current input, then it is a noop |
| 999 | // transfer and substituting the input won't change this instruction. Just |
| 1000 | // ignore the input and let someone else zap MDep. This handles cases like: |
| 1001 | // memcpy(a <- a) |
| 1002 | // memcpy(b <- a) |
| 1003 | if (M->getSource() == MDep->getSource()) |
| 1004 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1005 | |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 1006 | // Second, the length of the memcpy's must be the same, or the preceding one |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 1007 | // must be larger than the following one. |
Dan Gohman | 19e30d5 | 2011-01-21 22:07:57 +0000 | [diff] [blame] | 1008 | ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength()); |
| 1009 | ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength()); |
| 1010 | if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue()) |
| 1011 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1012 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1013 | AliasAnalysis &AA = LookupAliasAnalysis(); |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1014 | |
| 1015 | // Verify that the copied-from memory doesn't change in between the two |
| 1016 | // transfers. For example, in: |
| 1017 | // memcpy(a <- b) |
| 1018 | // *b = 42; |
| 1019 | // memcpy(c <- a) |
| 1020 | // It would be invalid to transform the second memcpy into memcpy(c <- b). |
| 1021 | // |
| 1022 | // TODO: If the code between M and MDep is transparent to the destination "c", |
| 1023 | // then we could still perform the xform by moving M up to the first memcpy. |
| 1024 | // |
| 1025 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 1026 | // not just the defining memcpy. |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1027 | MemDepResult SourceDep = |
| 1028 | MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false, |
| 1029 | M->getIterator(), M->getParent()); |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1030 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 1031 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1032 | |
Chris Lattner | 731caac | 2010-11-18 08:00:57 +0000 | [diff] [blame] | 1033 | // If the dest of the second might alias the source of the first, then the |
| 1034 | // source and dest might overlap. We still want to eliminate the intermediate |
| 1035 | // value, but we have to generate a memmove instead of memcpy. |
Chris Lattner | 6cf8d6c | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 1036 | bool UseMemMove = false; |
Chandler Carruth | 70c61c1 | 2015-06-04 02:03:15 +0000 | [diff] [blame] | 1037 | if (!AA.isNoAlias(MemoryLocation::getForDest(M), |
| 1038 | MemoryLocation::getForSource(MDep))) |
Chris Lattner | 6cf8d6c | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 1039 | UseMemMove = true; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1040 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1041 | // If all checks passed, then we can transform M. |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1042 | |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1043 | // Make sure to use the lesser of the alignment of the source and the dest |
| 1044 | // since we're changing where we're reading from, but don't want to increase |
| 1045 | // the alignment past what can be read from or written to. |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 1046 | // TODO: Is this worth it if we're creating a less aligned memcpy? For |
| 1047 | // example we could be moving from movaps -> movq on x86. |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1048 | unsigned Align = std::min(MDep->getAlignment(), M->getAlignment()); |
| 1049 | |
Chris Lattner | 6cf8d6c | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 1050 | IRBuilder<> Builder(M); |
| 1051 | if (UseMemMove) |
| 1052 | Builder.CreateMemMove(M->getRawDest(), MDep->getRawSource(), M->getLength(), |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1053 | Align, M->isVolatile()); |
Chris Lattner | 6cf8d6c | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 1054 | else |
| 1055 | Builder.CreateMemCpy(M->getRawDest(), MDep->getRawSource(), M->getLength(), |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1056 | Align, M->isVolatile()); |
Chris Lattner | 1385dff | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 1057 | |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1058 | // Remove the instruction we're replacing. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1059 | MD->removeInstruction(M); |
Chris Lattner | 1385dff | 2010-11-18 08:07:09 +0000 | [diff] [blame] | 1060 | M->eraseFromParent(); |
| 1061 | ++NumMemCpyInstr; |
| 1062 | return true; |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 1063 | } |
| 1064 | |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1065 | /// We've found that the (upward scanning) memory dependence of \p MemCpy is |
| 1066 | /// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that |
| 1067 | /// weren't copied over by \p MemCpy. |
| 1068 | /// |
| 1069 | /// In other words, transform: |
| 1070 | /// \code |
| 1071 | /// memset(dst, c, dst_size); |
| 1072 | /// memcpy(dst, src, src_size); |
| 1073 | /// \endcode |
| 1074 | /// into: |
| 1075 | /// \code |
| 1076 | /// memcpy(dst, src, src_size); |
| 1077 | /// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size); |
| 1078 | /// \endcode |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1079 | bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy, |
| 1080 | MemSetInst *MemSet) { |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1081 | // We can only transform memset/memcpy with the same destination. |
| 1082 | if (MemSet->getDest() != MemCpy->getDest()) |
| 1083 | return false; |
| 1084 | |
Ahmed Bougacha | 97876fa | 2015-05-21 01:43:39 +0000 | [diff] [blame] | 1085 | // Check that there are no other dependencies on the memset destination. |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1086 | MemDepResult DstDepInfo = |
| 1087 | MD->getPointerDependencyFrom(MemoryLocation::getForDest(MemSet), false, |
| 1088 | MemCpy->getIterator(), MemCpy->getParent()); |
Ahmed Bougacha | 97876fa | 2015-05-21 01:43:39 +0000 | [diff] [blame] | 1089 | if (DstDepInfo.getInst() != MemSet) |
| 1090 | return false; |
| 1091 | |
Ahmed Bougacha | 9692e30 | 2015-04-21 21:28:33 +0000 | [diff] [blame] | 1092 | // Use the same i8* dest as the memcpy, killing the memset dest if different. |
| 1093 | Value *Dest = MemCpy->getRawDest(); |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1094 | Value *DestSize = MemSet->getLength(); |
| 1095 | Value *SrcSize = MemCpy->getLength(); |
| 1096 | |
| 1097 | // By default, create an unaligned memset. |
| 1098 | unsigned Align = 1; |
| 1099 | // If Dest is aligned, and SrcSize is constant, use the minimum alignment |
| 1100 | // of the sum. |
| 1101 | const unsigned DestAlign = |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1102 | std::max(MemSet->getAlignment(), MemCpy->getAlignment()); |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1103 | if (DestAlign > 1) |
| 1104 | if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize)) |
| 1105 | Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign); |
| 1106 | |
Ahmed Bougacha | 97876fa | 2015-05-21 01:43:39 +0000 | [diff] [blame] | 1107 | IRBuilder<> Builder(MemCpy); |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1108 | |
Ahmed Bougacha | 05b72c1 | 2015-04-18 23:06:04 +0000 | [diff] [blame] | 1109 | // If the sizes have different types, zext the smaller one. |
Ahmed Bougacha | 7216ccc | 2015-04-18 17:57:41 +0000 | [diff] [blame] | 1110 | if (DestSize->getType() != SrcSize->getType()) { |
Ahmed Bougacha | 05b72c1 | 2015-04-18 23:06:04 +0000 | [diff] [blame] | 1111 | if (DestSize->getType()->getIntegerBitWidth() > |
| 1112 | SrcSize->getType()->getIntegerBitWidth()) |
| 1113 | SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType()); |
| 1114 | else |
| 1115 | DestSize = Builder.CreateZExt(DestSize, SrcSize->getType()); |
Ahmed Bougacha | 7216ccc | 2015-04-18 17:57:41 +0000 | [diff] [blame] | 1116 | } |
| 1117 | |
Benjamin Kramer | 1697d39 | 2016-11-07 17:47:28 +0000 | [diff] [blame] | 1118 | Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize); |
| 1119 | Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize); |
| 1120 | Value *MemsetLen = Builder.CreateSelect( |
| 1121 | Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff); |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1122 | Builder.CreateMemSet(Builder.CreateGEP(Dest, SrcSize), MemSet->getOperand(1), |
| 1123 | MemsetLen, Align); |
| 1124 | |
| 1125 | MD->removeInstruction(MemSet); |
| 1126 | MemSet->eraseFromParent(); |
| 1127 | return true; |
| 1128 | } |
Chris Lattner | 7e9b2ea | 2010-11-18 07:02:37 +0000 | [diff] [blame] | 1129 | |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1130 | /// Transform memcpy to memset when its source was just memset. |
| 1131 | /// In other words, turn: |
| 1132 | /// \code |
| 1133 | /// memset(dst1, c, dst1_size); |
| 1134 | /// memcpy(dst2, dst1, dst2_size); |
| 1135 | /// \endcode |
| 1136 | /// into: |
| 1137 | /// \code |
| 1138 | /// memset(dst1, c, dst1_size); |
| 1139 | /// memset(dst2, c, dst2_size); |
| 1140 | /// \endcode |
| 1141 | /// When dst2_size <= dst1_size. |
| 1142 | /// |
| 1143 | /// The \p MemCpy must have a Constant length. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1144 | bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy, |
| 1145 | MemSetInst *MemSet) { |
Tim Shen | a3dbead | 2016-08-25 19:27:26 +0000 | [diff] [blame] | 1146 | AliasAnalysis &AA = LookupAliasAnalysis(); |
| 1147 | |
Tim Shen | 3ad8b43 | 2016-08-25 21:03:46 +0000 | [diff] [blame] | 1148 | // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and |
| 1149 | // memcpying from the same address. Otherwise it is hard to reason about. |
Tim Shen | a3dbead | 2016-08-25 19:27:26 +0000 | [diff] [blame] | 1150 | if (!AA.isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource())) |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1151 | return false; |
| 1152 | |
| 1153 | ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength()); |
| 1154 | ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength()); |
| 1155 | // Make sure the memcpy doesn't read any more than what the memset wrote. |
| 1156 | // Don't worry about sizes larger than i64. |
| 1157 | if (!MemSetSize || CopySize->getZExtValue() > MemSetSize->getZExtValue()) |
| 1158 | return false; |
| 1159 | |
Ahmed Bougacha | 0541c67 | 2015-05-21 00:08:35 +0000 | [diff] [blame] | 1160 | IRBuilder<> Builder(MemCpy); |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1161 | Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1), |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1162 | CopySize, MemCpy->getAlignment()); |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1163 | return true; |
| 1164 | } |
| 1165 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 1166 | /// Perform simplification of memcpy's. If we have memcpy A |
Gabor Greif | 62f0aac | 2010-07-28 22:50:26 +0000 | [diff] [blame] | 1167 | /// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite |
| 1168 | /// B to be a memcpy from X to Z (or potentially a memmove, depending on |
| 1169 | /// circumstances). This allows later passes to remove the first memcpy |
| 1170 | /// altogether. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1171 | bool MemCpyOptPass::processMemCpy(MemCpyInst *M) { |
Nick Lewycky | 00703e7 | 2014-02-04 00:18:54 +0000 | [diff] [blame] | 1172 | // We can only optimize non-volatile memcpy's. |
| 1173 | if (M->isVolatile()) return false; |
Owen Anderson | 18e4fed | 2010-10-15 22:52:12 +0000 | [diff] [blame] | 1174 | |
Chris Lattner | bc4457e | 2010-12-09 07:45:45 +0000 | [diff] [blame] | 1175 | // If the source and destination of the memcpy are the same, then zap it. |
| 1176 | if (M->getSource() == M->getDest()) { |
| 1177 | MD->removeInstruction(M); |
| 1178 | M->eraseFromParent(); |
| 1179 | return false; |
| 1180 | } |
Benjamin Kramer | ea9152e | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 1181 | |
| 1182 | // If copying from a constant, try to turn the memcpy into a memset. |
Benjamin Kramer | b90b2f0 | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 1183 | if (GlobalVariable *GV = dyn_cast<GlobalVariable>(M->getSource())) |
Benjamin Kramer | 30342fb | 2010-12-26 15:23:45 +0000 | [diff] [blame] | 1184 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) |
Benjamin Kramer | b90b2f0 | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 1185 | if (Value *ByteVal = isBytewiseValue(GV->getInitializer())) { |
Chris Lattner | 6cf8d6c | 2010-12-26 22:57:41 +0000 | [diff] [blame] | 1186 | IRBuilder<> Builder(M); |
Nick Lewycky | 00703e7 | 2014-02-04 00:18:54 +0000 | [diff] [blame] | 1187 | Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(), |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1188 | M->getAlignment(), false); |
Benjamin Kramer | b90b2f0 | 2010-12-24 22:23:59 +0000 | [diff] [blame] | 1189 | MD->removeInstruction(M); |
| 1190 | M->eraseFromParent(); |
| 1191 | ++NumCpyToSet; |
| 1192 | return true; |
| 1193 | } |
Benjamin Kramer | ea9152e | 2010-12-24 21:17:12 +0000 | [diff] [blame] | 1194 | |
Ahmed Bougacha | b616966 | 2015-05-11 23:09:46 +0000 | [diff] [blame] | 1195 | MemDepResult DepInfo = MD->getDependency(M); |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1196 | |
| 1197 | // Try to turn a partially redundant memset + memcpy into |
| 1198 | // memcpy + smaller memset. We don't need the memcpy size for this. |
Ahmed Bougacha | b616966 | 2015-05-11 23:09:46 +0000 | [diff] [blame] | 1199 | if (DepInfo.isClobber()) |
| 1200 | if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst())) |
Ahmed Bougacha | 83f78a4 | 2015-04-17 22:20:57 +0000 | [diff] [blame] | 1201 | if (processMemSetMemCpyDependence(M, MDep)) |
| 1202 | return true; |
| 1203 | |
Nick Lewycky | 00703e7 | 2014-02-04 00:18:54 +0000 | [diff] [blame] | 1204 | // The optimizations after this point require the memcpy size. |
| 1205 | ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1206 | if (!CopySize) return false; |
Nick Lewycky | 00703e7 | 2014-02-04 00:18:54 +0000 | [diff] [blame] | 1207 | |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1208 | // There are four possible optimizations we can do for memcpy: |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1209 | // a) memcpy-memcpy xform which exposes redundance for DSE. |
| 1210 | // b) call-memcpy xform for return slot optimization. |
Nick Lewycky | 77d5fb4 | 2014-03-26 23:45:15 +0000 | [diff] [blame] | 1211 | // c) memcpy from freshly alloca'd space or space that has just started its |
| 1212 | // lifetime copies undefined data, and we can therefore eliminate the |
| 1213 | // memcpy in favor of the data that was already at the destination. |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1214 | // d) memcpy from a just-memset'd source can be turned into memset. |
Nick Lewycky | 0a7e9cc | 2011-10-16 20:13:32 +0000 | [diff] [blame] | 1215 | if (DepInfo.isClobber()) { |
| 1216 | if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) { |
| 1217 | if (performCallSlotOptzn(M, M->getDest(), M->getSource(), |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1218 | CopySize->getZExtValue(), M->getAlignment(), |
Duncan Sands | c6ada69 | 2012-10-04 10:54:40 +0000 | [diff] [blame] | 1219 | C)) { |
Nick Lewycky | 0a7e9cc | 2011-10-16 20:13:32 +0000 | [diff] [blame] | 1220 | MD->removeInstruction(M); |
| 1221 | M->eraseFromParent(); |
| 1222 | return true; |
| 1223 | } |
Chris Lattner | bc4457e | 2010-12-09 07:45:45 +0000 | [diff] [blame] | 1224 | } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1225 | } |
Ahmed Charles | 32e983e | 2012-02-13 06:30:56 +0000 | [diff] [blame] | 1226 | |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 1227 | MemoryLocation SrcLoc = MemoryLocation::getForSource(M); |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1228 | MemDepResult SrcDepInfo = MD->getPointerDependencyFrom( |
| 1229 | SrcLoc, true, M->getIterator(), M->getParent()); |
Ahmed Bougacha | b616966 | 2015-05-11 23:09:46 +0000 | [diff] [blame] | 1230 | |
Nick Lewycky | 0a7e9cc | 2011-10-16 20:13:32 +0000 | [diff] [blame] | 1231 | if (SrcDepInfo.isClobber()) { |
| 1232 | if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst())) |
Ahmed Bougacha | 15a31f6 | 2015-05-16 01:23:47 +0000 | [diff] [blame] | 1233 | return processMemCpyMemCpyDependence(M, MDep); |
Nick Lewycky | 9938494 | 2014-02-06 06:29:19 +0000 | [diff] [blame] | 1234 | } else if (SrcDepInfo.isDef()) { |
Nick Lewycky | 77d5fb4 | 2014-03-26 23:45:15 +0000 | [diff] [blame] | 1235 | Instruction *I = SrcDepInfo.getInst(); |
| 1236 | bool hasUndefContents = false; |
| 1237 | |
| 1238 | if (isa<AllocaInst>(I)) { |
| 1239 | hasUndefContents = true; |
| 1240 | } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { |
| 1241 | if (II->getIntrinsicID() == Intrinsic::lifetime_start) |
| 1242 | if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0))) |
| 1243 | if (LTSize->getZExtValue() >= CopySize->getZExtValue()) |
| 1244 | hasUndefContents = true; |
| 1245 | } |
| 1246 | |
| 1247 | if (hasUndefContents) { |
Nick Lewycky | 9938494 | 2014-02-06 06:29:19 +0000 | [diff] [blame] | 1248 | MD->removeInstruction(M); |
| 1249 | M->eraseFromParent(); |
| 1250 | ++NumMemCpyInstr; |
| 1251 | return true; |
| 1252 | } |
Nick Lewycky | 0a7e9cc | 2011-10-16 20:13:32 +0000 | [diff] [blame] | 1253 | } |
| 1254 | |
Ahmed Bougacha | f8fa3b8 | 2015-05-16 01:32:26 +0000 | [diff] [blame] | 1255 | if (SrcDepInfo.isClobber()) |
| 1256 | if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst())) |
| 1257 | if (performMemCpyToMemSetOptzn(M, MDep)) { |
| 1258 | MD->removeInstruction(M); |
| 1259 | M->eraseFromParent(); |
| 1260 | ++NumCpyToSet; |
| 1261 | return true; |
| 1262 | } |
| 1263 | |
Owen Anderson | ad5367f | 2008-04-29 21:51:00 +0000 | [diff] [blame] | 1264 | return false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1265 | } |
| 1266 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 1267 | /// Transforms memmove calls to memcpy calls when the src/dst are guaranteed |
| 1268 | /// not to alias. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1269 | bool MemCpyOptPass::processMemMove(MemMoveInst *M) { |
| 1270 | AliasAnalysis &AA = LookupAliasAnalysis(); |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1271 | |
David L. Jones | d21529f | 2017-01-23 23:16:46 +0000 | [diff] [blame] | 1272 | if (!TLI->has(LibFunc_memmove)) |
Chris Lattner | 23f61a0 | 2011-05-01 18:27:11 +0000 | [diff] [blame] | 1273 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1274 | |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1275 | // See if the pointers alias. |
Chandler Carruth | 70c61c1 | 2015-06-04 02:03:15 +0000 | [diff] [blame] | 1276 | if (!AA.isNoAlias(MemoryLocation::getForDest(M), |
| 1277 | MemoryLocation::getForSource(M))) |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1278 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1279 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1280 | DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *M |
| 1281 | << "\n"); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1282 | |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1283 | // If not, then we know we can transform this. |
Jay Foad | b804a2b | 2011-07-12 14:06:48 +0000 | [diff] [blame] | 1284 | Type *ArgTys[3] = { M->getRawDest()->getType(), |
| 1285 | M->getRawSource()->getType(), |
| 1286 | M->getLength()->getType() }; |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1287 | M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(), |
| 1288 | Intrinsic::memcpy, ArgTys)); |
Duncan Sands | 0edc710 | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 1289 | |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1290 | // MemDep may have over conservative information about this instruction, just |
| 1291 | // conservatively flush it from the cache. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1292 | MD->removeInstruction(M); |
Duncan Sands | 0edc710 | 2009-09-03 13:37:16 +0000 | [diff] [blame] | 1293 | |
| 1294 | ++NumMoveToCpy; |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1295 | return true; |
| 1296 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1297 | |
Sanjay Patel | a75c41e | 2015-08-13 22:53:20 +0000 | [diff] [blame] | 1298 | /// This is called on every byval argument in call sites. |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1299 | bool MemCpyOptPass::processByValArgument(CallSite CS, unsigned ArgNo) { |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1300 | const DataLayout &DL = CS.getCaller()->getParent()->getDataLayout(); |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1301 | // Find out what feeds this byval argument. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1302 | Value *ByValArg = CS.getArgument(ArgNo); |
Nick Lewycky | c585de6 | 2011-10-12 00:14:31 +0000 | [diff] [blame] | 1303 | Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType(); |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1304 | uint64_t ByValSize = DL.getTypeAllocSize(ByValTy); |
Chandler Carruth | ac80dc7 | 2015-06-17 07:18:54 +0000 | [diff] [blame] | 1305 | MemDepResult DepInfo = MD->getPointerDependencyFrom( |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1306 | MemoryLocation(ByValArg, ByValSize), true, |
| 1307 | CS.getInstruction()->getIterator(), CS.getInstruction()->getParent()); |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1308 | if (!DepInfo.isClobber()) |
| 1309 | return false; |
| 1310 | |
| 1311 | // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by |
| 1312 | // a memcpy, see if we can byval from the source of the memcpy instead of the |
| 1313 | // result. |
| 1314 | MemCpyInst *MDep = dyn_cast<MemCpyInst>(DepInfo.getInst()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1315 | if (!MDep || MDep->isVolatile() || |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1316 | ByValArg->stripPointerCasts() != MDep->getDest()) |
| 1317 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1318 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1319 | // The length of the memcpy must be larger or equal to the size of the byval. |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1320 | ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength()); |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1321 | if (!C1 || C1->getValue().getZExtValue() < ByValSize) |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1322 | return false; |
| 1323 | |
Chris Lattner | 83791ce | 2011-05-23 00:03:39 +0000 | [diff] [blame] | 1324 | // Get the alignment of the byval. If the call doesn't specify the alignment, |
| 1325 | // then it is some target specific value that we can't know. |
Reid Kleckner | 859f8b5 | 2017-04-28 20:34:27 +0000 | [diff] [blame^] | 1326 | unsigned ByValAlign = CS.getParamAlignment(ArgNo); |
Chris Lattner | 83791ce | 2011-05-23 00:03:39 +0000 | [diff] [blame] | 1327 | if (ByValAlign == 0) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1328 | |
Chris Lattner | 83791ce | 2011-05-23 00:03:39 +0000 | [diff] [blame] | 1329 | // If it is greater than the memcpy, then we check to see if we can force the |
| 1330 | // source of the memcpy to the alignment we need. If we fail, we bail out. |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1331 | AssumptionCache &AC = LookupAssumptionCache(); |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1332 | DominatorTree &DT = LookupDomTree(); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1333 | if (MDep->getAlignment() < ByValAlign && |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1334 | getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1335 | CS.getInstruction(), &AC, &DT) < ByValAlign) |
Chris Lattner | 83791ce | 2011-05-23 00:03:39 +0000 | [diff] [blame] | 1336 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1337 | |
Matt Arsenault | daa0887 | 2017-04-10 19:00:25 +0000 | [diff] [blame] | 1338 | // The address space of the memcpy source must match the byval argument |
| 1339 | if (MDep->getSource()->getType()->getPointerAddressSpace() != |
| 1340 | ByValArg->getType()->getPointerAddressSpace()) |
| 1341 | return false; |
| 1342 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1343 | // Verify that the copied-from memory doesn't change in between the memcpy and |
| 1344 | // the byval call. |
| 1345 | // memcpy(a <- b) |
| 1346 | // *b = 42; |
| 1347 | // foo(*a) |
| 1348 | // It would be invalid to transform the second memcpy into foo(*b). |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1349 | // |
| 1350 | // NOTE: This is conservative, it will stop on any read from the source loc, |
| 1351 | // not just the defining memcpy. |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1352 | MemDepResult SourceDep = MD->getPointerDependencyFrom( |
| 1353 | MemoryLocation::getForSource(MDep), false, |
| 1354 | CS.getInstruction()->getIterator(), MDep->getParent()); |
Chris Lattner | 5957229 | 2010-11-21 08:06:10 +0000 | [diff] [blame] | 1355 | if (!SourceDep.isClobber() || SourceDep.getInst() != MDep) |
| 1356 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1357 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1358 | Value *TmpCast = MDep->getSource(); |
| 1359 | if (MDep->getSource()->getType() != ByValArg->getType()) |
| 1360 | TmpCast = new BitCastInst(MDep->getSource(), ByValArg->getType(), |
| 1361 | "tmpcast", CS.getInstruction()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1362 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1363 | DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n" |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1364 | << " " << *MDep << "\n" |
| 1365 | << " " << *CS.getInstruction() << "\n"); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1366 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1367 | // Otherwise we're good! Update the byval argument. |
| 1368 | CS.setArgument(ArgNo, TmpCast); |
| 1369 | ++NumMemCpyInstr; |
| 1370 | return true; |
| 1371 | } |
| 1372 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1373 | /// Executes one iteration of MemCpyOptPass. |
| 1374 | bool MemCpyOptPass::iterateOnFunction(Function &F) { |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1375 | bool MadeChange = false; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1376 | |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1377 | // Walk all instruction in the function. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1378 | for (BasicBlock &BB : F) { |
| 1379 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1380 | // Avoid invalidating the iterator. |
Duncan P. N. Exon Smith | be4d8cb | 2015-10-13 19:26:58 +0000 | [diff] [blame] | 1381 | Instruction *I = &*BI++; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1382 | |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1383 | bool RepeatInstruction = false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1384 | |
Owen Anderson | 6a7355c | 2008-04-21 07:45:10 +0000 | [diff] [blame] | 1385 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1386 | MadeChange |= processStore(SI, BI); |
Chris Lattner | 9a1d63b | 2011-01-08 21:19:19 +0000 | [diff] [blame] | 1387 | else if (MemSetInst *M = dyn_cast<MemSetInst>(I)) |
| 1388 | RepeatInstruction = processMemSet(M, BI); |
| 1389 | else if (MemCpyInst *M = dyn_cast<MemCpyInst>(I)) |
Tim Northover | 3961735 | 2016-05-10 21:49:40 +0000 | [diff] [blame] | 1390 | RepeatInstruction = processMemCpy(M); |
Chris Lattner | 9a1d63b | 2011-01-08 21:19:19 +0000 | [diff] [blame] | 1391 | else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I)) |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1392 | RepeatInstruction = processMemMove(M); |
Benjamin Kramer | 3a09ef6 | 2015-04-10 14:50:08 +0000 | [diff] [blame] | 1393 | else if (auto CS = CallSite(I)) { |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1394 | for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) |
Nick Lewycky | 612d70b | 2011-11-20 19:09:04 +0000 | [diff] [blame] | 1395 | if (CS.isByValArgument(i)) |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1396 | MadeChange |= processByValArgument(CS, i); |
| 1397 | } |
| 1398 | |
| 1399 | // Reprocess the instruction if desired. |
| 1400 | if (RepeatInstruction) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1401 | if (BI != BB.begin()) |
| 1402 | --BI; |
Chris Lattner | 58f9f58 | 2010-11-21 00:28:59 +0000 | [diff] [blame] | 1403 | MadeChange = true; |
Chris Lattner | 1145e33 | 2009-09-01 17:56:32 +0000 | [diff] [blame] | 1404 | } |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1405 | } |
| 1406 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1407 | |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1408 | return MadeChange; |
Owen Anderson | ef9a6fd | 2008-04-09 08:23:16 +0000 | [diff] [blame] | 1409 | } |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1410 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1411 | PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) { |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1412 | auto &MD = AM.getResult<MemoryDependenceAnalysis>(F); |
| 1413 | auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); |
| 1414 | |
| 1415 | auto LookupAliasAnalysis = [&]() -> AliasAnalysis & { |
| 1416 | return AM.getResult<AAManager>(F); |
| 1417 | }; |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1418 | auto LookupAssumptionCache = [&]() -> AssumptionCache & { |
| 1419 | return AM.getResult<AssumptionAnalysis>(F); |
| 1420 | }; |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1421 | auto LookupDomTree = [&]() -> DominatorTree & { |
| 1422 | return AM.getResult<DominatorTreeAnalysis>(F); |
| 1423 | }; |
| 1424 | |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1425 | bool MadeChange = runImpl(F, &MD, &TLI, LookupAliasAnalysis, |
| 1426 | LookupAssumptionCache, LookupDomTree); |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1427 | if (!MadeChange) |
| 1428 | return PreservedAnalyses::all(); |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 1429 | |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1430 | PreservedAnalyses PA; |
Chandler Carruth | ca68a3e | 2017-01-15 06:32:49 +0000 | [diff] [blame] | 1431 | PA.preserveSet<CFGAnalyses>(); |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1432 | PA.preserve<GlobalsAA>(); |
| 1433 | PA.preserve<MemoryDependenceAnalysis>(); |
| 1434 | return PA; |
| 1435 | } |
| 1436 | |
| 1437 | bool MemCpyOptPass::runImpl( |
| 1438 | Function &F, MemoryDependenceResults *MD_, TargetLibraryInfo *TLI_, |
| 1439 | std::function<AliasAnalysis &()> LookupAliasAnalysis_, |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1440 | std::function<AssumptionCache &()> LookupAssumptionCache_, |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1441 | std::function<DominatorTree &()> LookupDomTree_) { |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1442 | bool MadeChange = false; |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1443 | MD = MD_; |
| 1444 | TLI = TLI_; |
Benjamin Kramer | 1afc1de | 2016-06-17 20:41:14 +0000 | [diff] [blame] | 1445 | LookupAliasAnalysis = std::move(LookupAliasAnalysis_); |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1446 | LookupAssumptionCache = std::move(LookupAssumptionCache_); |
Benjamin Kramer | 1afc1de | 2016-06-17 20:41:14 +0000 | [diff] [blame] | 1447 | LookupDomTree = std::move(LookupDomTree_); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1448 | |
Chris Lattner | 23f61a0 | 2011-05-01 18:27:11 +0000 | [diff] [blame] | 1449 | // If we don't have at least memset and memcpy, there is little point of doing |
| 1450 | // anything here. These are required by a freestanding implementation, so if |
| 1451 | // even they are disabled, there is no point in trying hard. |
David L. Jones | d21529f | 2017-01-23 23:16:46 +0000 | [diff] [blame] | 1452 | if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy)) |
Chris Lattner | 23f61a0 | 2011-05-01 18:27:11 +0000 | [diff] [blame] | 1453 | return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1454 | |
Eugene Zelenko | 34c2327 | 2017-01-18 00:57:48 +0000 | [diff] [blame] | 1455 | while (true) { |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1456 | if (!iterateOnFunction(F)) |
| 1457 | break; |
| 1458 | MadeChange = true; |
| 1459 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1460 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1461 | MD = nullptr; |
Chris Lattner | b5557a7 | 2009-09-01 17:09:55 +0000 | [diff] [blame] | 1462 | return MadeChange; |
| 1463 | } |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1464 | |
| 1465 | /// This is the main transformation entry point for a function. |
| 1466 | bool MemCpyOptLegacyPass::runOnFunction(Function &F) { |
| 1467 | if (skipFunction(F)) |
| 1468 | return false; |
| 1469 | |
| 1470 | auto *MD = &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(); |
| 1471 | auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
| 1472 | |
| 1473 | auto LookupAliasAnalysis = [this]() -> AliasAnalysis & { |
| 1474 | return getAnalysis<AAResultsWrapperPass>().getAAResults(); |
| 1475 | }; |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1476 | auto LookupAssumptionCache = [this, &F]() -> AssumptionCache & { |
| 1477 | return getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); |
| 1478 | }; |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1479 | auto LookupDomTree = [this]() -> DominatorTree & { |
| 1480 | return getAnalysis<DominatorTreeWrapperPass>().getDomTree(); |
| 1481 | }; |
| 1482 | |
Daniel Jasper | aec2fa3 | 2016-12-19 08:22:17 +0000 | [diff] [blame] | 1483 | return Impl.runImpl(F, MD, TLI, LookupAliasAnalysis, LookupAssumptionCache, |
| 1484 | LookupDomTree); |
Sean Silva | 6347df0 | 2016-06-14 02:44:55 +0000 | [diff] [blame] | 1485 | } |