OSDN Git Service

gn build: Merge r364387
[android-x86/external-llvm.git] / lib / Transforms / Scalar / ExpandMemCmp.cpp
1 //===--- ExpandMemCmp.cpp - Expand memcmp() to load/stores ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass tries to expand memcmp() calls into optimally-sized loads and
10 // compares for the target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/ConstantFolding.h"
16 #include "llvm/Analysis/DomTreeUpdater.h"
17 #include "llvm/Analysis/GlobalsModRef.h"
18 #include "llvm/Analysis/TargetLibraryInfo.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/TargetSubtargetInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/Transforms/Scalar.h"
25
26 using namespace llvm;
27
28 #define DEBUG_TYPE "expandmemcmp"
29
30 STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
31 STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
32 STATISTIC(NumMemCmpGreaterThanMax,
33           "Number of memcmp calls with size greater than max size");
34 STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
35
36 static cl::opt<unsigned> MemCmpEqZeroNumLoadsPerBlock(
37     "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
38     cl::desc("The number of loads per basic block for inline expansion of "
39              "memcmp that is only being compared against zero."));
40
41 static cl::opt<unsigned> MaxLoadsPerMemcmp(
42     "max-loads-per-memcmp", cl::Hidden,
43     cl::desc("Set maximum number of loads used in expanded memcmp"));
44
45 static cl::opt<unsigned> MaxLoadsPerMemcmpOptSize(
46     "max-loads-per-memcmp-opt-size", cl::Hidden,
47     cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
48
49 namespace {
50
51 // This class provides helper functions to expand a memcmp library call into an
52 // inline expansion.
53 class MemCmpExpansion {
54   struct ResultBlock {
55     BasicBlock *BB = nullptr;
56     PHINode *PhiSrc1 = nullptr;
57     PHINode *PhiSrc2 = nullptr;
58
59     ResultBlock() = default;
60   };
61
62   CallInst *const CI;
63   ResultBlock ResBlock;
64   const uint64_t Size;
65   unsigned MaxLoadSize;
66   uint64_t NumLoadsNonOneByte;
67   const uint64_t NumLoadsPerBlockForZeroCmp;
68   std::vector<BasicBlock *> LoadCmpBlocks;
69   BasicBlock *EndBlock = nullptr;
70   PHINode *PhiRes;
71   const bool IsUsedForZeroCmp;
72   const DataLayout &DL;
73   IRBuilder<> Builder;
74   DomTreeUpdater DTU;
75   // Represents the decomposition in blocks of the expansion. For example,
76   // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
77   // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {32, 1}.
78   struct LoadEntry {
79     LoadEntry(unsigned LoadSize, uint64_t Offset)
80         : LoadSize(LoadSize), Offset(Offset) {}
81
82     // The size of the load for this block, in bytes.
83     unsigned LoadSize;
84     // The offset of this load from the base pointer, in bytes.
85     uint64_t Offset;
86   };
87   using LoadEntryVector = SmallVector<LoadEntry, 8>;
88   LoadEntryVector LoadSequence;
89
90   void createLoadCmpBlocks();
91   void createResultBlock();
92   void setupResultBlockPHINodes();
93   void setupEndBlockPHINodes();
94   Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
95   void emitLoadCompareBlock(unsigned BlockIndex);
96   void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
97                                          unsigned &LoadIndex);
98   void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
99   void emitMemCmpResultBlock();
100   Value *getMemCmpExpansionZeroCase();
101   Value *getMemCmpEqZeroOneBlock();
102   Value *getMemCmpOneBlock();
103   Value *getPtrToElementAtOffset(Value *Source, Type *LoadSizeType,
104                                  uint64_t OffsetBytes);
105
106   static LoadEntryVector
107   computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
108                             unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
109   static LoadEntryVector
110   computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
111                                  unsigned MaxNumLoads,
112                                  unsigned &NumLoadsNonOneByte);
113
114 public:
115   MemCmpExpansion(CallInst *CI, uint64_t Size,
116                   const TargetTransformInfo::MemCmpExpansionOptions &Options,
117                   const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
118                   DominatorTree *DT);
119
120   unsigned getNumBlocks();
121   uint64_t getNumLoads() const { return LoadSequence.size(); }
122
123   Value *getMemCmpExpansion();
124 };
125
126 MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
127     uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
128     const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
129   NumLoadsNonOneByte = 0;
130   LoadEntryVector LoadSequence;
131   uint64_t Offset = 0;
132   while (Size && !LoadSizes.empty()) {
133     const unsigned LoadSize = LoadSizes.front();
134     const uint64_t NumLoadsForThisSize = Size / LoadSize;
135     if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
136       // Do not expand if the total number of loads is larger than what the
137       // target allows. Note that it's important that we exit before completing
138       // the expansion to avoid using a ton of memory to store the expansion for
139       // large sizes.
140       return {};
141     }
142     if (NumLoadsForThisSize > 0) {
143       for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
144         LoadSequence.push_back({LoadSize, Offset});
145         Offset += LoadSize;
146       }
147       if (LoadSize > 1)
148         ++NumLoadsNonOneByte;
149       Size = Size % LoadSize;
150     }
151     LoadSizes = LoadSizes.drop_front();
152   }
153   return LoadSequence;
154 }
155
156 MemCmpExpansion::LoadEntryVector
157 MemCmpExpansion::computeOverlappingLoadSequence(uint64_t Size,
158                                                 const unsigned MaxLoadSize,
159                                                 const unsigned MaxNumLoads,
160                                                 unsigned &NumLoadsNonOneByte) {
161   // These are already handled by the greedy approach.
162   if (Size < 2 || MaxLoadSize < 2)
163     return {};
164
165   // We try to do as many non-overlapping loads as possible starting from the
166   // beginning.
167   const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
168   assert(NumNonOverlappingLoads && "there must be at least one load");
169   // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
170   // an overlapping load.
171   Size = Size - NumNonOverlappingLoads * MaxLoadSize;
172   // Bail if we do not need an overloapping store, this is already handled by
173   // the greedy approach.
174   if (Size == 0)
175     return {};
176   // Bail if the number of loads (non-overlapping + potential overlapping one)
177   // is larger than the max allowed.
178   if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
179     return {};
180
181   // Add non-overlapping loads.
182   LoadEntryVector LoadSequence;
183   uint64_t Offset = 0;
184   for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
185     LoadSequence.push_back({MaxLoadSize, Offset});
186     Offset += MaxLoadSize;
187   }
188
189   // Add the last overlapping load.
190   assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
191   LoadSequence.push_back({MaxLoadSize, Offset - (MaxLoadSize - Size)});
192   NumLoadsNonOneByte = 1;
193   return LoadSequence;
194 }
195
196 // Initialize the basic block structure required for expansion of memcmp call
197 // with given maximum load size and memcmp size parameter.
198 // This structure includes:
199 // 1. A list of load compare blocks - LoadCmpBlocks.
200 // 2. An EndBlock, split from original instruction point, which is the block to
201 // return from.
202 // 3. ResultBlock, block to branch to for early exit when a
203 // LoadCmpBlock finds a difference.
204 MemCmpExpansion::MemCmpExpansion(
205     CallInst *const CI, uint64_t Size,
206     const TargetTransformInfo::MemCmpExpansionOptions &Options,
207     const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
208     DominatorTree *DT)
209     : CI(CI), Size(Size), MaxLoadSize(0), NumLoadsNonOneByte(0),
210       NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
211       IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), Builder(CI),
212       DTU(DT, /*PostDominator*/ nullptr,
213           DomTreeUpdater::UpdateStrategy::Eager) {
214   assert(Size > 0 && "zero blocks");
215   // Scale the max size down if the target can load more bytes than we need.
216   llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
217   while (!LoadSizes.empty() && LoadSizes.front() > Size) {
218     LoadSizes = LoadSizes.drop_front();
219   }
220   assert(!LoadSizes.empty() && "cannot load Size bytes");
221   MaxLoadSize = LoadSizes.front();
222   // Compute the decomposition.
223   unsigned GreedyNumLoadsNonOneByte = 0;
224   LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
225                                            GreedyNumLoadsNonOneByte);
226   NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
227   assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
228   // If we allow overlapping loads and the load sequence is not already optimal,
229   // use overlapping loads.
230   if (Options.AllowOverlappingLoads &&
231       (LoadSequence.empty() || LoadSequence.size() > 2)) {
232     unsigned OverlappingNumLoadsNonOneByte = 0;
233     auto OverlappingLoads = computeOverlappingLoadSequence(
234         Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
235     if (!OverlappingLoads.empty() &&
236         (LoadSequence.empty() ||
237          OverlappingLoads.size() < LoadSequence.size())) {
238       LoadSequence = OverlappingLoads;
239       NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
240     }
241   }
242   assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
243 }
244
245 unsigned MemCmpExpansion::getNumBlocks() {
246   if (IsUsedForZeroCmp)
247     return getNumLoads() / NumLoadsPerBlockForZeroCmp +
248            (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
249   return getNumLoads();
250 }
251
252 void MemCmpExpansion::createLoadCmpBlocks() {
253   assert(ResBlock.BB && "ResBlock must be created before LoadCmpBlocks");
254   for (unsigned i = 0; i < getNumBlocks(); i++) {
255     BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
256                                         EndBlock->getParent(), EndBlock);
257     LoadCmpBlocks.push_back(BB);
258   }
259 }
260
261 void MemCmpExpansion::createResultBlock() {
262   assert(EndBlock && "EndBlock must be created before ResultBlock");
263   ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
264                                    EndBlock->getParent(), EndBlock);
265 }
266
267 /// Return a pointer to an element of type `LoadSizeType` at offset
268 /// `OffsetBytes`.
269 Value *MemCmpExpansion::getPtrToElementAtOffset(Value *Source,
270                                                 Type *LoadSizeType,
271                                                 uint64_t OffsetBytes) {
272   if (OffsetBytes > 0) {
273     auto *ByteType = Type::getInt8Ty(CI->getContext());
274     Source = Builder.CreateGEP(
275         ByteType, Builder.CreateBitCast(Source, ByteType->getPointerTo()),
276         ConstantInt::get(ByteType, OffsetBytes));
277   }
278   return Builder.CreateBitCast(Source, LoadSizeType->getPointerTo());
279 }
280
281 // This function creates the IR instructions for loading and comparing 1 byte.
282 // It loads 1 byte from each source of the memcmp parameters with the given
283 // GEPIndex. It then subtracts the two loaded values and adds this result to the
284 // final phi node for selecting the memcmp result.
285 void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
286                                                unsigned OffsetBytes) {
287   BasicBlock *const BB = LoadCmpBlocks[BlockIndex];
288   Builder.SetInsertPoint(BB);
289   Type *LoadSizeType = Type::getInt8Ty(CI->getContext());
290   Value *Source1 =
291       getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType, OffsetBytes);
292   Value *Source2 =
293       getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType, OffsetBytes);
294
295   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
296   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
297
298   LoadSrc1 = Builder.CreateZExt(LoadSrc1, Type::getInt32Ty(CI->getContext()));
299   LoadSrc2 = Builder.CreateZExt(LoadSrc2, Type::getInt32Ty(CI->getContext()));
300   Value *Diff = Builder.CreateSub(LoadSrc1, LoadSrc2);
301
302   PhiRes->addIncoming(Diff, LoadCmpBlocks[BlockIndex]);
303
304   if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
305     // Early exit branch if difference found to EndBlock. Otherwise, continue to
306     // next LoadCmpBlock,
307     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
308                                     ConstantInt::get(Diff->getType(), 0));
309     BasicBlock *const NextBB = LoadCmpBlocks[BlockIndex + 1];
310     BranchInst *CmpBr = BranchInst::Create(EndBlock, NextBB, Cmp);
311     Builder.Insert(CmpBr);
312     DTU.applyUpdates({{DominatorTree::Insert, BB, EndBlock},
313                       {DominatorTree::Insert, BB, NextBB}});
314   } else {
315     // The last block has an unconditional branch to EndBlock.
316     BranchInst *CmpBr = BranchInst::Create(EndBlock);
317     Builder.Insert(CmpBr);
318     DTU.applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
319   }
320 }
321
322 /// Generate an equality comparison for one or more pairs of loaded values.
323 /// This is used in the case where the memcmp() call is compared equal or not
324 /// equal to zero.
325 Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
326                                             unsigned &LoadIndex) {
327   assert(LoadIndex < getNumLoads() &&
328          "getCompareLoadPairs() called with no remaining loads");
329   std::vector<Value *> XorList, OrList;
330   Value *Diff = nullptr;
331
332   const unsigned NumLoads =
333       std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
334
335   // For a single-block expansion, start inserting before the memcmp call.
336   if (LoadCmpBlocks.empty())
337     Builder.SetInsertPoint(CI);
338   else
339     Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
340
341   Value *Cmp = nullptr;
342   // If we have multiple loads per block, we need to generate a composite
343   // comparison using xor+or. The type for the combinations is the largest load
344   // type.
345   IntegerType *const MaxLoadType =
346       NumLoads == 1 ? nullptr
347                     : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
348   for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
349     const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
350
351     IntegerType *LoadSizeType =
352         IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
353
354     Value *Source1 = getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType,
355                                              CurLoadEntry.Offset);
356     Value *Source2 = getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType,
357                                              CurLoadEntry.Offset);
358
359     // Get a constant or load a value for each source address.
360     Value *LoadSrc1 = nullptr;
361     if (auto *Source1C = dyn_cast<Constant>(Source1))
362       LoadSrc1 = ConstantFoldLoadFromConstPtr(Source1C, LoadSizeType, DL);
363     if (!LoadSrc1)
364       LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
365
366     Value *LoadSrc2 = nullptr;
367     if (auto *Source2C = dyn_cast<Constant>(Source2))
368       LoadSrc2 = ConstantFoldLoadFromConstPtr(Source2C, LoadSizeType, DL);
369     if (!LoadSrc2)
370       LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
371
372     if (NumLoads != 1) {
373       if (LoadSizeType != MaxLoadType) {
374         LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
375         LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
376       }
377       // If we have multiple loads per block, we need to generate a composite
378       // comparison using xor+or.
379       Diff = Builder.CreateXor(LoadSrc1, LoadSrc2);
380       Diff = Builder.CreateZExt(Diff, MaxLoadType);
381       XorList.push_back(Diff);
382     } else {
383       // If there's only one load per block, we just compare the loaded values.
384       Cmp = Builder.CreateICmpNE(LoadSrc1, LoadSrc2);
385     }
386   }
387
388   auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
389     std::vector<Value *> OutList;
390     for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
391       Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
392       OutList.push_back(Or);
393     }
394     if (InList.size() % 2 != 0)
395       OutList.push_back(InList.back());
396     return OutList;
397   };
398
399   if (!Cmp) {
400     // Pairwise OR the XOR results.
401     OrList = pairWiseOr(XorList);
402
403     // Pairwise OR the OR results until one result left.
404     while (OrList.size() != 1) {
405       OrList = pairWiseOr(OrList);
406     }
407
408     assert(Diff && "Failed to find comparison diff");
409     Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
410   }
411
412   return Cmp;
413 }
414
415 void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
416                                                         unsigned &LoadIndex) {
417   Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
418
419   BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
420                            ? EndBlock
421                            : LoadCmpBlocks[BlockIndex + 1];
422   // Early exit branch if difference found to ResultBlock. Otherwise,
423   // continue to next LoadCmpBlock or EndBlock.
424   BranchInst *CmpBr = BranchInst::Create(ResBlock.BB, NextBB, Cmp);
425   Builder.Insert(CmpBr);
426   BasicBlock *const BB = LoadCmpBlocks[BlockIndex];
427
428   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
429   // since early exit to ResultBlock was not taken (no difference was found in
430   // any of the bytes).
431   if (BlockIndex == LoadCmpBlocks.size() - 1) {
432     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
433     PhiRes->addIncoming(Zero, BB);
434   }
435   DTU.applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
436                     {DominatorTree::Insert, BB, NextBB}});
437 }
438
439 // This function creates the IR intructions for loading and comparing using the
440 // given LoadSize. It loads the number of bytes specified by LoadSize from each
441 // source of the memcmp parameters. It then does a subtract to see if there was
442 // a difference in the loaded values. If a difference is found, it branches
443 // with an early exit to the ResultBlock for calculating which source was
444 // larger. Otherwise, it falls through to the either the next LoadCmpBlock or
445 // the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
446 // a special case through emitLoadCompareByteBlock. The special handling can
447 // simply subtract the loaded values and add it to the result phi node.
448 void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
449   // There is one load per block in this case, BlockIndex == LoadIndex.
450   const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
451
452   if (CurLoadEntry.LoadSize == 1) {
453     MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
454     return;
455   }
456
457   Type *LoadSizeType =
458       IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
459   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
460   assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
461
462   BasicBlock *const BB = LoadCmpBlocks[BlockIndex];
463   Builder.SetInsertPoint(BB);
464
465   Value *Source1 = getPtrToElementAtOffset(CI->getArgOperand(0), LoadSizeType,
466                                            CurLoadEntry.Offset);
467   Value *Source2 = getPtrToElementAtOffset(CI->getArgOperand(1), LoadSizeType,
468                                            CurLoadEntry.Offset);
469
470   // Load LoadSizeType from the base address.
471   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
472   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
473
474   if (DL.isLittleEndian()) {
475     Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
476                                                 Intrinsic::bswap, LoadSizeType);
477     LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
478     LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
479   }
480
481   if (LoadSizeType != MaxLoadType) {
482     LoadSrc1 = Builder.CreateZExt(LoadSrc1, MaxLoadType);
483     LoadSrc2 = Builder.CreateZExt(LoadSrc2, MaxLoadType);
484   }
485
486   // Add the loaded values to the phi nodes for calculating memcmp result only
487   // if result is not used in a zero equality.
488   if (!IsUsedForZeroCmp) {
489     ResBlock.PhiSrc1->addIncoming(LoadSrc1, LoadCmpBlocks[BlockIndex]);
490     ResBlock.PhiSrc2->addIncoming(LoadSrc2, LoadCmpBlocks[BlockIndex]);
491   }
492
493   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, LoadSrc1, LoadSrc2);
494   BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
495                            ? EndBlock
496                            : LoadCmpBlocks[BlockIndex + 1];
497   // Early exit branch if difference found to ResultBlock. Otherwise, continue
498   // to next LoadCmpBlock or EndBlock.
499   BranchInst *CmpBr = BranchInst::Create(NextBB, ResBlock.BB, Cmp);
500   Builder.Insert(CmpBr);
501
502   // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
503   // since early exit to ResultBlock was not taken (no difference was found in
504   // any of the bytes).
505   if (BlockIndex == LoadCmpBlocks.size() - 1) {
506     Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
507     PhiRes->addIncoming(Zero, BB);
508   }
509   DTU.applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
510                     {DominatorTree::Insert, BB, NextBB}});
511 }
512
513 // This function populates the ResultBlock with a sequence to calculate the
514 // memcmp result. It compares the two loaded source values and returns -1 if
515 // src1 < src2 and 1 if src1 > src2.
516 void MemCmpExpansion::emitMemCmpResultBlock() {
517   // Special case: if memcmp result is used in a zero equality, result does not
518   // need to be calculated and can simply return 1.
519   if (IsUsedForZeroCmp) {
520     BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
521     Builder.SetInsertPoint(ResBlock.BB, InsertPt);
522     Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
523     PhiRes->addIncoming(Res, ResBlock.BB);
524     BranchInst *NewBr = BranchInst::Create(EndBlock);
525     Builder.Insert(NewBr);
526     DTU.applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
527     return;
528   }
529   BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
530   Builder.SetInsertPoint(ResBlock.BB, InsertPt);
531
532   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
533                                   ResBlock.PhiSrc2);
534
535   Value *Res =
536       Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
537                            ConstantInt::get(Builder.getInt32Ty(), 1));
538
539   BranchInst *NewBr = BranchInst::Create(EndBlock);
540   Builder.Insert(NewBr);
541   PhiRes->addIncoming(Res, ResBlock.BB);
542   DTU.applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
543 }
544
545 void MemCmpExpansion::setupResultBlockPHINodes() {
546   Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
547   Builder.SetInsertPoint(ResBlock.BB);
548   // Note: this assumes one load per block.
549   ResBlock.PhiSrc1 =
550       Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
551   ResBlock.PhiSrc2 =
552       Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
553 }
554
555 void MemCmpExpansion::setupEndBlockPHINodes() {
556   Builder.SetInsertPoint(&EndBlock->front());
557   PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
558 }
559
560 Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
561   unsigned LoadIndex = 0;
562   // This loop populates each of the LoadCmpBlocks with the IR sequence to
563   // handle multiple loads per block.
564   for (unsigned I = 0; I < getNumBlocks(); ++I) {
565     emitLoadCompareBlockMultipleLoads(I, LoadIndex);
566   }
567
568   emitMemCmpResultBlock();
569   return PhiRes;
570 }
571
572 /// A memcmp expansion that compares equality with 0 and only has one block of
573 /// load and compare can bypass the compare, branch, and phi IR that is required
574 /// in the general case.
575 Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
576   unsigned LoadIndex = 0;
577   Value *Cmp = getCompareLoadPairs(0, LoadIndex);
578   assert(LoadIndex == getNumLoads() && "some entries were not consumed");
579   return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
580 }
581
582 /// A memcmp expansion that only has one block of load and compare can bypass
583 /// the compare, branch, and phi IR that is required in the general case.
584 Value *MemCmpExpansion::getMemCmpOneBlock() {
585   Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
586   Value *Source1 = CI->getArgOperand(0);
587   Value *Source2 = CI->getArgOperand(1);
588
589   // Cast source to LoadSizeType*.
590   if (Source1->getType() != LoadSizeType)
591     Source1 = Builder.CreateBitCast(Source1, LoadSizeType->getPointerTo());
592   if (Source2->getType() != LoadSizeType)
593     Source2 = Builder.CreateBitCast(Source2, LoadSizeType->getPointerTo());
594
595   // Load LoadSizeType from the base address.
596   Value *LoadSrc1 = Builder.CreateLoad(LoadSizeType, Source1);
597   Value *LoadSrc2 = Builder.CreateLoad(LoadSizeType, Source2);
598
599   if (DL.isLittleEndian() && Size != 1) {
600     Function *Bswap = Intrinsic::getDeclaration(CI->getModule(),
601                                                 Intrinsic::bswap, LoadSizeType);
602     LoadSrc1 = Builder.CreateCall(Bswap, LoadSrc1);
603     LoadSrc2 = Builder.CreateCall(Bswap, LoadSrc2);
604   }
605
606   if (Size < 4) {
607     // The i8 and i16 cases don't need compares. We zext the loaded values and
608     // subtract them to get the suitable negative, zero, or positive i32 result.
609     LoadSrc1 = Builder.CreateZExt(LoadSrc1, Builder.getInt32Ty());
610     LoadSrc2 = Builder.CreateZExt(LoadSrc2, Builder.getInt32Ty());
611     return Builder.CreateSub(LoadSrc1, LoadSrc2);
612   }
613
614   // The result of memcmp is negative, zero, or positive, so produce that by
615   // subtracting 2 extended compare bits: sub (ugt, ult).
616   // If a target prefers to use selects to get -1/0/1, they should be able
617   // to transform this later. The inverse transform (going from selects to math)
618   // may not be possible in the DAG because the selects got converted into
619   // branches before we got there.
620   Value *CmpUGT = Builder.CreateICmpUGT(LoadSrc1, LoadSrc2);
621   Value *CmpULT = Builder.CreateICmpULT(LoadSrc1, LoadSrc2);
622   Value *ZextUGT = Builder.CreateZExt(CmpUGT, Builder.getInt32Ty());
623   Value *ZextULT = Builder.CreateZExt(CmpULT, Builder.getInt32Ty());
624   return Builder.CreateSub(ZextUGT, ZextULT);
625 }
626
627 // This function expands the memcmp call into an inline expansion and returns
628 // the memcmp result.
629 Value *MemCmpExpansion::getMemCmpExpansion() {
630   // Create the basic block framework for a multi-block expansion.
631   if (getNumBlocks() != 1) {
632     BasicBlock *StartBlock = CI->getParent();
633     EndBlock = StartBlock->splitBasicBlock(CI, "endblock");
634     DTU.applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
635     setupEndBlockPHINodes();
636     createResultBlock();
637
638     // If return value of memcmp is not used in a zero equality, we need to
639     // calculate which source was larger. The calculation requires the
640     // two loaded source values of each load compare block.
641     // These will be saved in the phi nodes created by setupResultBlockPHINodes.
642     if (!IsUsedForZeroCmp)
643       setupResultBlockPHINodes();
644
645     // Create the number of required load compare basic blocks.
646     createLoadCmpBlocks();
647
648     // Update the terminator added by splitBasicBlock to branch to the first
649     // LoadCmpBlock.
650     BasicBlock *const FirstLoadBB = LoadCmpBlocks[0];
651     StartBlock->getTerminator()->setSuccessor(0, FirstLoadBB);
652     DTU.applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
653                       {DominatorTree::Insert, StartBlock, FirstLoadBB}});
654   }
655
656   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
657
658   if (IsUsedForZeroCmp)
659     return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
660                                : getMemCmpExpansionZeroCase();
661
662   if (getNumBlocks() == 1)
663     return getMemCmpOneBlock();
664
665   for (unsigned I = 0; I < getNumBlocks(); ++I) {
666     emitLoadCompareBlock(I);
667   }
668
669   emitMemCmpResultBlock();
670   return PhiRes;
671 }
672
673 // This function checks to see if an expansion of memcmp can be generated.
674 // It checks for constant compare size that is less than the max inline size.
675 // If an expansion cannot occur, returns false to leave as a library call.
676 // Otherwise, the library call is replaced with a new IR instruction sequence.
677 /// We want to transform:
678 /// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
679 /// To:
680 /// loadbb:
681 ///  %0 = bitcast i32* %buffer2 to i8*
682 ///  %1 = bitcast i32* %buffer1 to i8*
683 ///  %2 = bitcast i8* %1 to i64*
684 ///  %3 = bitcast i8* %0 to i64*
685 ///  %4 = load i64, i64* %2
686 ///  %5 = load i64, i64* %3
687 ///  %6 = call i64 @llvm.bswap.i64(i64 %4)
688 ///  %7 = call i64 @llvm.bswap.i64(i64 %5)
689 ///  %8 = sub i64 %6, %7
690 ///  %9 = icmp ne i64 %8, 0
691 ///  br i1 %9, label %res_block, label %loadbb1
692 /// res_block:                                        ; preds = %loadbb2,
693 /// %loadbb1, %loadbb
694 ///  %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
695 ///  %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
696 ///  %10 = icmp ult i64 %phi.src1, %phi.src2
697 ///  %11 = select i1 %10, i32 -1, i32 1
698 ///  br label %endblock
699 /// loadbb1:                                          ; preds = %loadbb
700 ///  %12 = bitcast i32* %buffer2 to i8*
701 ///  %13 = bitcast i32* %buffer1 to i8*
702 ///  %14 = bitcast i8* %13 to i32*
703 ///  %15 = bitcast i8* %12 to i32*
704 ///  %16 = getelementptr i32, i32* %14, i32 2
705 ///  %17 = getelementptr i32, i32* %15, i32 2
706 ///  %18 = load i32, i32* %16
707 ///  %19 = load i32, i32* %17
708 ///  %20 = call i32 @llvm.bswap.i32(i32 %18)
709 ///  %21 = call i32 @llvm.bswap.i32(i32 %19)
710 ///  %22 = zext i32 %20 to i64
711 ///  %23 = zext i32 %21 to i64
712 ///  %24 = sub i64 %22, %23
713 ///  %25 = icmp ne i64 %24, 0
714 ///  br i1 %25, label %res_block, label %loadbb2
715 /// loadbb2:                                          ; preds = %loadbb1
716 ///  %26 = bitcast i32* %buffer2 to i8*
717 ///  %27 = bitcast i32* %buffer1 to i8*
718 ///  %28 = bitcast i8* %27 to i16*
719 ///  %29 = bitcast i8* %26 to i16*
720 ///  %30 = getelementptr i16, i16* %28, i16 6
721 ///  %31 = getelementptr i16, i16* %29, i16 6
722 ///  %32 = load i16, i16* %30
723 ///  %33 = load i16, i16* %31
724 ///  %34 = call i16 @llvm.bswap.i16(i16 %32)
725 ///  %35 = call i16 @llvm.bswap.i16(i16 %33)
726 ///  %36 = zext i16 %34 to i64
727 ///  %37 = zext i16 %35 to i64
728 ///  %38 = sub i64 %36, %37
729 ///  %39 = icmp ne i64 %38, 0
730 ///  br i1 %39, label %res_block, label %loadbb3
731 /// loadbb3:                                          ; preds = %loadbb2
732 ///  %40 = bitcast i32* %buffer2 to i8*
733 ///  %41 = bitcast i32* %buffer1 to i8*
734 ///  %42 = getelementptr i8, i8* %41, i8 14
735 ///  %43 = getelementptr i8, i8* %40, i8 14
736 ///  %44 = load i8, i8* %42
737 ///  %45 = load i8, i8* %43
738 ///  %46 = zext i8 %44 to i32
739 ///  %47 = zext i8 %45 to i32
740 ///  %48 = sub i32 %46, %47
741 ///  br label %endblock
742 /// endblock:                                         ; preds = %res_block,
743 /// %loadbb3
744 ///  %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
745 ///  ret i32 %phi.res
746 static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
747                          const DataLayout *DL, DominatorTree *DT) {
748   NumMemCmpCalls++;
749
750   // Early exit from expansion if -Oz.
751   if (CI->getFunction()->hasMinSize())
752     return false;
753
754   // Early exit from expansion if size is not a constant.
755   ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
756   if (!SizeCast) {
757     NumMemCmpNotConstant++;
758     return false;
759   }
760   const uint64_t SizeVal = SizeCast->getZExtValue();
761
762   if (SizeVal == 0) {
763     return false;
764   }
765   // TTI call to check if target would like to expand memcmp. Also, get the
766   // available load sizes.
767   const bool IsUsedForZeroCmp = isOnlyUsedInZeroEqualityComparison(CI);
768   auto Options = TTI->enableMemCmpExpansion(CI->getFunction()->hasOptSize(),
769                                             IsUsedForZeroCmp);
770   if (!Options)
771     return false;
772
773   if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
774     Options.NumLoadsPerBlock = MemCmpEqZeroNumLoadsPerBlock;
775
776   if (CI->getFunction()->hasOptSize() &&
777       MaxLoadsPerMemcmpOptSize.getNumOccurrences())
778     Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
779
780   if (!CI->getFunction()->hasOptSize() && MaxLoadsPerMemcmp.getNumOccurrences())
781     Options.MaxNumLoads = MaxLoadsPerMemcmp;
782
783   MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DT);
784
785   // Don't expand if this will require more loads than desired by the target.
786   if (Expansion.getNumLoads() == 0) {
787     NumMemCmpGreaterThanMax++;
788     return false;
789   }
790
791   NumMemCmpInlined++;
792
793   Value *Res = Expansion.getMemCmpExpansion();
794
795   // Replace call with result of expansion and erase call.
796   CI->replaceAllUsesWith(Res);
797   CI->eraseFromParent();
798
799   return true;
800 }
801
802 class ExpandMemCmpPass : public FunctionPass {
803 public:
804   static char ID;
805
806   ExpandMemCmpPass() : FunctionPass(ID) {
807     initializeExpandMemCmpPassPass(*PassRegistry::getPassRegistry());
808   }
809
810   bool runOnFunction(Function &F) override {
811     if (skipFunction(F))
812       return false;
813
814     const TargetLibraryInfo *TLI =
815         &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
816     const TargetTransformInfo *TTI =
817         &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
818     // ExpandMemCmp does not need the DominatorTree, but we update it if it's
819     // already available.
820     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
821     auto PA = runImpl(F, TLI, TTI, DTWP ? &DTWP->getDomTree() : nullptr);
822     return !PA.areAllPreserved();
823   }
824
825 private:
826   void getAnalysisUsage(AnalysisUsage &AU) const override {
827     AU.addRequired<TargetLibraryInfoWrapperPass>();
828     AU.addRequired<TargetTransformInfoWrapperPass>();
829     AU.addUsedIfAvailable<DominatorTreeWrapperPass>();
830     AU.addPreserved<GlobalsAAWrapperPass>();
831     AU.addPreserved<DominatorTreeWrapperPass>();
832     FunctionPass::getAnalysisUsage(AU);
833   }
834
835   PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
836                             const TargetTransformInfo *TTI, DominatorTree *DT);
837   // Returns true if a change was made.
838   bool runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
839                   const TargetTransformInfo *TTI, const DataLayout &DL,
840                   DominatorTree *DT);
841 };
842
843 bool ExpandMemCmpPass::runOnBlock(BasicBlock &BB, const TargetLibraryInfo *TLI,
844                                   const TargetTransformInfo *TTI,
845                                   const DataLayout &DL, DominatorTree *DT) {
846   for (Instruction &I : BB) {
847     CallInst *CI = dyn_cast<CallInst>(&I);
848     if (!CI) {
849       continue;
850     }
851     LibFunc Func;
852     if (TLI->getLibFunc(ImmutableCallSite(CI), Func) &&
853         (Func == LibFunc_memcmp || Func == LibFunc_bcmp) &&
854         expandMemCmp(CI, TTI, &DL, DT)) {
855       return true;
856     }
857   }
858   return false;
859 }
860
861 PreservedAnalyses ExpandMemCmpPass::runImpl(Function &F,
862                                             const TargetLibraryInfo *TLI,
863                                             const TargetTransformInfo *TTI,
864                                             DominatorTree *DT) {
865   const DataLayout &DL = F.getParent()->getDataLayout();
866   bool MadeChanges = false;
867   for (auto BBIt = F.begin(); BBIt != F.end();) {
868     if (runOnBlock(*BBIt, TLI, TTI, DL, DT)) {
869       MadeChanges = true;
870       // If changes were made, restart the function from the beginning, since
871       // the structure of the function was changed.
872       BBIt = F.begin();
873     } else {
874       ++BBIt;
875     }
876   }
877   if (!MadeChanges)
878     return PreservedAnalyses::all();
879   PreservedAnalyses PA;
880   PA.preserve<GlobalsAA>();
881   PA.preserve<DominatorTreeAnalysis>();
882   return PA;
883 }
884
885 } // namespace
886
887 char ExpandMemCmpPass::ID = 0;
888 INITIALIZE_PASS_BEGIN(ExpandMemCmpPass, "expandmemcmp",
889                       "Expand memcmp() to load/stores", false, false)
890 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
891 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
892 INITIALIZE_PASS_END(ExpandMemCmpPass, "expandmemcmp",
893                     "Expand memcmp() to load/stores", false, false)
894
895 Pass *llvm::createExpandMemCmpPass() { return new ExpandMemCmpPass(); }