LLVM 24.0.0git
ExpandMemCmp.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/Statistic.h"
23#include "llvm/IR/Dominators.h"
24#include "llvm/IR/IRBuilder.h"
31#include <optional>
32
33using namespace llvm;
34using namespace llvm::PatternMatch;
35
36#define DEBUG_TYPE "expand-memcmp"
37
38STATISTIC(NumMemCmpCalls, "Number of memcmp calls");
39STATISTIC(NumMemCmpNotConstant, "Number of memcmp calls without constant size");
40STATISTIC(NumMemCmpGreaterThanMax,
41 "Number of memcmp calls with size greater than max size");
42STATISTIC(NumMemCmpInlined, "Number of inlined memcmp calls");
43
45 "memcmp-num-loads-per-block", cl::Hidden, cl::init(1),
46 cl::desc("The number of loads per basic block for inline expansion of "
47 "memcmp that is only being compared against zero."));
48
50 "max-loads-per-memcmp", cl::Hidden,
51 cl::desc("Set maximum number of loads used in expanded memcmp"));
52
54 "max-loads-per-memcmp-opt-size", cl::Hidden,
55 cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"));
56
57namespace {
58
59// Return the known alignment of the pointer argument \p ArgNo of \p CI,
60// combining the alignment of the underlying pointer value with any align
61// attribute on the call site itself.
62static Align getMemCmpArgAlignment(const CallInst *CI, unsigned ArgNo,
63 const DataLayout &DL) {
65 if (MaybeAlign ParamAlign = CI->getParamAlign(ArgNo))
66 A = std::max(A, *ParamAlign);
67 return A;
68}
69
70// This class provides helper functions to expand a memcmp library call into an
71// inline expansion.
72class MemCmpExpansion {
73 struct ResultBlock {
74 BasicBlock *BB = nullptr;
75 PHINode *PhiSrc1 = nullptr;
76 PHINode *PhiSrc2 = nullptr;
77
78 ResultBlock() = default;
79 };
80
81 CallInst *const CI = nullptr;
82 ResultBlock ResBlock;
83 const uint64_t Size;
84 unsigned MaxLoadSize = 0;
85 uint64_t NumLoadsNonOneByte = 0;
86 const uint64_t NumLoadsPerBlockForZeroCmp;
87 std::vector<BasicBlock *> LoadCmpBlocks;
88 BasicBlock *EndBlock = nullptr;
89 PHINode *PhiRes = nullptr;
90 const bool IsUsedForZeroCmp;
91 const DataLayout &DL;
92 const TargetTransformInfo &TTI;
93 // The known common alignment of the two source pointers.
94 const Align CommonAlign;
95 DomTreeUpdater *DTU = nullptr;
96 IRBuilder<> Builder;
97 // Represents the decomposition in blocks of the expansion. For example,
98 // comparing 33 bytes on X86+sse can be done with 2x16-byte loads and
99 // 1x1-byte load, which would be represented as [{16, 0}, {16, 16}, {1, 32}.
100 struct LoadEntry {
101 LoadEntry(unsigned LoadSize, uint64_t Offset)
102 : LoadSize(LoadSize), Offset(Offset) {
103 }
104
105 // The size of the load for this block, in bytes.
106 unsigned LoadSize;
107 // The offset of this load from the base pointer, in bytes.
108 uint64_t Offset;
109 };
110 using LoadEntryVector = SmallVector<LoadEntry, 8>;
111 LoadEntryVector LoadSequence;
112
113 void createLoadCmpBlocks();
114 void createResultBlock();
115 void setupResultBlockPHINodes();
116 void setupEndBlockPHINodes();
117 Value *getCompareLoadPairs(unsigned BlockIndex, unsigned &LoadIndex);
118 void emitLoadCompareBlock(unsigned BlockIndex);
119 void emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
120 unsigned &LoadIndex);
121 void emitLoadCompareByteBlock(unsigned BlockIndex, unsigned OffsetBytes);
122 void emitMemCmpResultBlock();
123 Value *getMemCmpExpansionZeroCase();
124 Value *getMemCmpEqZeroOneBlock();
125 Value *getMemCmpOneBlock();
126 struct LoadPair {
127 Value *Lhs = nullptr;
128 Value *Rhs = nullptr;
129 };
130 LoadPair getLoadPair(Type *LoadSizeType, Type *BSwapSizeType,
131 Type *CmpSizeType, unsigned OffsetBytes);
132
133 // Return true if a load of `LoadSize` bytes at `Offset` from the base
134 // pointers is accessible on the target: either it is naturally aligned given
135 // the known common base alignment, or the target allows a misaligned access
136 // of that width.
137 bool isAccessAllowed(unsigned LoadSize, uint64_t Offset) const;
138
139 static LoadEntryVector
140 computeGreedyLoadSequence(uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
141 unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte);
142 LoadEntryVector
143 computeOverlappingLoadSequence(uint64_t Size, unsigned MaxLoadSize,
144 unsigned MaxNumLoads,
145 unsigned &NumLoadsNonOneByte) const;
146
147 void optimiseLoadSequence(
148 LoadEntryVector &LoadSequence,
149 const TargetTransformInfo::MemCmpExpansionOptions &Options,
150 bool IsUsedForZeroCmp) const;
151
152public:
153 MemCmpExpansion(CallInst *CI, uint64_t Size,
154 const TargetTransformInfo::MemCmpExpansionOptions &Options,
155 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
156 DomTreeUpdater *DTU, const TargetTransformInfo &TTI,
157 Align CommonAlign);
158
159 unsigned getNumBlocks();
160 uint64_t getNumLoads() const { return LoadSequence.size(); }
161
162 Value *getMemCmpExpansion();
163};
164
165// Return true if a load of `LoadSize` bytes at `Offset` from the base pointers
166// is accessible on the target: either it is naturally aligned given the known
167// common base alignment, or the target allows a misaligned access of that
168// width. We query whether the access is *allowed*, not whether it is *fast*,
169// matching the historical behavior of forming unaligned loads whenever the
170// target permits them.
171static bool isAccessAllowed(const CallInst *CI, const TargetTransformInfo &TTI,
172 Align CommonAlign, unsigned LoadSize,
174 // The access is naturally aligned when the known alignment is at least the
175 // load width. LoadSize is not necessarily a power of two here: some targets
176 // like RISC-V add non-power-of-two load sizes for vector memcmp, so compare
177 // against the raw width rather than constructing an Align, which would
178 // require a power of two.
179 Align AccessAlign = commonAlignment(CommonAlign, Offset);
180 if (AccessAlign.value() >= LoadSize)
181 return true;
182 unsigned AS = CI->getArgOperand(0)->getType()->getPointerAddressSpace();
183 return TTI.allowsMisalignedMemoryAccesses(CI->getContext(), LoadSize * 8, AS,
184 AccessAlign);
185}
186
187// Return true if a load of `LoadSize` bytes at `Offset` from the base pointers
188// is accessible on the target given the known common base alignment. This gates
189// the (power-of-two) overlapping loads; tail expansions are always legalized by
190// the backend and skip this check.
191bool MemCmpExpansion::isAccessAllowed(unsigned LoadSize,
192 uint64_t Offset) const {
193 return ::isAccessAllowed(CI, TTI, CommonAlign, LoadSize, Offset);
194}
195
196MemCmpExpansion::LoadEntryVector MemCmpExpansion::computeGreedyLoadSequence(
197 uint64_t Size, llvm::ArrayRef<unsigned> LoadSizes,
198 const unsigned MaxNumLoads, unsigned &NumLoadsNonOneByte) {
199 NumLoadsNonOneByte = 0;
200 LoadEntryVector LoadSequence;
201 uint64_t Offset = 0;
202 while (Size && !LoadSizes.empty()) {
203 const unsigned LoadSize = LoadSizes.front();
204 const uint64_t NumLoadsForThisSize = Size / LoadSize;
205 if (LoadSequence.size() + NumLoadsForThisSize > MaxNumLoads) {
206 // Do not expand if the total number of loads is larger than what the
207 // target allows. Note that it's important that we exit before completing
208 // the expansion to avoid using a ton of memory to store the expansion for
209 // large sizes.
210 return {};
211 }
212 if (NumLoadsForThisSize > 0) {
213 for (uint64_t I = 0; I < NumLoadsForThisSize; ++I) {
214 LoadSequence.push_back({LoadSize, Offset});
215 Offset += LoadSize;
216 }
217 if (LoadSize > 1)
218 ++NumLoadsNonOneByte;
219 Size = Size % LoadSize;
220 }
221 LoadSizes = LoadSizes.drop_front();
222 }
223 return LoadSequence;
224}
225
226MemCmpExpansion::LoadEntryVector
227MemCmpExpansion::computeOverlappingLoadSequence(
228 uint64_t Size, const unsigned MaxLoadSize, const unsigned MaxNumLoads,
229 unsigned &NumLoadsNonOneByte) const {
230 // These are already handled by the greedy approach.
231 if (Size < 2 || MaxLoadSize < 2)
232 return {};
233
234 // We try to do as many non-overlapping loads as possible starting from the
235 // beginning.
236 const uint64_t NumNonOverlappingLoads = Size / MaxLoadSize;
237 assert(NumNonOverlappingLoads && "there must be at least one load");
238 // There remain 0 to (MaxLoadSize - 1) bytes to load, this will be done with
239 // an overlapping load.
240 Size = Size - NumNonOverlappingLoads * MaxLoadSize;
241 // Bail if we do not need an overloapping store, this is already handled by
242 // the greedy approach.
243 if (Size == 0)
244 return {};
245 // Bail if the number of loads (non-overlapping + potential overlapping one)
246 // is larger than the max allowed.
247 if ((NumNonOverlappingLoads + 1) > MaxNumLoads)
248 return {};
249
250 // Add non-overlapping loads.
251 LoadEntryVector LoadSequence;
252 uint64_t Offset = 0;
253 for (uint64_t I = 0; I < NumNonOverlappingLoads; ++I) {
254 LoadSequence.push_back({MaxLoadSize, Offset});
255 Offset += MaxLoadSize;
256 }
257
258 // Add the last overlapping load. Its offset is not a multiple of the load
259 // size, so it may be misaligned; bail if the target cannot access it.
260 assert(Size > 0 && Size < MaxLoadSize && "broken invariant");
261 uint64_t OverlapOffset = Offset - (MaxLoadSize - Size);
262 if (!isAccessAllowed(MaxLoadSize, OverlapOffset))
263 return {};
264
265 LoadSequence.push_back({MaxLoadSize, OverlapOffset});
266 NumLoadsNonOneByte = 1;
267 return LoadSequence;
268}
269
270void MemCmpExpansion::optimiseLoadSequence(
271 LoadEntryVector &LoadSequence,
272 const TargetTransformInfo::MemCmpExpansionOptions &Options,
273 bool IsUsedForZeroCmp) const {
274 // This part of code attempts to optimize the LoadSequence by merging allowed
275 // subsequences into single loads of allowed sizes from
276 // `MemCmpExpansionOptions::AllowedTailExpansions`. If it is for zero
277 // comparison or if no allowed tail expansions are specified, we exit early.
278 if (IsUsedForZeroCmp || Options.AllowedTailExpansions.empty())
279 return;
280
281 while (LoadSequence.size() >= 2) {
282 auto Last = LoadSequence[LoadSequence.size() - 1];
283 auto PreLast = LoadSequence[LoadSequence.size() - 2];
284
285 // Exit the loop if the two sequences are not contiguous
286 if (PreLast.Offset + PreLast.LoadSize != Last.Offset)
287 break;
288
289 auto LoadSize = Last.LoadSize + PreLast.LoadSize;
290 if (find(Options.AllowedTailExpansions, LoadSize) ==
291 Options.AllowedTailExpansions.end())
292 break;
293
294 // A merged load wider than MaxLoadSize can only be emitted when it is the
295 // sole load (getMemCmpOneBlock); in a multi-block expansion
296 // emitLoadCompareBlock requires every load to fit in MaxLoadSize (the
297 // result-block phis are sized to it). The per-call-site alignment filter
298 // can shrink MaxLoadSize, so stop merging when the result would still be
299 // multi-block and the merged load exceeds it.
300 if (LoadSize > MaxLoadSize && LoadSequence.size() > 2)
301 break;
302
303 // Remove the last two sequences and replace with the combined sequence
304 LoadSequence.pop_back();
305 LoadSequence.pop_back();
306 LoadSequence.emplace_back(LoadSize, PreLast.Offset);
307 }
308}
309
310// Initialize the basic block structure required for expansion of memcmp call
311// with given maximum load size and memcmp size parameter.
312// This structure includes:
313// 1. A list of load compare blocks - LoadCmpBlocks.
314// 2. An EndBlock, split from original instruction point, which is the block to
315// return from.
316// 3. ResultBlock, block to branch to for early exit when a
317// LoadCmpBlock finds a difference.
318MemCmpExpansion::MemCmpExpansion(
319 CallInst *const CI, uint64_t Size,
320 const TargetTransformInfo::MemCmpExpansionOptions &Options,
321 const bool IsUsedForZeroCmp, const DataLayout &TheDataLayout,
322 DomTreeUpdater *DTU, const TargetTransformInfo &TTI, Align CommonAlign)
323 : CI(CI), Size(Size), NumLoadsPerBlockForZeroCmp(Options.NumLoadsPerBlock),
324 IsUsedForZeroCmp(IsUsedForZeroCmp), DL(TheDataLayout), TTI(TTI),
325 CommonAlign(CommonAlign), DTU(DTU), Builder(CI) {
326 assert(Size > 0 && "zero blocks");
327 // Scale the max size down if the target can load more bytes than we need.
328 llvm::ArrayRef<unsigned> LoadSizes(Options.LoadSizes);
329 while (!LoadSizes.empty() && LoadSizes.front() > Size) {
330 LoadSizes = LoadSizes.drop_front();
331 }
332 assert(!LoadSizes.empty() && "cannot load Size bytes");
333 MaxLoadSize = LoadSizes.front();
334 // Compute the decomposition.
335 unsigned GreedyNumLoadsNonOneByte = 0;
336 LoadSequence = computeGreedyLoadSequence(Size, LoadSizes, Options.MaxNumLoads,
337 GreedyNumLoadsNonOneByte);
338 NumLoadsNonOneByte = GreedyNumLoadsNonOneByte;
339 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
340 // If we allow overlapping loads and the load sequence is not already optimal,
341 // use overlapping loads.
342 if (Options.AllowOverlappingLoads &&
343 (LoadSequence.empty() || LoadSequence.size() > 2)) {
344 unsigned OverlappingNumLoadsNonOneByte = 0;
345 auto OverlappingLoads = computeOverlappingLoadSequence(
346 Size, MaxLoadSize, Options.MaxNumLoads, OverlappingNumLoadsNonOneByte);
347 if (!OverlappingLoads.empty() &&
348 (LoadSequence.empty() ||
349 OverlappingLoads.size() < LoadSequence.size())) {
350 LoadSequence = OverlappingLoads;
351 NumLoadsNonOneByte = OverlappingNumLoadsNonOneByte;
352 }
353 }
354 assert(LoadSequence.size() <= Options.MaxNumLoads && "broken invariant");
355 optimiseLoadSequence(LoadSequence, Options, IsUsedForZeroCmp);
356}
357
358unsigned MemCmpExpansion::getNumBlocks() {
359 if (IsUsedForZeroCmp)
360 return getNumLoads() / NumLoadsPerBlockForZeroCmp +
361 (getNumLoads() % NumLoadsPerBlockForZeroCmp != 0 ? 1 : 0);
362 return getNumLoads();
363}
364
365void MemCmpExpansion::createLoadCmpBlocks() {
366 for (unsigned i = 0; i < getNumBlocks(); i++) {
367 BasicBlock *BB = BasicBlock::Create(CI->getContext(), "loadbb",
368 EndBlock->getParent(), EndBlock);
369 LoadCmpBlocks.push_back(BB);
370 }
371}
372
373void MemCmpExpansion::createResultBlock() {
374 ResBlock.BB = BasicBlock::Create(CI->getContext(), "res_block",
375 EndBlock->getParent(), EndBlock);
376}
377
378MemCmpExpansion::LoadPair MemCmpExpansion::getLoadPair(Type *LoadSizeType,
379 Type *BSwapSizeType,
380 Type *CmpSizeType,
381 unsigned OffsetBytes) {
382 // Get the memory source at offset `OffsetBytes`.
383 Value *LhsSource = CI->getArgOperand(0);
384 Value *RhsSource = CI->getArgOperand(1);
385 Align LhsAlign = getMemCmpArgAlignment(CI, 0, DL);
386 Align RhsAlign = getMemCmpArgAlignment(CI, 1, DL);
387 if (OffsetBytes > 0) {
388 auto *ByteType = Type::getInt8Ty(CI->getContext());
389 LhsSource = Builder.CreateConstGEP1_64(ByteType, LhsSource, OffsetBytes);
390 RhsSource = Builder.CreateConstGEP1_64(ByteType, RhsSource, OffsetBytes);
391 LhsAlign = commonAlignment(LhsAlign, OffsetBytes);
392 RhsAlign = commonAlignment(RhsAlign, OffsetBytes);
393 }
394
395 // Create a constant or a load from the source.
396 Value *Lhs = nullptr;
397 if (auto *C = dyn_cast<Constant>(LhsSource))
398 Lhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
399 if (!Lhs)
400 Lhs = Builder.CreateAlignedLoad(LoadSizeType, LhsSource, LhsAlign);
401
402 Value *Rhs = nullptr;
403 if (auto *C = dyn_cast<Constant>(RhsSource))
404 Rhs = ConstantFoldLoadFromConstPtr(C, LoadSizeType, DL);
405 if (!Rhs)
406 Rhs = Builder.CreateAlignedLoad(LoadSizeType, RhsSource, RhsAlign);
407
408 // Zero extend if Byte Swap intrinsic has different type
409 if (BSwapSizeType && LoadSizeType != BSwapSizeType) {
410 Lhs = Builder.CreateZExt(Lhs, BSwapSizeType);
411 Rhs = Builder.CreateZExt(Rhs, BSwapSizeType);
412 }
413
414 // Swap bytes if required.
415 if (BSwapSizeType) {
417 CI->getModule(), Intrinsic::bswap, BSwapSizeType);
418 Lhs = Builder.CreateCall(Bswap, Lhs);
419 Rhs = Builder.CreateCall(Bswap, Rhs);
420 }
421
422 // Zero extend if required.
423 if (CmpSizeType != nullptr && CmpSizeType != Lhs->getType()) {
424 Lhs = Builder.CreateZExt(Lhs, CmpSizeType);
425 Rhs = Builder.CreateZExt(Rhs, CmpSizeType);
426 }
427 return {Lhs, Rhs};
428}
429
430// This function creates the IR instructions for loading and comparing 1 byte.
431// It loads 1 byte from each source of the memcmp parameters with the given
432// GEPIndex. It then subtracts the two loaded values and adds this result to the
433// final phi node for selecting the memcmp result.
434void MemCmpExpansion::emitLoadCompareByteBlock(unsigned BlockIndex,
435 unsigned OffsetBytes) {
436 BasicBlock *BB = LoadCmpBlocks[BlockIndex];
437 Builder.SetInsertPoint(BB);
438 const LoadPair Loads =
439 getLoadPair(Type::getInt8Ty(CI->getContext()), nullptr,
440 Type::getInt32Ty(CI->getContext()), OffsetBytes);
441 Value *Diff = Builder.CreateSub(Loads.Lhs, Loads.Rhs);
442
443 PhiRes->addIncoming(Diff, BB);
444
445 if (BlockIndex < (LoadCmpBlocks.size() - 1)) {
446 // Early exit branch if difference found to EndBlock. Otherwise, continue to
447 // next LoadCmpBlock,
448 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_NE, Diff,
449 ConstantInt::get(Diff->getType(), 0));
450 Builder.CreateCondBr(Cmp, EndBlock, LoadCmpBlocks[BlockIndex + 1]);
451 if (DTU)
452 DTU->applyUpdates(
453 {{DominatorTree::Insert, BB, EndBlock},
454 {DominatorTree::Insert, BB, LoadCmpBlocks[BlockIndex + 1]}});
455 } else {
456 // The last block has an unconditional branch to EndBlock.
457 Builder.CreateBr(EndBlock);
458 if (DTU)
459 DTU->applyUpdates({{DominatorTree::Insert, BB, EndBlock}});
460 }
461}
462
463/// Generate an equality comparison for one or more pairs of loaded values.
464/// This is used in the case where the memcmp() call is compared equal or not
465/// equal to zero.
466Value *MemCmpExpansion::getCompareLoadPairs(unsigned BlockIndex,
467 unsigned &LoadIndex) {
468 assert(LoadIndex < getNumLoads() &&
469 "getCompareLoadPairs() called with no remaining loads");
470 std::vector<Value *> XorList, OrList;
471 Value *Diff = nullptr;
472
473 const unsigned NumLoads =
474 std::min(getNumLoads() - LoadIndex, NumLoadsPerBlockForZeroCmp);
475
476 // For a single-block expansion, start inserting before the memcmp call.
477 if (LoadCmpBlocks.empty())
478 Builder.SetInsertPoint(CI);
479 else
480 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
481
482 Value *Cmp = nullptr;
483 // If we have multiple loads per block, we need to generate a composite
484 // comparison using xor+or. The type for the combinations is the largest load
485 // type.
486 IntegerType *const MaxLoadType =
487 NumLoads == 1 ? nullptr
488 : IntegerType::get(CI->getContext(), MaxLoadSize * 8);
489
490 for (unsigned i = 0; i < NumLoads; ++i, ++LoadIndex) {
491 const LoadEntry &CurLoadEntry = LoadSequence[LoadIndex];
492 const LoadPair Loads = getLoadPair(
493 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8), nullptr,
494 MaxLoadType, CurLoadEntry.Offset);
495
496 if (NumLoads != 1) {
497 // If we have multiple loads per block, we need to generate a composite
498 // comparison using xor+or.
499 Diff = Builder.CreateXor(Loads.Lhs, Loads.Rhs);
500 Diff = Builder.CreateZExt(Diff, MaxLoadType);
501 XorList.push_back(Diff);
502 } else {
503 // If there's only one load per block, we just compare the loaded values.
504 Cmp = Builder.CreateICmpNE(Loads.Lhs, Loads.Rhs);
505 }
506 }
507
508 auto pairWiseOr = [&](std::vector<Value *> &InList) -> std::vector<Value *> {
509 std::vector<Value *> OutList;
510 for (unsigned i = 0; i < InList.size() - 1; i = i + 2) {
511 Value *Or = Builder.CreateOr(InList[i], InList[i + 1]);
512 OutList.push_back(Or);
513 }
514 if (InList.size() % 2 != 0)
515 OutList.push_back(InList.back());
516 return OutList;
517 };
518
519 if (!Cmp) {
520 // Pairwise OR the XOR results.
521 OrList = pairWiseOr(XorList);
522
523 // Pairwise OR the OR results until one result left.
524 while (OrList.size() != 1) {
525 OrList = pairWiseOr(OrList);
526 }
527
528 assert(Diff && "Failed to find comparison diff");
529 Cmp = Builder.CreateICmpNE(OrList[0], ConstantInt::get(Diff->getType(), 0));
530 }
531
532 return Cmp;
533}
534
535void MemCmpExpansion::emitLoadCompareBlockMultipleLoads(unsigned BlockIndex,
536 unsigned &LoadIndex) {
537 Value *Cmp = getCompareLoadPairs(BlockIndex, LoadIndex);
538
539 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
540 ? EndBlock
541 : LoadCmpBlocks[BlockIndex + 1];
542 // Early exit branch if difference found to ResultBlock. Otherwise,
543 // continue to next LoadCmpBlock or EndBlock.
544 BasicBlock *BB = Builder.GetInsertBlock();
545 CondBrInst *CmpBr = Builder.CreateCondBr(Cmp, ResBlock.BB, NextBB);
547 CI->getFunction());
548 if (DTU)
549 DTU->applyUpdates({{DominatorTree::Insert, BB, ResBlock.BB},
550 {DominatorTree::Insert, BB, NextBB}});
551
552 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
553 // since early exit to ResultBlock was not taken (no difference was found in
554 // any of the bytes).
555 if (BlockIndex == LoadCmpBlocks.size() - 1) {
556 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
557 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
558 }
559}
560
561// This function creates the IR intructions for loading and comparing using the
562// given LoadSize. It loads the number of bytes specified by LoadSize from each
563// source of the memcmp parameters. It then does a subtract to see if there was
564// a difference in the loaded values. If a difference is found, it branches
565// with an early exit to the ResultBlock for calculating which source was
566// larger. Otherwise, it falls through to the either the next LoadCmpBlock or
567// the EndBlock if this is the last LoadCmpBlock. Loading 1 byte is handled with
568// a special case through emitLoadCompareByteBlock. The special handling can
569// simply subtract the loaded values and add it to the result phi node.
570void MemCmpExpansion::emitLoadCompareBlock(unsigned BlockIndex) {
571 // There is one load per block in this case, BlockIndex == LoadIndex.
572 const LoadEntry &CurLoadEntry = LoadSequence[BlockIndex];
573
574 if (CurLoadEntry.LoadSize == 1) {
575 MemCmpExpansion::emitLoadCompareByteBlock(BlockIndex, CurLoadEntry.Offset);
576 return;
577 }
578
579 Type *LoadSizeType =
580 IntegerType::get(CI->getContext(), CurLoadEntry.LoadSize * 8);
581 Type *BSwapSizeType =
582 DL.isLittleEndian()
584 PowerOf2Ceil(CurLoadEntry.LoadSize * 8))
585 : nullptr;
586 Type *MaxLoadType = IntegerType::get(
587 CI->getContext(),
588 std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(CurLoadEntry.LoadSize)) * 8);
589 assert(CurLoadEntry.LoadSize <= MaxLoadSize && "Unexpected load type");
590
591 Builder.SetInsertPoint(LoadCmpBlocks[BlockIndex]);
592
593 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
594 CurLoadEntry.Offset);
595
596 // Add the loaded values to the phi nodes for calculating memcmp result only
597 // if result is not used in a zero equality.
598 if (!IsUsedForZeroCmp) {
599 ResBlock.PhiSrc1->addIncoming(Loads.Lhs, LoadCmpBlocks[BlockIndex]);
600 ResBlock.PhiSrc2->addIncoming(Loads.Rhs, LoadCmpBlocks[BlockIndex]);
601 }
602
603 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Loads.Lhs, Loads.Rhs);
604 BasicBlock *NextBB = (BlockIndex == (LoadCmpBlocks.size() - 1))
605 ? EndBlock
606 : LoadCmpBlocks[BlockIndex + 1];
607 // Early exit branch if difference found to ResultBlock. Otherwise, continue
608 // to next LoadCmpBlock or EndBlock.
609 BasicBlock *BB = Builder.GetInsertBlock();
610 CondBrInst *CmpBr = Builder.CreateCondBr(Cmp, NextBB, ResBlock.BB);
612 CI->getFunction());
613 if (DTU)
614 DTU->applyUpdates({{DominatorTree::Insert, BB, NextBB},
615 {DominatorTree::Insert, BB, ResBlock.BB}});
616
617 // Add a phi edge for the last LoadCmpBlock to Endblock with a value of 0
618 // since early exit to ResultBlock was not taken (no difference was found in
619 // any of the bytes).
620 if (BlockIndex == LoadCmpBlocks.size() - 1) {
621 Value *Zero = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 0);
622 PhiRes->addIncoming(Zero, LoadCmpBlocks[BlockIndex]);
623 }
624}
625
626// This function populates the ResultBlock with a sequence to calculate the
627// memcmp result. It compares the two loaded source values and returns -1 if
628// src1 < src2 and 1 if src1 > src2.
629void MemCmpExpansion::emitMemCmpResultBlock() {
630 // Special case: if memcmp result is used in a zero equality, result does not
631 // need to be calculated and can simply return 1.
632 if (IsUsedForZeroCmp) {
633 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
634 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
635 Value *Res = ConstantInt::get(Type::getInt32Ty(CI->getContext()), 1);
636 PhiRes->addIncoming(Res, ResBlock.BB);
637 Builder.CreateBr(EndBlock);
638 if (DTU)
639 DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
640 return;
641 }
642 BasicBlock::iterator InsertPt = ResBlock.BB->getFirstInsertionPt();
643 Builder.SetInsertPoint(ResBlock.BB, InsertPt);
644
645 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, ResBlock.PhiSrc1,
646 ResBlock.PhiSrc2);
647
648 Value *Res =
649 Builder.CreateSelect(Cmp, Constant::getAllOnesValue(Builder.getInt32Ty()),
650 ConstantInt::get(Builder.getInt32Ty(), 1));
652 DEBUG_TYPE, CI->getFunction());
653
654 PhiRes->addIncoming(Res, ResBlock.BB);
655 Builder.CreateBr(EndBlock);
656 if (DTU)
657 DTU->applyUpdates({{DominatorTree::Insert, ResBlock.BB, EndBlock}});
658}
659
660void MemCmpExpansion::setupResultBlockPHINodes() {
661 Type *MaxLoadType = IntegerType::get(CI->getContext(), MaxLoadSize * 8);
662 Builder.SetInsertPoint(ResBlock.BB);
663 // Note: this assumes one load per block.
664 ResBlock.PhiSrc1 =
665 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src1");
666 ResBlock.PhiSrc2 =
667 Builder.CreatePHI(MaxLoadType, NumLoadsNonOneByte, "phi.src2");
668}
669
670void MemCmpExpansion::setupEndBlockPHINodes() {
671 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
672 PhiRes = Builder.CreatePHI(Type::getInt32Ty(CI->getContext()), 2, "phi.res");
673}
674
675Value *MemCmpExpansion::getMemCmpExpansionZeroCase() {
676 unsigned LoadIndex = 0;
677 // This loop populates each of the LoadCmpBlocks with the IR sequence to
678 // handle multiple loads per block.
679 for (unsigned I = 0; I < getNumBlocks(); ++I) {
680 emitLoadCompareBlockMultipleLoads(I, LoadIndex);
681 }
682
683 emitMemCmpResultBlock();
684 return PhiRes;
685}
686
687/// A memcmp expansion that compares equality with 0 and only has one block of
688/// load and compare can bypass the compare, branch, and phi IR that is required
689/// in the general case.
690Value *MemCmpExpansion::getMemCmpEqZeroOneBlock() {
691 unsigned LoadIndex = 0;
692 Value *Cmp = getCompareLoadPairs(0, LoadIndex);
693 assert(LoadIndex == getNumLoads() && "some entries were not consumed");
694 return Builder.CreateZExt(Cmp, Type::getInt32Ty(CI->getContext()));
695}
696
697/// A memcmp expansion that only has one block of load and compare can bypass
698/// the compare, branch, and phi IR that is required in the general case.
699/// This function also analyses users of memcmp, and if there is only one user
700/// from which we can conclude that only 2 out of 3 memcmp outcomes really
701/// matter, then it generates more efficient code with only one comparison.
702Value *MemCmpExpansion::getMemCmpOneBlock() {
703 bool NeedsBSwap = DL.isLittleEndian() && Size != 1;
704 Type *LoadSizeType = IntegerType::get(CI->getContext(), Size * 8);
705 Type *BSwapSizeType =
706 NeedsBSwap ? IntegerType::get(CI->getContext(), PowerOf2Ceil(Size * 8))
707 : nullptr;
708 Type *MaxLoadType =
710 std::max(MaxLoadSize, (unsigned)PowerOf2Ceil(Size)) * 8);
711
712 // The i8 and i16 cases don't need compares. We zext the loaded values and
713 // subtract them to get the suitable negative, zero, or positive i32 result.
714 if (Size == 1 || Size == 2) {
715 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType,
716 Builder.getInt32Ty(), /*Offset*/ 0);
717 return Builder.CreateSub(Loads.Lhs, Loads.Rhs);
718 }
719
720 const LoadPair Loads = getLoadPair(LoadSizeType, BSwapSizeType, MaxLoadType,
721 /*Offset*/ 0);
722
723 // If a user of memcmp cares only about two outcomes, for example:
724 // bool result = memcmp(a, b, NBYTES) > 0;
725 // We can generate more optimal code with a smaller number of operations
726 if (CI->hasOneUser()) {
727 auto *UI = cast<Instruction>(*CI->user_begin());
728 CmpPredicate Pred = ICmpInst::Predicate::BAD_ICMP_PREDICATE;
729 bool NeedsZExt = false;
730 // This is a special case because instead of checking if the result is less
731 // than zero:
732 // bool result = memcmp(a, b, NBYTES) < 0;
733 // Compiler is clever enough to generate the following code:
734 // bool result = memcmp(a, b, NBYTES) >> 31;
735 if (match(UI,
736 m_LShr(m_Value(),
737 m_SpecificInt(CI->getType()->getIntegerBitWidth() - 1)))) {
738 Pred = ICmpInst::ICMP_SLT;
739 NeedsZExt = true;
740 } else if (match(UI, m_SpecificICmp(ICmpInst::ICMP_SGT, m_Specific(CI),
741 m_AllOnes()))) {
742 // Adjust predicate as if it compared with 0.
743 Pred = ICmpInst::ICMP_SGE;
744 } else if (match(UI, m_SpecificICmp(ICmpInst::ICMP_SLT, m_Specific(CI),
745 m_One()))) {
746 // Adjust predicate as if it compared with 0.
747 Pred = ICmpInst::ICMP_SLE;
748 } else {
749 // In case of a successful match this call will set `Pred` variable
750 match(UI, m_ICmp(Pred, m_Specific(CI), m_Zero()));
751 }
752 // Generate new code and remove the original memcmp call and the user
753 if (ICmpInst::isSigned(Pred)) {
755 Loads.Lhs, Loads.Rhs);
756 auto *Result = NeedsZExt ? Builder.CreateZExt(Cmp, UI->getType()) : Cmp;
757 UI->replaceAllUsesWith(Result);
758 UI->eraseFromParent();
759 CI->eraseFromParent();
760 return nullptr;
761 }
762 }
763
764 // The result of memcmp is negative, zero, or positive.
765 return Builder.CreateIntrinsic(Builder.getInt32Ty(), Intrinsic::ucmp,
766 {Loads.Lhs, Loads.Rhs});
767}
768
769// This function expands the memcmp call into an inline expansion and returns
770// the memcmp result. Returns nullptr if the memcmp is already replaced.
771Value *MemCmpExpansion::getMemCmpExpansion() {
772 // Create the basic block framework for a multi-block expansion.
773 if (getNumBlocks() != 1) {
774 BasicBlock *StartBlock = CI->getParent();
775 EndBlock = SplitBlock(StartBlock, CI, DTU, /*LI=*/nullptr,
776 /*MSSAU=*/nullptr, "endblock");
777 setupEndBlockPHINodes();
778 createResultBlock();
779
780 // If return value of memcmp is not used in a zero equality, we need to
781 // calculate which source was larger. The calculation requires the
782 // two loaded source values of each load compare block.
783 // These will be saved in the phi nodes created by setupResultBlockPHINodes.
784 if (!IsUsedForZeroCmp) setupResultBlockPHINodes();
785
786 // Create the number of required load compare basic blocks.
787 createLoadCmpBlocks();
788
789 // Update the terminator added by SplitBlock to branch to the first
790 // LoadCmpBlock.
791 StartBlock->getTerminator()->setSuccessor(0, LoadCmpBlocks[0]);
792 if (DTU)
793 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, LoadCmpBlocks[0]},
794 {DominatorTree::Delete, StartBlock, EndBlock}});
795 }
796
798
799 if (IsUsedForZeroCmp)
800 return getNumBlocks() == 1 ? getMemCmpEqZeroOneBlock()
801 : getMemCmpExpansionZeroCase();
802
803 if (getNumBlocks() == 1)
804 return getMemCmpOneBlock();
805
806 for (unsigned I = 0; I < getNumBlocks(); ++I) {
807 emitLoadCompareBlock(I);
808 }
809
810 emitMemCmpResultBlock();
811 return PhiRes;
812}
813
814// This function checks to see if an expansion of memcmp can be generated.
815// It checks for constant compare size that is less than the max inline size.
816// If an expansion cannot occur, returns false to leave as a library call.
817// Otherwise, the library call is replaced with a new IR instruction sequence.
818/// We want to transform:
819/// %call = call signext i32 @memcmp(i8* %0, i8* %1, i64 15)
820/// To:
821/// loadbb:
822/// %0 = bitcast i32* %buffer2 to i8*
823/// %1 = bitcast i32* %buffer1 to i8*
824/// %2 = bitcast i8* %1 to i64*
825/// %3 = bitcast i8* %0 to i64*
826/// %4 = load i64, i64* %2
827/// %5 = load i64, i64* %3
828/// %6 = call i64 @llvm.bswap.i64(i64 %4)
829/// %7 = call i64 @llvm.bswap.i64(i64 %5)
830/// %8 = sub i64 %6, %7
831/// %9 = icmp ne i64 %8, 0
832/// br i1 %9, label %res_block, label %loadbb1
833/// res_block: ; preds = %loadbb2,
834/// %loadbb1, %loadbb
835/// %phi.src1 = phi i64 [ %6, %loadbb ], [ %22, %loadbb1 ], [ %36, %loadbb2 ]
836/// %phi.src2 = phi i64 [ %7, %loadbb ], [ %23, %loadbb1 ], [ %37, %loadbb2 ]
837/// %10 = icmp ult i64 %phi.src1, %phi.src2
838/// %11 = select i1 %10, i32 -1, i32 1
839/// br label %endblock
840/// loadbb1: ; preds = %loadbb
841/// %12 = bitcast i32* %buffer2 to i8*
842/// %13 = bitcast i32* %buffer1 to i8*
843/// %14 = bitcast i8* %13 to i32*
844/// %15 = bitcast i8* %12 to i32*
845/// %16 = getelementptr i32, i32* %14, i32 2
846/// %17 = getelementptr i32, i32* %15, i32 2
847/// %18 = load i32, i32* %16
848/// %19 = load i32, i32* %17
849/// %20 = call i32 @llvm.bswap.i32(i32 %18)
850/// %21 = call i32 @llvm.bswap.i32(i32 %19)
851/// %22 = zext i32 %20 to i64
852/// %23 = zext i32 %21 to i64
853/// %24 = sub i64 %22, %23
854/// %25 = icmp ne i64 %24, 0
855/// br i1 %25, label %res_block, label %loadbb2
856/// loadbb2: ; preds = %loadbb1
857/// %26 = bitcast i32* %buffer2 to i8*
858/// %27 = bitcast i32* %buffer1 to i8*
859/// %28 = bitcast i8* %27 to i16*
860/// %29 = bitcast i8* %26 to i16*
861/// %30 = getelementptr i16, i16* %28, i16 6
862/// %31 = getelementptr i16, i16* %29, i16 6
863/// %32 = load i16, i16* %30
864/// %33 = load i16, i16* %31
865/// %34 = call i16 @llvm.bswap.i16(i16 %32)
866/// %35 = call i16 @llvm.bswap.i16(i16 %33)
867/// %36 = zext i16 %34 to i64
868/// %37 = zext i16 %35 to i64
869/// %38 = sub i64 %36, %37
870/// %39 = icmp ne i64 %38, 0
871/// br i1 %39, label %res_block, label %loadbb3
872/// loadbb3: ; preds = %loadbb2
873/// %40 = bitcast i32* %buffer2 to i8*
874/// %41 = bitcast i32* %buffer1 to i8*
875/// %42 = getelementptr i8, i8* %41, i8 14
876/// %43 = getelementptr i8, i8* %40, i8 14
877/// %44 = load i8, i8* %42
878/// %45 = load i8, i8* %43
879/// %46 = zext i8 %44 to i32
880/// %47 = zext i8 %45 to i32
881/// %48 = sub i32 %46, %47
882/// br label %endblock
883/// endblock: ; preds = %res_block,
884/// %loadbb3
885/// %phi.res = phi i32 [ %48, %loadbb3 ], [ %11, %res_block ]
886/// ret i32 %phi.res
887static bool expandMemCmp(CallInst *CI, const TargetTransformInfo *TTI,
888 const DataLayout *DL, ProfileSummaryInfo *PSI,
889 BlockFrequencyInfo *BFI, DomTreeUpdater *DTU,
890 const bool IsBCmp) {
891 NumMemCmpCalls++;
892
893 // Early exit from expansion if -Oz.
894 if (CI->getFunction()->hasMinSize())
895 return false;
896
897 // Early exit from expansion if size is not a constant.
898 ConstantInt *SizeCast = dyn_cast<ConstantInt>(CI->getArgOperand(2));
899 if (!SizeCast) {
900 NumMemCmpNotConstant++;
901 return false;
902 }
903 const uint64_t SizeVal = SizeCast->getZExtValue();
904
905 if (SizeVal == 0) {
906 return false;
907 }
908 // TTI call to check if target would like to expand memcmp. Also, get the
909 // available load sizes.
910 const bool IsUsedForZeroCmp =
912 bool OptForSize = llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
913 auto Options = TTI->enableMemCmpExpansion(OptForSize,
914 IsUsedForZeroCmp);
915 if (!Options) return false;
916
917 if (MemCmpEqZeroNumLoadsPerBlock.getNumOccurrences())
919
920 if (OptForSize &&
921 MaxLoadsPerMemcmpOptSize.getNumOccurrences())
922 Options.MaxNumLoads = MaxLoadsPerMemcmpOptSize;
923
924 if (!OptForSize && MaxLoadsPerMemcmp.getNumOccurrences())
925 Options.MaxNumLoads = MaxLoadsPerMemcmp;
926
927 // Keep only the load sizes the target can access at the base alignment:
928 // either the access is naturally aligned, or the target allows a misaligned
929 // access of that width. This lets strict-alignment targets expand compares
930 // whose pointers happen to be sufficiently aligned, while still falling back
931 // to the libcall when no load size fits. Because the greedy load sequence
932 // only places a load of size S at an offset that is a multiple of S, a size
933 // kept here is always accessible in that sequence; overlapping loads and
934 // merged tail expansions are checked separately against their actual offsets
935 // in MemCmpExpansion.
936 const Align CommonAlign = std::min(getMemCmpArgAlignment(CI, 0, *DL),
937 getMemCmpArgAlignment(CI, 1, *DL));
938 llvm::erase_if(Options.LoadSizes, [&](unsigned LoadSize) {
939 return !isAccessAllowed(CI, *TTI, CommonAlign, LoadSize, /*Offset=*/0);
940 });
941 // If the filter removed every load size, bail out to the libcall: the
942 // MemCmpExpansion constructor asserts that at least one load size remains.
943 // In practice all in-tree targets include a byte load size, which is
944 // accessible at any alignment and therefore always survives the filter.
945 if (Options.LoadSizes.empty())
946 return false;
947
948 MemCmpExpansion Expansion(CI, SizeVal, Options, IsUsedForZeroCmp, *DL, DTU,
949 *TTI, CommonAlign);
950
951 // Don't expand if this will require more loads than desired by the target.
952 if (Expansion.getNumLoads() == 0) {
953 NumMemCmpGreaterThanMax++;
954 return false;
955 }
956
957 NumMemCmpInlined++;
958
959 if (Value *Res = Expansion.getMemCmpExpansion()) {
960 // Replace call with result of expansion and erase call.
961 CI->replaceAllUsesWith(Res);
962 CI->eraseFromParent();
963 }
964
965 return true;
966}
967
968static PreservedAnalyses runImpl(Function &F, const TargetLibraryInfo *TLI,
969 const TargetTransformInfo *TTI,
970 ProfileSummaryInfo *PSI,
971 BlockFrequencyInfo *BFI, DominatorTree *DT) {
972 std::optional<DomTreeUpdater> DTU;
973 if (DT)
974 DTU.emplace(DT, DomTreeUpdater::UpdateStrategy::Lazy);
975
976 const DataLayout& DL = F.getDataLayout();
978 for (Instruction &I : instructions(F)) {
979 if (auto *CI = dyn_cast<CallInst>(&I)) {
980 LibFunc Func;
981 if (TLI->getLibFunc(*CI, Func) &&
982 (Func == LibFunc_memcmp || Func == LibFunc_bcmp))
983 MemCmpCalls.push_back({CI, Func});
984 }
985 }
986
987 bool MadeChanges = false;
988 for (const auto &[CI, Func] : MemCmpCalls) {
989 if (expandMemCmp(CI, TTI, &DL, PSI, BFI, DTU ? &*DTU : nullptr,
990 Func == LibFunc_bcmp))
991 MadeChanges = true;
992 }
993
994 if (MadeChanges)
995 for (BasicBlock &BB : F)
997 if (!MadeChanges)
998 return PreservedAnalyses::all();
999 PreservedAnalyses PA;
1000 PA.preserve<DominatorTreeAnalysis>();
1001 return PA;
1002}
1003
1004} // namespace
1005
1008 // Don't expand memcmp in sanitized functions — sanitizers intercept memcmp
1009 // calls to check for memory errors, and expanding would bypass that.
1010 if (F.hasFnAttribute(Attribute::SanitizeAddress) ||
1011 F.hasFnAttribute(Attribute::SanitizeMemory) ||
1012 F.hasFnAttribute(Attribute::SanitizeThread) ||
1013 F.hasFnAttribute(Attribute::SanitizeHWAddress))
1014 return PreservedAnalyses::all();
1015
1016 const auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1017 const auto &TTI = FAM.getResult<TargetIRAnalysis>(F);
1018 auto *PSI = FAM.getResult<ModuleAnalysisManagerFunctionProxy>(F)
1019 .getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
1020 BlockFrequencyInfo *BFI = (PSI && PSI->hasProfileSummary())
1021 ? &FAM.getResult<BlockFrequencyAnalysis>(F)
1022 : nullptr;
1023 auto *DT = FAM.getCachedResult<DominatorTreeAnalysis>(F);
1024
1025 return runImpl(F, &TLI, &TTI, PSI, BFI, DT);
1026}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Expand Atomic instructions
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static bool runImpl(MachineFunction &MF)
Definition CFIFixup.cpp:304
DXIL Intrinsic Expansion
static cl::opt< unsigned > MaxLoadsPerMemcmpOptSize("max-loads-per-memcmp-opt-size", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp for -Os/Oz"))
static cl::opt< unsigned > MaxLoadsPerMemcmp("max-loads-per-memcmp", cl::Hidden, cl::desc("Set maximum number of loads used in expanded memcmp"))
static cl::opt< unsigned > MemCmpEqZeroNumLoadsPerBlock("memcmp-num-loads-per-block", cl::Hidden, cl::init(1), cl::desc("The number of loads per basic block for inline expansion of " "memcmp that is only being compared against zero."))
#define DEBUG_TYPE
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
This pass exposes codegen information to IR-level passes.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
MaybeAlign getParamAlign(unsigned ArgNo) const
Extract the alignment for a call or parameter (0=unknown).
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:688
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
Value * CreateConstGEP1_64(Type *Ty, Value *Ptr, uint64_t Idx0, const Twine &Name="")
Definition IRBuilder.h:2055
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1934
CondBrInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
Definition IRBuilder.h:1216
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:221
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
Definition IRBuilder.h:534
BasicBlock * GetInsertBlock() const
Definition IRBuilder.h:175
Value * CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2379
UncondBrInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
Definition IRBuilder.h:1210
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2540
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1439
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2121
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value * > Args={}, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2554
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:181
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1622
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:2485
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1592
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:348
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
void push_back(const T &Elt)
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI MemCmpExpansionOptions enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const
LLVM_ABI unsigned getIntegerBitWidth() const
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
user_iterator user_begin()
Definition Value.h:402
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:163
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:993
const ParentTy * getParent() const
Definition ilist_node.h:34
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
auto m_Value()
Match an arbitrary value and ignore it.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
initializer< Ty > init(const Ty &Val)
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1765
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:736
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:386
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
TargetTransformInfo TTI
IRBuilder(LLVMContext &, FolderTy, InserterTy, MDNode *, ArrayRef< OperandBundleDef >) -> IRBuilder< FolderTy, InserterTy >
@ Or
Bitwise or logical OR of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2192
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:201
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:77
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106