LLVM 18.0.0git
CodeGenPrepare.cpp
Go to the documentation of this file.
1//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
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 munges the code in the input function to better prepare it for
10// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
23#include "llvm/ADT/Statistic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
47#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugInfo.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
54#include "llvm/IR/GlobalValue.h"
56#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
58#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
62#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/IntrinsicsAArch64.h"
64#include "llvm/IR/LLVMContext.h"
65#include "llvm/IR/MDBuilder.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/Operator.h"
70#include "llvm/IR/Statepoint.h"
71#include "llvm/IR/Type.h"
72#include "llvm/IR/Use.h"
73#include "llvm/IR/User.h"
74#include "llvm/IR/Value.h"
75#include "llvm/IR/ValueHandle.h"
76#include "llvm/IR/ValueMap.h"
78#include "llvm/Pass.h"
84#include "llvm/Support/Debug.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <optional>
102#include <utility>
103#include <vector>
104
105using namespace llvm;
106using namespace llvm::PatternMatch;
107
108#define DEBUG_TYPE "codegenprepare"
109
110STATISTIC(NumBlocksElim, "Number of blocks eliminated");
111STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
112STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
113STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
114 "sunken Cmps");
115STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
116 "of sunken Casts");
117STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
118 "computations were sunk");
119STATISTIC(NumMemoryInstsPhiCreated,
120 "Number of phis created when address "
121 "computations were sunk to memory instructions");
122STATISTIC(NumMemoryInstsSelectCreated,
123 "Number of select created when address "
124 "computations were sunk to memory instructions");
125STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
126STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
127STATISTIC(NumAndsAdded,
128 "Number of and mask instructions added to form ext loads");
129STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
130STATISTIC(NumRetsDup, "Number of return instructions duplicated");
131STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
132STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
133STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
134
136 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
137 cl::desc("Disable branch optimizations in CodeGenPrepare"));
138
139static cl::opt<bool>
140 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
141 cl::desc("Disable GC optimizations in CodeGenPrepare"));
142
143static cl::opt<bool>
144 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
145 cl::init(false),
146 cl::desc("Disable select to branch conversion."));
147
148static cl::opt<bool>
149 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
150 cl::desc("Address sinking in CGP using GEPs."));
151
152static cl::opt<bool>
153 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
154 cl::desc("Enable sinkinig and/cmp into branches."));
155
157 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
158 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
159
161 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
162 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
163
165 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
166 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
167 "CodeGenPrepare"));
168
170 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
171 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
172 "optimization in CodeGenPrepare"));
173
175 "disable-preheader-prot", cl::Hidden, cl::init(false),
176 cl::desc("Disable protection against removing loop preheaders"));
177
179 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
180 cl::desc("Use profile info to add section prefix for hot/cold functions"));
181
183 "profile-unknown-in-special-section", cl::Hidden,
184 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
185 "profile, we cannot tell the function is cold for sure because "
186 "it may be a function newly added without ever being sampled. "
187 "With the flag enabled, compiler can put such profile unknown "
188 "functions into a special section, so runtime system can choose "
189 "to handle it in a different way than .text section, to save "
190 "RAM for example. "));
191
193 "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
194 cl::desc("Use the basic-block-sections profile to determine the text "
195 "section prefix for hot functions. Functions with "
196 "basic-block-sections profile will be placed in `.text.hot` "
197 "regardless of their FDO profile info. Other functions won't be "
198 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
199 "profiles."));
200
202 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
203 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
204 "(frequency of destination block) is greater than this ratio"));
205
207 "force-split-store", cl::Hidden, cl::init(false),
208 cl::desc("Force store splitting no matter what the target query says."));
209
211 "cgp-type-promotion-merge", cl::Hidden,
212 cl::desc("Enable merging of redundant sexts when one is dominating"
213 " the other."),
214 cl::init(true));
215
217 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
218 cl::desc("Disables combining addressing modes with different parts "
219 "in optimizeMemoryInst."));
220
221static cl::opt<bool>
222 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
223 cl::desc("Allow creation of Phis in Address sinking."));
224
226 "addr-sink-new-select", cl::Hidden, cl::init(true),
227 cl::desc("Allow creation of selects in Address sinking."));
228
230 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
231 cl::desc("Allow combining of BaseReg field in Address sinking."));
232
234 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
235 cl::desc("Allow combining of BaseGV field in Address sinking."));
236
238 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
239 cl::desc("Allow combining of BaseOffs field in Address sinking."));
240
242 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
243 cl::desc("Allow combining of ScaledReg field in Address sinking."));
244
245static cl::opt<bool>
246 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
247 cl::init(true),
248 cl::desc("Enable splitting large offset of GEP."));
249
251 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
252 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
253
254static cl::opt<bool>
255 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
256 cl::desc("Enable BFI update verification for "
257 "CodeGenPrepare."));
258
259static cl::opt<bool>
260 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(true),
261 cl::desc("Enable converting phi types in CodeGenPrepare"));
262
264 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
265 cl::desc("Least BB number of huge function."));
266
268 MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(100),
270 cl::desc("Max number of address users to look at"));
271
272static cl::opt<bool>
273 DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(false),
274 cl::desc("Disable elimination of dead PHI nodes."));
275
276namespace {
277
278enum ExtType {
279 ZeroExtension, // Zero extension has been seen.
280 SignExtension, // Sign extension has been seen.
281 BothExtension // This extension type is used if we saw sext after
282 // ZeroExtension had been set, or if we saw zext after
283 // SignExtension had been set. It makes the type
284 // information of a promoted instruction invalid.
285};
286
287enum ModifyDT {
288 NotModifyDT, // Not Modify any DT.
289 ModifyBBDT, // Modify the Basic Block Dominator Tree.
290 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
291 // This usually means we move/delete/insert instruction
292 // in a Basic Block. So we should re-iterate instructions
293 // in such Basic Block.
294};
295
296using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
297using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
298using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
300using ValueToSExts = MapVector<Value *, SExts>;
301
302class TypePromotionTransaction;
303
304class CodeGenPrepare : public FunctionPass {
305 const TargetMachine *TM = nullptr;
306 const TargetSubtargetInfo *SubtargetInfo = nullptr;
307 const TargetLowering *TLI = nullptr;
308 const TargetRegisterInfo *TRI = nullptr;
309 const TargetTransformInfo *TTI = nullptr;
310 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
311 const TargetLibraryInfo *TLInfo = nullptr;
312 LoopInfo *LI = nullptr;
313 std::unique_ptr<BlockFrequencyInfo> BFI;
314 std::unique_ptr<BranchProbabilityInfo> BPI;
315 ProfileSummaryInfo *PSI = nullptr;
316
317 /// As we scan instructions optimizing them, this is the next instruction
318 /// to optimize. Transforms that can invalidate this should update it.
319 BasicBlock::iterator CurInstIterator;
320
321 /// Keeps track of non-local addresses that have been sunk into a block.
322 /// This allows us to avoid inserting duplicate code for blocks with
323 /// multiple load/stores of the same address. The usage of WeakTrackingVH
324 /// enables SunkAddrs to be treated as a cache whose entries can be
325 /// invalidated if a sunken address computation has been erased.
327
328 /// Keeps track of all instructions inserted for the current function.
329 SetOfInstrs InsertedInsts;
330
331 /// Keeps track of the type of the related instruction before their
332 /// promotion for the current function.
333 InstrToOrigTy PromotedInsts;
334
335 /// Keep track of instructions removed during promotion.
336 SetOfInstrs RemovedInsts;
337
338 /// Keep track of sext chains based on their initial value.
339 DenseMap<Value *, Instruction *> SeenChainsForSExt;
340
341 /// Keep track of GEPs accessing the same data structures such as structs or
342 /// arrays that are candidates to be split later because of their large
343 /// size.
346 LargeOffsetGEPMap;
347
348 /// Keep track of new GEP base after splitting the GEPs having large offset.
349 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
350
351 /// Map serial numbers to Large offset GEPs.
352 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
353
354 /// Keep track of SExt promoted.
355 ValueToSExts ValToSExtendedUses;
356
357 /// True if the function has the OptSize attribute.
358 bool OptSize;
359
360 /// DataLayout for the Function being processed.
361 const DataLayout *DL = nullptr;
362
363 /// Building the dominator tree can be expensive, so we only build it
364 /// lazily and update it when required.
365 std::unique_ptr<DominatorTree> DT;
366
367public:
368 /// If encounter huge function, we need to limit the build time.
369 bool IsHugeFunc = false;
370
371 /// FreshBBs is like worklist, it collected the updated BBs which need
372 /// to be optimized again.
373 /// Note: Consider building time in this pass, when a BB updated, we need
374 /// to insert such BB into FreshBBs for huge function.
376
377 static char ID; // Pass identification, replacement for typeid
378
379 CodeGenPrepare() : FunctionPass(ID) {
381 }
382
383 bool runOnFunction(Function &F) override;
384
385 void releaseMemory() override {
386 // Clear per function information.
387 InsertedInsts.clear();
388 PromotedInsts.clear();
389 FreshBBs.clear();
390 BPI.reset();
391 BFI.reset();
392 }
393
394 StringRef getPassName() const override { return "CodeGen Prepare"; }
395
396 void getAnalysisUsage(AnalysisUsage &AU) const override {
397 // FIXME: When we can selectively preserve passes, preserve the domtree.
404 }
405
406private:
407 template <typename F>
408 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
409 // Substituting can cause recursive simplifications, which can invalidate
410 // our iterator. Use a WeakTrackingVH to hold onto it in case this
411 // happens.
412 Value *CurValue = &*CurInstIterator;
413 WeakTrackingVH IterHandle(CurValue);
414
415 f();
416
417 // If the iterator instruction was recursively deleted, start over at the
418 // start of the block.
419 if (IterHandle != CurValue) {
420 CurInstIterator = BB->begin();
421 SunkAddrs.clear();
422 }
423 }
424
425 // Get the DominatorTree, building if necessary.
426 DominatorTree &getDT(Function &F) {
427 if (!DT)
428 DT = std::make_unique<DominatorTree>(F);
429 return *DT;
430 }
431
432 void removeAllAssertingVHReferences(Value *V);
433 bool eliminateAssumptions(Function &F);
434 bool eliminateFallThrough(Function &F, DominatorTree *DT = nullptr);
435 bool eliminateMostlyEmptyBlocks(Function &F);
436 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
437 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
438 void eliminateMostlyEmptyBlock(BasicBlock *BB);
439 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
440 bool isPreheader);
441 bool makeBitReverse(Instruction &I);
442 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
443 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
444 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
445 unsigned AddrSpace);
446 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
447 bool optimizeInlineAsmInst(CallInst *CS);
448 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
449 bool optimizeExt(Instruction *&I);
450 bool optimizeExtUses(Instruction *I);
451 bool optimizeLoadExt(LoadInst *Load);
452 bool optimizeShiftInst(BinaryOperator *BO);
453 bool optimizeFunnelShift(IntrinsicInst *Fsh);
454 bool optimizeSelectInst(SelectInst *SI);
455 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
456 bool optimizeSwitchType(SwitchInst *SI);
457 bool optimizeSwitchPhiConstants(SwitchInst *SI);
458 bool optimizeSwitchInst(SwitchInst *SI);
459 bool optimizeExtractElementInst(Instruction *Inst);
460 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
461 bool fixupDbgValue(Instruction *I);
462 bool placeDbgValues(Function &F);
463 bool placePseudoProbes(Function &F);
464 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
465 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
466 bool tryToPromoteExts(TypePromotionTransaction &TPT,
468 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
469 unsigned CreatedInstsCost = 0);
470 bool mergeSExts(Function &F);
471 bool splitLargeGEPOffsets();
472 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
473 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
474 bool optimizePhiTypes(Function &F);
475 bool performAddressTypePromotion(
476 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
477 bool HasPromoted, TypePromotionTransaction &TPT,
478 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
479 bool splitBranchCondition(Function &F, ModifyDT &ModifiedDT);
480 bool simplifyOffsetableRelocate(GCStatepointInst &I);
481
482 bool tryToSinkFreeOperands(Instruction *I);
483 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
484 CmpInst *Cmp, Intrinsic::ID IID);
485 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
486 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
487 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
488 void verifyBFIUpdates(Function &F);
489};
490
491} // end anonymous namespace
492
493char CodeGenPrepare::ID = 0;
494
496 "Optimize for code generation", false, false)
503INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation",
505
506FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
507
508bool CodeGenPrepare::runOnFunction(Function &F) {
509 if (skipFunction(F))
510 return false;
511
512 DL = &F.getParent()->getDataLayout();
513
514 bool EverMadeChange = false;
515
516 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
517 SubtargetInfo = TM->getSubtargetImpl(F);
518 TLI = SubtargetInfo->getTargetLowering();
519 TRI = SubtargetInfo->getRegisterInfo();
520 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
521 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
522 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
523 BPI.reset(new BranchProbabilityInfo(F, *LI));
524 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
525 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
526 BBSectionsProfileReader =
527 getAnalysisIfAvailable<BasicBlockSectionsProfileReader>();
528 OptSize = F.hasOptSize();
529 // Use the basic-block-sections profile to promote hot functions to .text.hot
530 // if requested.
531 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
532 BBSectionsProfileReader->isFunctionHot(F.getName())) {
533 F.setSectionPrefix("hot");
534 } else if (ProfileGuidedSectionPrefix) {
535 // The hot attribute overwrites profile count based hotness while profile
536 // counts based hotness overwrite the cold attribute.
537 // This is a conservative behabvior.
538 if (F.hasFnAttribute(Attribute::Hot) ||
539 PSI->isFunctionHotInCallGraph(&F, *BFI))
540 F.setSectionPrefix("hot");
541 // If PSI shows this function is not hot, we will placed the function
542 // into unlikely section if (1) PSI shows this is a cold function, or
543 // (2) the function has a attribute of cold.
544 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
545 F.hasFnAttribute(Attribute::Cold))
546 F.setSectionPrefix("unlikely");
549 F.setSectionPrefix("unknown");
550 }
551
552 /// This optimization identifies DIV instructions that can be
553 /// profitably bypassed and carried out with a shorter, faster divide.
554 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
555 const DenseMap<unsigned int, unsigned int> &BypassWidths =
557 BasicBlock *BB = &*F.begin();
558 while (BB != nullptr) {
559 // bypassSlowDivision may create new BBs, but we don't want to reapply the
560 // optimization to those blocks.
561 BasicBlock *Next = BB->getNextNode();
562 // F.hasOptSize is already checked in the outer if statement.
563 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
564 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
565 BB = Next;
566 }
567 }
568
569 // Get rid of @llvm.assume builtins before attempting to eliminate empty
570 // blocks, since there might be blocks that only contain @llvm.assume calls
571 // (plus arguments that we can get rid of).
572 EverMadeChange |= eliminateAssumptions(F);
573
574 // Eliminate blocks that contain only PHI nodes and an
575 // unconditional branch.
576 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
577
578 ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
580 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
581
582 // Split some critical edges where one of the sources is an indirect branch,
583 // to help generate sane code for PHIs involving such edges.
584 EverMadeChange |=
585 SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
586
587 // If we are optimzing huge function, we need to consider the build time.
588 // Because the basic algorithm's complex is near O(N!).
589 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
590
591 // Transformations above may invalidate dominator tree and/or loop info.
592 DT.reset();
593 LI->releaseMemory();
594 LI->analyze(getDT(F));
595
596 bool MadeChange = true;
597 bool FuncIterated = false;
598 while (MadeChange) {
599 MadeChange = false;
600
602 if (FuncIterated && !FreshBBs.contains(&BB))
603 continue;
604
605 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
606 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
607
608 if (ModifiedDTOnIteration == ModifyDT::ModifyBBDT)
609 DT.reset();
610
611 MadeChange |= Changed;
612 if (IsHugeFunc) {
613 // If the BB is updated, it may still has chance to be optimized.
614 // This usually happen at sink optimization.
615 // For example:
616 //
617 // bb0:
618 // %and = and i32 %a, 4
619 // %cmp = icmp eq i32 %and, 0
620 //
621 // If the %cmp sink to other BB, the %and will has chance to sink.
622 if (Changed)
623 FreshBBs.insert(&BB);
624 else if (FuncIterated)
625 FreshBBs.erase(&BB);
626 } else {
627 // For small/normal functions, we restart BB iteration if the dominator
628 // tree of the Function was changed.
629 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
630 break;
631 }
632 }
633 // We have iterated all the BB in the (only work for huge) function.
634 FuncIterated = IsHugeFunc;
635
636 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
637 MadeChange |= mergeSExts(F);
638 if (!LargeOffsetGEPMap.empty())
639 MadeChange |= splitLargeGEPOffsets();
640 MadeChange |= optimizePhiTypes(F);
641
642 if (MadeChange)
643 eliminateFallThrough(F, DT.get());
644
645#ifndef NDEBUG
646 if (MadeChange && VerifyLoopInfo)
647 LI->verify(getDT(F));
648#endif
649
650 // Really free removed instructions during promotion.
651 for (Instruction *I : RemovedInsts)
652 I->deleteValue();
653
654 EverMadeChange |= MadeChange;
655 SeenChainsForSExt.clear();
656 ValToSExtendedUses.clear();
657 RemovedInsts.clear();
658 LargeOffsetGEPMap.clear();
659 LargeOffsetGEPID.clear();
660 }
661
662 NewGEPBases.clear();
663 SunkAddrs.clear();
664
665 if (!DisableBranchOpts) {
666 MadeChange = false;
667 // Use a set vector to get deterministic iteration order. The order the
668 // blocks are removed may affect whether or not PHI nodes in successors
669 // are removed.
671 for (BasicBlock &BB : F) {
673 MadeChange |= ConstantFoldTerminator(&BB, true);
674 if (!MadeChange)
675 continue;
676
677 for (BasicBlock *Succ : Successors)
678 if (pred_empty(Succ))
679 WorkList.insert(Succ);
680 }
681
682 // Delete the dead blocks and any of their dead successors.
683 MadeChange |= !WorkList.empty();
684 while (!WorkList.empty()) {
685 BasicBlock *BB = WorkList.pop_back_val();
687
688 DeleteDeadBlock(BB);
689
690 for (BasicBlock *Succ : Successors)
691 if (pred_empty(Succ))
692 WorkList.insert(Succ);
693 }
694
695 // Merge pairs of basic blocks with unconditional branches, connected by
696 // a single edge.
697 if (EverMadeChange || MadeChange)
698 MadeChange |= eliminateFallThrough(F);
699
700 EverMadeChange |= MadeChange;
701 }
702
703 if (!DisableGCOpts) {
705 for (BasicBlock &BB : F)
706 for (Instruction &I : BB)
707 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
708 Statepoints.push_back(SP);
709 for (auto &I : Statepoints)
710 EverMadeChange |= simplifyOffsetableRelocate(*I);
711 }
712
713 // Do this last to clean up use-before-def scenarios introduced by other
714 // preparatory transforms.
715 EverMadeChange |= placeDbgValues(F);
716 EverMadeChange |= placePseudoProbes(F);
717
718#ifndef NDEBUG
720 verifyBFIUpdates(F);
721#endif
722
723 return EverMadeChange;
724}
725
726bool CodeGenPrepare::eliminateAssumptions(Function &F) {
727 bool MadeChange = false;
728 for (BasicBlock &BB : F) {
729 CurInstIterator = BB.begin();
730 while (CurInstIterator != BB.end()) {
731 Instruction *I = &*(CurInstIterator++);
732 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
733 MadeChange = true;
734 Value *Operand = Assume->getOperand(0);
735 Assume->eraseFromParent();
736
737 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
738 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
739 });
740 }
741 }
742 }
743 return MadeChange;
744}
745
746/// An instruction is about to be deleted, so remove all references to it in our
747/// GEP-tracking data strcutures.
748void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
749 LargeOffsetGEPMap.erase(V);
750 NewGEPBases.erase(V);
751
752 auto GEP = dyn_cast<GetElementPtrInst>(V);
753 if (!GEP)
754 return;
755
756 LargeOffsetGEPID.erase(GEP);
757
758 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
759 if (VecI == LargeOffsetGEPMap.end())
760 return;
761
762 auto &GEPVector = VecI->second;
763 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
764
765 if (GEPVector.empty())
766 LargeOffsetGEPMap.erase(VecI);
767}
768
769// Verify BFI has been updated correctly by recomputing BFI and comparing them.
770void LLVM_ATTRIBUTE_UNUSED CodeGenPrepare::verifyBFIUpdates(Function &F) {
771 DominatorTree NewDT(F);
772 LoopInfo NewLI(NewDT);
773 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
774 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
775 NewBFI.verifyMatch(*BFI);
776}
777
778/// Merge basic blocks which are connected by a single edge, where one of the
779/// basic blocks has a single successor pointing to the other basic block,
780/// which has a single predecessor.
781bool CodeGenPrepare::eliminateFallThrough(Function &F, DominatorTree *DT) {
782 bool Changed = false;
783 // Scan all of the blocks in the function, except for the entry block.
784 // Use a temporary array to avoid iterator being invalidated when
785 // deleting blocks.
787 for (auto &Block : llvm::drop_begin(F))
788 Blocks.push_back(&Block);
789
791 for (auto &Block : Blocks) {
792 auto *BB = cast_or_null<BasicBlock>(Block);
793 if (!BB)
794 continue;
795 // If the destination block has a single pred, then this is a trivial
796 // edge, just collapse it.
797 BasicBlock *SinglePred = BB->getSinglePredecessor();
798
799 // Don't merge if BB's address is taken.
800 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
801 continue;
802
803 // Make an effort to skip unreachable blocks.
804 if (DT && !DT->isReachableFromEntry(BB))
805 continue;
806
807 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
808 if (Term && !Term->isConditional()) {
809 Changed = true;
810 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
811
812 // Merge BB into SinglePred and delete it.
813 MergeBlockIntoPredecessor(BB, /* DTU */ nullptr, LI, /* MSSAU */ nullptr,
814 /* MemDep */ nullptr,
815 /* PredecessorWithTwoSuccessors */ false, DT);
816 Preds.insert(SinglePred);
817
818 if (IsHugeFunc) {
819 // Update FreshBBs to optimize the merged BB.
820 FreshBBs.insert(SinglePred);
821 FreshBBs.erase(BB);
822 }
823 }
824 }
825
826 // (Repeatedly) merging blocks into their predecessors can create redundant
827 // debug intrinsics.
828 for (const auto &Pred : Preds)
829 if (auto *BB = cast_or_null<BasicBlock>(Pred))
831
832 return Changed;
833}
834
835/// Find a destination block from BB if BB is mergeable empty block.
836BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
837 // If this block doesn't end with an uncond branch, ignore it.
838 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
839 if (!BI || !BI->isUnconditional())
840 return nullptr;
841
842 // If the instruction before the branch (skipping debug info) isn't a phi
843 // node, then other stuff is happening here.
845 if (BBI != BB->begin()) {
846 --BBI;
847 while (isa<DbgInfoIntrinsic>(BBI)) {
848 if (BBI == BB->begin())
849 break;
850 --BBI;
851 }
852 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
853 return nullptr;
854 }
855
856 // Do not break infinite loops.
857 BasicBlock *DestBB = BI->getSuccessor(0);
858 if (DestBB == BB)
859 return nullptr;
860
861 if (!canMergeBlocks(BB, DestBB))
862 DestBB = nullptr;
863
864 return DestBB;
865}
866
867/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
868/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
869/// edges in ways that are non-optimal for isel. Start by eliminating these
870/// blocks so we can split them the way we want them.
871bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
873 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
874 while (!LoopList.empty()) {
875 Loop *L = LoopList.pop_back_val();
876 llvm::append_range(LoopList, *L);
877 if (BasicBlock *Preheader = L->getLoopPreheader())
878 Preheaders.insert(Preheader);
879 }
880
881 bool MadeChange = false;
882 // Copy blocks into a temporary array to avoid iterator invalidation issues
883 // as we remove them.
884 // Note that this intentionally skips the entry block.
886 for (auto &Block : llvm::drop_begin(F)) {
887 // Delete phi nodes that could block deleting other empty blocks.
889 MadeChange |= DeleteDeadPHIs(&Block, TLInfo);
890 Blocks.push_back(&Block);
891 }
892
893 for (auto &Block : Blocks) {
894 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
895 if (!BB)
896 continue;
897 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
898 if (!DestBB ||
899 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
900 continue;
901
902 eliminateMostlyEmptyBlock(BB);
903 MadeChange = true;
904 }
905 return MadeChange;
906}
907
908bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
909 BasicBlock *DestBB,
910 bool isPreheader) {
911 // Do not delete loop preheaders if doing so would create a critical edge.
912 // Loop preheaders can be good locations to spill registers. If the
913 // preheader is deleted and we create a critical edge, registers may be
914 // spilled in the loop body instead.
915 if (!DisablePreheaderProtect && isPreheader &&
916 !(BB->getSinglePredecessor() &&
918 return false;
919
920 // Skip merging if the block's successor is also a successor to any callbr
921 // that leads to this block.
922 // FIXME: Is this really needed? Is this a correctness issue?
923 for (BasicBlock *Pred : predecessors(BB)) {
924 if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
925 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
926 if (DestBB == CBI->getSuccessor(i))
927 return false;
928 }
929
930 // Try to skip merging if the unique predecessor of BB is terminated by a
931 // switch or indirect branch instruction, and BB is used as an incoming block
932 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
933 // add COPY instructions in the predecessor of BB instead of BB (if it is not
934 // merged). Note that the critical edge created by merging such blocks wont be
935 // split in MachineSink because the jump table is not analyzable. By keeping
936 // such empty block (BB), ISel will place COPY instructions in BB, not in the
937 // predecessor of BB.
938 BasicBlock *Pred = BB->getUniquePredecessor();
939 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
940 isa<IndirectBrInst>(Pred->getTerminator())))
941 return true;
942
943 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
944 return true;
945
946 // We use a simple cost heuristic which determine skipping merging is
947 // profitable if the cost of skipping merging is less than the cost of
948 // merging : Cost(skipping merging) < Cost(merging BB), where the
949 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
950 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
951 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
952 // Freq(Pred) / Freq(BB) > 2.
953 // Note that if there are multiple empty blocks sharing the same incoming
954 // value for the PHIs in the DestBB, we consider them together. In such
955 // case, Cost(merging BB) will be the sum of their frequencies.
956
957 if (!isa<PHINode>(DestBB->begin()))
958 return true;
959
960 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
961
962 // Find all other incoming blocks from which incoming values of all PHIs in
963 // DestBB are the same as the ones from BB.
964 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
965 if (DestBBPred == BB)
966 continue;
967
968 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
969 return DestPN.getIncomingValueForBlock(BB) ==
970 DestPN.getIncomingValueForBlock(DestBBPred);
971 }))
972 SameIncomingValueBBs.insert(DestBBPred);
973 }
974
975 // See if all BB's incoming values are same as the value from Pred. In this
976 // case, no reason to skip merging because COPYs are expected to be place in
977 // Pred already.
978 if (SameIncomingValueBBs.count(Pred))
979 return true;
980
981 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
982 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
983
984 for (auto *SameValueBB : SameIncomingValueBBs)
985 if (SameValueBB->getUniquePredecessor() == Pred &&
986 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
987 BBFreq += BFI->getBlockFreq(SameValueBB);
988
989 std::optional<BlockFrequency> Limit = BBFreq.mul(FreqRatioToSkipMerge);
990 return !Limit || PredFreq <= *Limit;
991}
992
993/// Return true if we can merge BB into DestBB if there is a single
994/// unconditional branch between them, and BB contains no other non-phi
995/// instructions.
996bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
997 const BasicBlock *DestBB) const {
998 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
999 // the successor. If there are more complex condition (e.g. preheaders),
1000 // don't mess around with them.
1001 for (const PHINode &PN : BB->phis()) {
1002 for (const User *U : PN.users()) {
1003 const Instruction *UI = cast<Instruction>(U);
1004 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
1005 return false;
1006 // If User is inside DestBB block and it is a PHINode then check
1007 // incoming value. If incoming value is not from BB then this is
1008 // a complex condition (e.g. preheaders) we want to avoid here.
1009 if (UI->getParent() == DestBB) {
1010 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
1011 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1012 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
1013 if (Insn && Insn->getParent() == BB &&
1014 Insn->getParent() != UPN->getIncomingBlock(I))
1015 return false;
1016 }
1017 }
1018 }
1019 }
1020
1021 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1022 // and DestBB may have conflicting incoming values for the block. If so, we
1023 // can't merge the block.
1024 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
1025 if (!DestBBPN)
1026 return true; // no conflict.
1027
1028 // Collect the preds of BB.
1030 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1031 // It is faster to get preds from a PHI than with pred_iterator.
1032 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1033 BBPreds.insert(BBPN->getIncomingBlock(i));
1034 } else {
1035 BBPreds.insert(pred_begin(BB), pred_end(BB));
1036 }
1037
1038 // Walk the preds of DestBB.
1039 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1040 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1041 if (BBPreds.count(Pred)) { // Common predecessor?
1042 for (const PHINode &PN : DestBB->phis()) {
1043 const Value *V1 = PN.getIncomingValueForBlock(Pred);
1044 const Value *V2 = PN.getIncomingValueForBlock(BB);
1045
1046 // If V2 is a phi node in BB, look up what the mapped value will be.
1047 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
1048 if (V2PN->getParent() == BB)
1049 V2 = V2PN->getIncomingValueForBlock(Pred);
1050
1051 // If there is a conflict, bail out.
1052 if (V1 != V2)
1053 return false;
1054 }
1055 }
1056 }
1057
1058 return true;
1059}
1060
1061/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1062static void replaceAllUsesWith(Value *Old, Value *New,
1064 bool IsHuge) {
1065 auto *OldI = dyn_cast<Instruction>(Old);
1066 if (OldI) {
1067 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1068 UI != E; ++UI) {
1069 Instruction *User = cast<Instruction>(*UI);
1070 if (IsHuge)
1071 FreshBBs.insert(User->getParent());
1072 }
1073 }
1074 Old->replaceAllUsesWith(New);
1075}
1076
1077/// Eliminate a basic block that has only phi's and an unconditional branch in
1078/// it.
1079void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1080 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
1081 BasicBlock *DestBB = BI->getSuccessor(0);
1082
1083 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1084 << *BB << *DestBB);
1085
1086 // If the destination block has a single pred, then this is a trivial edge,
1087 // just collapse it.
1088 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1089 if (SinglePred != DestBB) {
1090 assert(SinglePred == BB &&
1091 "Single predecessor not the same as predecessor");
1092 // Merge DestBB into SinglePred/BB and delete it.
1094 // Note: BB(=SinglePred) will not be deleted on this path.
1095 // DestBB(=its single successor) is the one that was deleted.
1096 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1097
1098 if (IsHugeFunc) {
1099 // Update FreshBBs to optimize the merged BB.
1100 FreshBBs.insert(SinglePred);
1101 FreshBBs.erase(DestBB);
1102 }
1103 return;
1104 }
1105 }
1106
1107 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1108 // to handle the new incoming edges it is about to have.
1109 for (PHINode &PN : DestBB->phis()) {
1110 // Remove the incoming value for BB, and remember it.
1111 Value *InVal = PN.removeIncomingValue(BB, false);
1112
1113 // Two options: either the InVal is a phi node defined in BB or it is some
1114 // value that dominates BB.
1115 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1116 if (InValPhi && InValPhi->getParent() == BB) {
1117 // Add all of the input values of the input PHI as inputs of this phi.
1118 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1119 PN.addIncoming(InValPhi->getIncomingValue(i),
1120 InValPhi->getIncomingBlock(i));
1121 } else {
1122 // Otherwise, add one instance of the dominating value for each edge that
1123 // we will be adding.
1124 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1125 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1126 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1127 } else {
1128 for (BasicBlock *Pred : predecessors(BB))
1129 PN.addIncoming(InVal, Pred);
1130 }
1131 }
1132 }
1133
1134 // The PHIs are now updated, change everything that refers to BB to use
1135 // DestBB and remove BB.
1136 BB->replaceAllUsesWith(DestBB);
1137 BB->eraseFromParent();
1138 ++NumBlocksElim;
1139
1140 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1141}
1142
1143// Computes a map of base pointer relocation instructions to corresponding
1144// derived pointer relocation instructions given a vector of all relocate calls
1146 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1148 &RelocateInstMap) {
1149 // Collect information in two maps: one primarily for locating the base object
1150 // while filling the second map; the second map is the final structure holding
1151 // a mapping between Base and corresponding Derived relocate calls
1153 for (auto *ThisRelocate : AllRelocateCalls) {
1154 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1155 ThisRelocate->getDerivedPtrIndex());
1156 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1157 }
1158 for (auto &Item : RelocateIdxMap) {
1159 std::pair<unsigned, unsigned> Key = Item.first;
1160 if (Key.first == Key.second)
1161 // Base relocation: nothing to insert
1162 continue;
1163
1164 GCRelocateInst *I = Item.second;
1165 auto BaseKey = std::make_pair(Key.first, Key.first);
1166
1167 // We're iterating over RelocateIdxMap so we cannot modify it.
1168 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1169 if (MaybeBase == RelocateIdxMap.end())
1170 // TODO: We might want to insert a new base object relocate and gep off
1171 // that, if there are enough derived object relocates.
1172 continue;
1173
1174 RelocateInstMap[MaybeBase->second].push_back(I);
1175 }
1176}
1177
1178// Accepts a GEP and extracts the operands into a vector provided they're all
1179// small integer constants
1181 SmallVectorImpl<Value *> &OffsetV) {
1182 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1183 // Only accept small constant integer operands
1184 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1185 if (!Op || Op->getZExtValue() > 20)
1186 return false;
1187 }
1188
1189 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1190 OffsetV.push_back(GEP->getOperand(i));
1191 return true;
1192}
1193
1194// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1195// replace, computes a replacement, and affects it.
1196static bool
1198 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1199 bool MadeChange = false;
1200 // We must ensure the relocation of derived pointer is defined after
1201 // relocation of base pointer. If we find a relocation corresponding to base
1202 // defined earlier than relocation of base then we move relocation of base
1203 // right before found relocation. We consider only relocation in the same
1204 // basic block as relocation of base. Relocations from other basic block will
1205 // be skipped by optimization and we do not care about them.
1206 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1207 &*R != RelocatedBase; ++R)
1208 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1209 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1210 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1211 RelocatedBase->moveBefore(RI);
1212 MadeChange = true;
1213 break;
1214 }
1215
1216 for (GCRelocateInst *ToReplace : Targets) {
1217 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1218 "Not relocating a derived object of the original base object");
1219 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1220 // A duplicate relocate call. TODO: coalesce duplicates.
1221 continue;
1222 }
1223
1224 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1225 // Base and derived relocates are in different basic blocks.
1226 // In this case transform is only valid when base dominates derived
1227 // relocate. However it would be too expensive to check dominance
1228 // for each such relocate, so we skip the whole transformation.
1229 continue;
1230 }
1231
1232 Value *Base = ToReplace->getBasePtr();
1233 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1234 if (!Derived || Derived->getPointerOperand() != Base)
1235 continue;
1236
1238 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1239 continue;
1240
1241 // Create a Builder and replace the target callsite with a gep
1242 assert(RelocatedBase->getNextNode() &&
1243 "Should always have one since it's not a terminator");
1244
1245 // Insert after RelocatedBase
1246 IRBuilder<> Builder(RelocatedBase->getNextNode());
1247 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1248
1249 // If gc_relocate does not match the actual type, cast it to the right type.
1250 // In theory, there must be a bitcast after gc_relocate if the type does not
1251 // match, and we should reuse it to get the derived pointer. But it could be
1252 // cases like this:
1253 // bb1:
1254 // ...
1255 // %g1 = call coldcc i8 addrspace(1)*
1256 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1257 //
1258 // bb2:
1259 // ...
1260 // %g2 = call coldcc i8 addrspace(1)*
1261 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1262 //
1263 // merge:
1264 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1265 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1266 //
1267 // In this case, we can not find the bitcast any more. So we insert a new
1268 // bitcast no matter there is already one or not. In this way, we can handle
1269 // all cases, and the extra bitcast should be optimized away in later
1270 // passes.
1271 Value *ActualRelocatedBase = RelocatedBase;
1272 if (RelocatedBase->getType() != Base->getType()) {
1273 ActualRelocatedBase =
1274 Builder.CreateBitCast(RelocatedBase, Base->getType());
1275 }
1276 Value *Replacement =
1277 Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
1278 ArrayRef(OffsetV));
1279 Replacement->takeName(ToReplace);
1280 // If the newly generated derived pointer's type does not match the original
1281 // derived pointer's type, cast the new derived pointer to match it. Same
1282 // reasoning as above.
1283 Value *ActualReplacement = Replacement;
1284 if (Replacement->getType() != ToReplace->getType()) {
1285 ActualReplacement =
1286 Builder.CreateBitCast(Replacement, ToReplace->getType());
1287 }
1288 ToReplace->replaceAllUsesWith(ActualReplacement);
1289 ToReplace->eraseFromParent();
1290
1291 MadeChange = true;
1292 }
1293 return MadeChange;
1294}
1295
1296// Turns this:
1297//
1298// %base = ...
1299// %ptr = gep %base + 15
1300// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1301// %base' = relocate(%tok, i32 4, i32 4)
1302// %ptr' = relocate(%tok, i32 4, i32 5)
1303// %val = load %ptr'
1304//
1305// into this:
1306//
1307// %base = ...
1308// %ptr = gep %base + 15
1309// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1310// %base' = gc.relocate(%tok, i32 4, i32 4)
1311// %ptr' = gep %base' + 15
1312// %val = load %ptr'
1313bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1314 bool MadeChange = false;
1315 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1316 for (auto *U : I.users())
1317 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1318 // Collect all the relocate calls associated with a statepoint
1319 AllRelocateCalls.push_back(Relocate);
1320
1321 // We need at least one base pointer relocation + one derived pointer
1322 // relocation to mangle
1323 if (AllRelocateCalls.size() < 2)
1324 return false;
1325
1326 // RelocateInstMap is a mapping from the base relocate instruction to the
1327 // corresponding derived relocate instructions
1329 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1330 if (RelocateInstMap.empty())
1331 return false;
1332
1333 for (auto &Item : RelocateInstMap)
1334 // Item.first is the RelocatedBase to offset against
1335 // Item.second is the vector of Targets to replace
1336 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1337 return MadeChange;
1338}
1339
1340/// Sink the specified cast instruction into its user blocks.
1341static bool SinkCast(CastInst *CI) {
1342 BasicBlock *DefBB = CI->getParent();
1343
1344 /// InsertedCasts - Only insert a cast in each block once.
1346
1347 bool MadeChange = false;
1348 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1349 UI != E;) {
1350 Use &TheUse = UI.getUse();
1351 Instruction *User = cast<Instruction>(*UI);
1352
1353 // Figure out which BB this cast is used in. For PHI's this is the
1354 // appropriate predecessor block.
1355 BasicBlock *UserBB = User->getParent();
1356 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1357 UserBB = PN->getIncomingBlock(TheUse);
1358 }
1359
1360 // Preincrement use iterator so we don't invalidate it.
1361 ++UI;
1362
1363 // The first insertion point of a block containing an EH pad is after the
1364 // pad. If the pad is the user, we cannot sink the cast past the pad.
1365 if (User->isEHPad())
1366 continue;
1367
1368 // If the block selected to receive the cast is an EH pad that does not
1369 // allow non-PHI instructions before the terminator, we can't sink the
1370 // cast.
1371 if (UserBB->getTerminator()->isEHPad())
1372 continue;
1373
1374 // If this user is in the same block as the cast, don't change the cast.
1375 if (UserBB == DefBB)
1376 continue;
1377
1378 // If we have already inserted a cast into this block, use it.
1379 CastInst *&InsertedCast = InsertedCasts[UserBB];
1380
1381 if (!InsertedCast) {
1382 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1383 assert(InsertPt != UserBB->end());
1384 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1385 CI->getType(), "", &*InsertPt);
1386 InsertedCast->setDebugLoc(CI->getDebugLoc());
1387 }
1388
1389 // Replace a use of the cast with a use of the new cast.
1390 TheUse = InsertedCast;
1391 MadeChange = true;
1392 ++NumCastUses;
1393 }
1394
1395 // If we removed all uses, nuke the cast.
1396 if (CI->use_empty()) {
1397 salvageDebugInfo(*CI);
1398 CI->eraseFromParent();
1399 MadeChange = true;
1400 }
1401
1402 return MadeChange;
1403}
1404
1405/// If the specified cast instruction is a noop copy (e.g. it's casting from
1406/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1407/// reduce the number of virtual registers that must be created and coalesced.
1408///
1409/// Return true if any changes are made.
1411 const DataLayout &DL) {
1412 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1413 // than sinking only nop casts, but is helpful on some platforms.
1414 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1415 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1416 ASC->getDestAddressSpace()))
1417 return false;
1418 }
1419
1420 // If this is a noop copy,
1421 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1422 EVT DstVT = TLI.getValueType(DL, CI->getType());
1423
1424 // This is an fp<->int conversion?
1425 if (SrcVT.isInteger() != DstVT.isInteger())
1426 return false;
1427
1428 // If this is an extension, it will be a zero or sign extension, which
1429 // isn't a noop.
1430 if (SrcVT.bitsLT(DstVT))
1431 return false;
1432
1433 // If these values will be promoted, find out what they will be promoted
1434 // to. This helps us consider truncates on PPC as noop copies when they
1435 // are.
1436 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1437 TargetLowering::TypePromoteInteger)
1438 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1439 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1440 TargetLowering::TypePromoteInteger)
1441 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1442
1443 // If, after promotion, these are the same types, this is a noop copy.
1444 if (SrcVT != DstVT)
1445 return false;
1446
1447 return SinkCast(CI);
1448}
1449
1450// Match a simple increment by constant operation. Note that if a sub is
1451// matched, the step is negated (as if the step had been canonicalized to
1452// an add, even though we leave the instruction alone.)
1453bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1454 Constant *&Step) {
1455 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1456 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
1457 m_Instruction(LHS), m_Constant(Step)))))
1458 return true;
1459 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1460 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
1461 m_Instruction(LHS), m_Constant(Step))))) {
1462 Step = ConstantExpr::getNeg(Step);
1463 return true;
1464 }
1465 return false;
1466}
1467
1468/// If given \p PN is an inductive variable with value IVInc coming from the
1469/// backedge, and on each iteration it gets increased by Step, return pair
1470/// <IVInc, Step>. Otherwise, return std::nullopt.
1471static std::optional<std::pair<Instruction *, Constant *>>
1472getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1473 const Loop *L = LI->getLoopFor(PN->getParent());
1474 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1475 return std::nullopt;
1476 auto *IVInc =
1477 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1478 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1479 return std::nullopt;
1480 Instruction *LHS = nullptr;
1481 Constant *Step = nullptr;
1482 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1483 return std::make_pair(IVInc, Step);
1484 return std::nullopt;
1485}
1486
1487static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1488 auto *I = dyn_cast<Instruction>(V);
1489 if (!I)
1490 return false;
1491 Instruction *LHS = nullptr;
1492 Constant *Step = nullptr;
1493 if (!matchIncrement(I, LHS, Step))
1494 return false;
1495 if (auto *PN = dyn_cast<PHINode>(LHS))
1496 if (auto IVInc = getIVIncrement(PN, LI))
1497 return IVInc->first == I;
1498 return false;
1499}
1500
1501bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1502 Value *Arg0, Value *Arg1,
1503 CmpInst *Cmp,
1504 Intrinsic::ID IID) {
1505 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1506 if (!isIVIncrement(BO, LI))
1507 return false;
1508 const Loop *L = LI->getLoopFor(BO->getParent());
1509 assert(L && "L should not be null after isIVIncrement()");
1510 // Do not risk on moving increment into a child loop.
1511 if (LI->getLoopFor(Cmp->getParent()) != L)
1512 return false;
1513
1514 // Finally, we need to ensure that the insert point will dominate all
1515 // existing uses of the increment.
1516
1517 auto &DT = getDT(*BO->getParent()->getParent());
1518 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1519 // If we're moving up the dom tree, all uses are trivially dominated.
1520 // (This is the common case for code produced by LSR.)
1521 return true;
1522
1523 // Otherwise, special case the single use in the phi recurrence.
1524 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1525 };
1526 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1527 // We used to use a dominator tree here to allow multi-block optimization.
1528 // But that was problematic because:
1529 // 1. It could cause a perf regression by hoisting the math op into the
1530 // critical path.
1531 // 2. It could cause a perf regression by creating a value that was live
1532 // across multiple blocks and increasing register pressure.
1533 // 3. Use of a dominator tree could cause large compile-time regression.
1534 // This is because we recompute the DT on every change in the main CGP
1535 // run-loop. The recomputing is probably unnecessary in many cases, so if
1536 // that was fixed, using a DT here would be ok.
1537 //
1538 // There is one important particular case we still want to handle: if BO is
1539 // the IV increment. Important properties that make it profitable:
1540 // - We can speculate IV increment anywhere in the loop (as long as the
1541 // indvar Phi is its only user);
1542 // - Upon computing Cmp, we effectively compute something equivalent to the
1543 // IV increment (despite it loops differently in the IR). So moving it up
1544 // to the cmp point does not really increase register pressure.
1545 return false;
1546 }
1547
1548 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1549 if (BO->getOpcode() == Instruction::Add &&
1550 IID == Intrinsic::usub_with_overflow) {
1551 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1552 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1553 }
1554
1555 // Insert at the first instruction of the pair.
1556 Instruction *InsertPt = nullptr;
1557 for (Instruction &Iter : *Cmp->getParent()) {
1558 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1559 // the overflow intrinsic are defined.
1560 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1561 InsertPt = &Iter;
1562 break;
1563 }
1564 }
1565 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1566
1567 IRBuilder<> Builder(InsertPt);
1568 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1569 if (BO->getOpcode() != Instruction::Xor) {
1570 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1571 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1572 } else
1573 assert(BO->hasOneUse() &&
1574 "Patterns with XOr should use the BO only in the compare");
1575 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1576 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1577 Cmp->eraseFromParent();
1578 BO->eraseFromParent();
1579 return true;
1580}
1581
1582/// Match special-case patterns that check for unsigned add overflow.
1584 BinaryOperator *&Add) {
1585 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1586 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1587 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1588
1589 // We are not expecting non-canonical/degenerate code. Just bail out.
1590 if (isa<Constant>(A))
1591 return false;
1592
1593 ICmpInst::Predicate Pred = Cmp->getPredicate();
1594 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1595 B = ConstantInt::get(B->getType(), 1);
1596 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1597 B = ConstantInt::get(B->getType(), -1);
1598 else
1599 return false;
1600
1601 // Check the users of the variable operand of the compare looking for an add
1602 // with the adjusted constant.
1603 for (User *U : A->users()) {
1604 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1605 Add = cast<BinaryOperator>(U);
1606 return true;
1607 }
1608 }
1609 return false;
1610}
1611
1612/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1613/// intrinsic. Return true if any changes were made.
1614bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1615 ModifyDT &ModifiedDT) {
1616 bool EdgeCase = false;
1617 Value *A, *B;
1619 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1621 return false;
1622 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1623 A = Add->getOperand(0);
1624 B = Add->getOperand(1);
1625 EdgeCase = true;
1626 }
1627
1629 TLI->getValueType(*DL, Add->getType()),
1630 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1631 return false;
1632
1633 // We don't want to move around uses of condition values this late, so we
1634 // check if it is legal to create the call to the intrinsic in the basic
1635 // block containing the icmp.
1636 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1637 return false;
1638
1639 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1640 Intrinsic::uadd_with_overflow))
1641 return false;
1642
1643 // Reset callers - do not crash by iterating over a dead instruction.
1644 ModifiedDT = ModifyDT::ModifyInstDT;
1645 return true;
1646}
1647
1648bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1649 ModifyDT &ModifiedDT) {
1650 // We are not expecting non-canonical/degenerate code. Just bail out.
1651 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1652 if (isa<Constant>(A) && isa<Constant>(B))
1653 return false;
1654
1655 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1656 ICmpInst::Predicate Pred = Cmp->getPredicate();
1657 if (Pred == ICmpInst::ICMP_UGT) {
1658 std::swap(A, B);
1659 Pred = ICmpInst::ICMP_ULT;
1660 }
1661 // Convert special-case: (A == 0) is the same as (A u< 1).
1662 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1663 B = ConstantInt::get(B->getType(), 1);
1664 Pred = ICmpInst::ICMP_ULT;
1665 }
1666 // Convert special-case: (A != 0) is the same as (0 u< A).
1667 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1668 std::swap(A, B);
1669 Pred = ICmpInst::ICMP_ULT;
1670 }
1671 if (Pred != ICmpInst::ICMP_ULT)
1672 return false;
1673
1674 // Walk the users of a variable operand of a compare looking for a subtract or
1675 // add with that same operand. Also match the 2nd operand of the compare to
1676 // the add/sub, but that may be a negated constant operand of an add.
1677 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1678 BinaryOperator *Sub = nullptr;
1679 for (User *U : CmpVariableOperand->users()) {
1680 // A - B, A u< B --> usubo(A, B)
1681 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1682 Sub = cast<BinaryOperator>(U);
1683 break;
1684 }
1685
1686 // A + (-C), A u< C (canonicalized form of (sub A, C))
1687 const APInt *CmpC, *AddC;
1688 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1689 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1690 Sub = cast<BinaryOperator>(U);
1691 break;
1692 }
1693 }
1694 if (!Sub)
1695 return false;
1696
1698 TLI->getValueType(*DL, Sub->getType()),
1699 Sub->hasNUsesOrMore(1)))
1700 return false;
1701
1702 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1703 Cmp, Intrinsic::usub_with_overflow))
1704 return false;
1705
1706 // Reset callers - do not crash by iterating over a dead instruction.
1707 ModifiedDT = ModifyDT::ModifyInstDT;
1708 return true;
1709}
1710
1711/// Sink the given CmpInst into user blocks to reduce the number of virtual
1712/// registers that must be created and coalesced. This is a clear win except on
1713/// targets with multiple condition code registers (PowerPC), where it might
1714/// lose; some adjustment may be wanted there.
1715///
1716/// Return true if any changes are made.
1717static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1719 return false;
1720
1721 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1722 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1723 return false;
1724
1725 // Only insert a cmp in each block once.
1727
1728 bool MadeChange = false;
1729 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1730 UI != E;) {
1731 Use &TheUse = UI.getUse();
1732 Instruction *User = cast<Instruction>(*UI);
1733
1734 // Preincrement use iterator so we don't invalidate it.
1735 ++UI;
1736
1737 // Don't bother for PHI nodes.
1738 if (isa<PHINode>(User))
1739 continue;
1740
1741 // Figure out which BB this cmp is used in.
1742 BasicBlock *UserBB = User->getParent();
1743 BasicBlock *DefBB = Cmp->getParent();
1744
1745 // If this user is in the same block as the cmp, don't change the cmp.
1746 if (UserBB == DefBB)
1747 continue;
1748
1749 // If we have already inserted a cmp into this block, use it.
1750 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1751
1752 if (!InsertedCmp) {
1753 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1754 assert(InsertPt != UserBB->end());
1755 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1756 Cmp->getOperand(0), Cmp->getOperand(1), "",
1757 &*InsertPt);
1758 // Propagate the debug info.
1759 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1760 }
1761
1762 // Replace a use of the cmp with a use of the new cmp.
1763 TheUse = InsertedCmp;
1764 MadeChange = true;
1765 ++NumCmpUses;
1766 }
1767
1768 // If we removed all uses, nuke the cmp.
1769 if (Cmp->use_empty()) {
1770 Cmp->eraseFromParent();
1771 MadeChange = true;
1772 }
1773
1774 return MadeChange;
1775}
1776
1777/// For pattern like:
1778///
1779/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1780/// ...
1781/// DomBB:
1782/// ...
1783/// br DomCond, TrueBB, CmpBB
1784/// CmpBB: (with DomBB being the single predecessor)
1785/// ...
1786/// Cmp = icmp eq CmpOp0, CmpOp1
1787/// ...
1788///
1789/// It would use two comparison on targets that lowering of icmp sgt/slt is
1790/// different from lowering of icmp eq (PowerPC). This function try to convert
1791/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1792/// After that, DomCond and Cmp can use the same comparison so reduce one
1793/// comparison.
1794///
1795/// Return true if any changes are made.
1797 const TargetLowering &TLI) {
1799 return false;
1800
1801 ICmpInst::Predicate Pred = Cmp->getPredicate();
1802 if (Pred != ICmpInst::ICMP_EQ)
1803 return false;
1804
1805 // If icmp eq has users other than BranchInst and SelectInst, converting it to
1806 // icmp slt/sgt would introduce more redundant LLVM IR.
1807 for (User *U : Cmp->users()) {
1808 if (isa<BranchInst>(U))
1809 continue;
1810 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1811 continue;
1812 return false;
1813 }
1814
1815 // This is a cheap/incomplete check for dominance - just match a single
1816 // predecessor with a conditional branch.
1817 BasicBlock *CmpBB = Cmp->getParent();
1818 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1819 if (!DomBB)
1820 return false;
1821
1822 // We want to ensure that the only way control gets to the comparison of
1823 // interest is that a less/greater than comparison on the same operands is
1824 // false.
1825 Value *DomCond;
1826 BasicBlock *TrueBB, *FalseBB;
1827 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1828 return false;
1829 if (CmpBB != FalseBB)
1830 return false;
1831
1832 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1833 ICmpInst::Predicate DomPred;
1834 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1835 return false;
1836 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1837 return false;
1838
1839 // Convert the equality comparison to the opposite of the dominating
1840 // comparison and swap the direction for all branch/select users.
1841 // We have conceptually converted:
1842 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1843 // to
1844 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1845 // And similarly for branches.
1846 for (User *U : Cmp->users()) {
1847 if (auto *BI = dyn_cast<BranchInst>(U)) {
1848 assert(BI->isConditional() && "Must be conditional");
1849 BI->swapSuccessors();
1850 continue;
1851 }
1852 if (auto *SI = dyn_cast<SelectInst>(U)) {
1853 // Swap operands
1854 SI->swapValues();
1855 SI->swapProfMetadata();
1856 continue;
1857 }
1858 llvm_unreachable("Must be a branch or a select");
1859 }
1860 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1861 return true;
1862}
1863
1864/// Many architectures use the same instruction for both subtract and cmp. Try
1865/// to swap cmp operands to match subtract operations to allow for CSE.
1867 Value *Op0 = Cmp->getOperand(0);
1868 Value *Op1 = Cmp->getOperand(1);
1869 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
1870 isa<Constant>(Op1) || Op0 == Op1)
1871 return false;
1872
1873 // If a subtract already has the same operands as a compare, swapping would be
1874 // bad. If a subtract has the same operands as a compare but in reverse order,
1875 // then swapping is good.
1876 int GoodToSwap = 0;
1877 unsigned NumInspected = 0;
1878 for (const User *U : Op0->users()) {
1879 // Avoid walking many users.
1880 if (++NumInspected > 128)
1881 return false;
1882 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
1883 GoodToSwap++;
1884 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
1885 GoodToSwap--;
1886 }
1887
1888 if (GoodToSwap > 0) {
1889 Cmp->swapOperands();
1890 return true;
1891 }
1892 return false;
1893}
1894
1895bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
1896 if (sinkCmpExpression(Cmp, *TLI))
1897 return true;
1898
1899 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1900 return true;
1901
1902 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1903 return true;
1904
1905 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1906 return true;
1907
1909 return true;
1910
1911 return false;
1912}
1913
1914/// Duplicate and sink the given 'and' instruction into user blocks where it is
1915/// used in a compare to allow isel to generate better code for targets where
1916/// this operation can be combined.
1917///
1918/// Return true if any changes are made.
1920 SetOfInstrs &InsertedInsts) {
1921 // Double-check that we're not trying to optimize an instruction that was
1922 // already optimized by some other part of this pass.
1923 assert(!InsertedInsts.count(AndI) &&
1924 "Attempting to optimize already optimized and instruction");
1925 (void)InsertedInsts;
1926
1927 // Nothing to do for single use in same basic block.
1928 if (AndI->hasOneUse() &&
1929 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1930 return false;
1931
1932 // Try to avoid cases where sinking/duplicating is likely to increase register
1933 // pressure.
1934 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1935 !isa<ConstantInt>(AndI->getOperand(1)) &&
1936 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1937 return false;
1938
1939 for (auto *U : AndI->users()) {
1940 Instruction *User = cast<Instruction>(U);
1941
1942 // Only sink 'and' feeding icmp with 0.
1943 if (!isa<ICmpInst>(User))
1944 return false;
1945
1946 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1947 if (!CmpC || !CmpC->isZero())
1948 return false;
1949 }
1950
1951 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1952 return false;
1953
1954 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1955 LLVM_DEBUG(AndI->getParent()->dump());
1956
1957 // Push the 'and' into the same block as the icmp 0. There should only be
1958 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1959 // others, so we don't need to keep track of which BBs we insert into.
1960 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1961 UI != E;) {
1962 Use &TheUse = UI.getUse();
1963 Instruction *User = cast<Instruction>(*UI);
1964
1965 // Preincrement use iterator so we don't invalidate it.
1966 ++UI;
1967
1968 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1969
1970 // Keep the 'and' in the same place if the use is already in the same block.
1971 Instruction *InsertPt =
1972 User->getParent() == AndI->getParent() ? AndI : User;
1973 Instruction *InsertedAnd =
1974 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1975 AndI->getOperand(1), "", InsertPt);
1976 // Propagate the debug info.
1977 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1978
1979 // Replace a use of the 'and' with a use of the new 'and'.
1980 TheUse = InsertedAnd;
1981 ++NumAndUses;
1982 LLVM_DEBUG(User->getParent()->dump());
1983 }
1984
1985 // We removed all uses, nuke the and.
1986 AndI->eraseFromParent();
1987 return true;
1988}
1989
1990/// Check if the candidates could be combined with a shift instruction, which
1991/// includes:
1992/// 1. Truncate instruction
1993/// 2. And instruction and the imm is a mask of the low bits:
1994/// imm & (imm+1) == 0
1996 if (!isa<TruncInst>(User)) {
1997 if (User->getOpcode() != Instruction::And ||
1998 !isa<ConstantInt>(User->getOperand(1)))
1999 return false;
2000
2001 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2002
2003 if ((Cimm & (Cimm + 1)).getBoolValue())
2004 return false;
2005 }
2006 return true;
2007}
2008
2009/// Sink both shift and truncate instruction to the use of truncate's BB.
2010static bool
2013 const TargetLowering &TLI, const DataLayout &DL) {
2014 BasicBlock *UserBB = User->getParent();
2016 auto *TruncI = cast<TruncInst>(User);
2017 bool MadeChange = false;
2018
2019 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2020 TruncE = TruncI->user_end();
2021 TruncUI != TruncE;) {
2022
2023 Use &TruncTheUse = TruncUI.getUse();
2024 Instruction *TruncUser = cast<Instruction>(*TruncUI);
2025 // Preincrement use iterator so we don't invalidate it.
2026
2027 ++TruncUI;
2028
2029 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2030 if (!ISDOpcode)
2031 continue;
2032
2033 // If the use is actually a legal node, there will not be an
2034 // implicit truncate.
2035 // FIXME: always querying the result type is just an
2036 // approximation; some nodes' legality is determined by the
2037 // operand or other means. There's no good way to find out though.
2039 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2040 continue;
2041
2042 // Don't bother for PHI nodes.
2043 if (isa<PHINode>(TruncUser))
2044 continue;
2045
2046 BasicBlock *TruncUserBB = TruncUser->getParent();
2047
2048 if (UserBB == TruncUserBB)
2049 continue;
2050
2051 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2052 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2053
2054 if (!InsertedShift && !InsertedTrunc) {
2055 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2056 assert(InsertPt != TruncUserBB->end());
2057 // Sink the shift
2058 if (ShiftI->getOpcode() == Instruction::AShr)
2059 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2060 "", &*InsertPt);
2061 else
2062 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2063 "", &*InsertPt);
2064 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2065
2066 // Sink the trunc
2067 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2068 TruncInsertPt++;
2069 assert(TruncInsertPt != TruncUserBB->end());
2070
2071 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2072 TruncI->getType(), "", &*TruncInsertPt);
2073 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2074
2075 MadeChange = true;
2076
2077 TruncTheUse = InsertedTrunc;
2078 }
2079 }
2080 return MadeChange;
2081}
2082
2083/// Sink the shift *right* instruction into user blocks if the uses could
2084/// potentially be combined with this shift instruction and generate BitExtract
2085/// instruction. It will only be applied if the architecture supports BitExtract
2086/// instruction. Here is an example:
2087/// BB1:
2088/// %x.extract.shift = lshr i64 %arg1, 32
2089/// BB2:
2090/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2091/// ==>
2092///
2093/// BB2:
2094/// %x.extract.shift.1 = lshr i64 %arg1, 32
2095/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2096///
2097/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2098/// instruction.
2099/// Return true if any changes are made.
2101 const TargetLowering &TLI,
2102 const DataLayout &DL) {
2103 BasicBlock *DefBB = ShiftI->getParent();
2104
2105 /// Only insert instructions in each block once.
2107
2108 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2109
2110 bool MadeChange = false;
2111 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2112 UI != E;) {
2113 Use &TheUse = UI.getUse();
2114 Instruction *User = cast<Instruction>(*UI);
2115 // Preincrement use iterator so we don't invalidate it.
2116 ++UI;
2117
2118 // Don't bother for PHI nodes.
2119 if (isa<PHINode>(User))
2120 continue;
2121
2123 continue;
2124
2125 BasicBlock *UserBB = User->getParent();
2126
2127 if (UserBB == DefBB) {
2128 // If the shift and truncate instruction are in the same BB. The use of
2129 // the truncate(TruncUse) may still introduce another truncate if not
2130 // legal. In this case, we would like to sink both shift and truncate
2131 // instruction to the BB of TruncUse.
2132 // for example:
2133 // BB1:
2134 // i64 shift.result = lshr i64 opnd, imm
2135 // trunc.result = trunc shift.result to i16
2136 //
2137 // BB2:
2138 // ----> We will have an implicit truncate here if the architecture does
2139 // not have i16 compare.
2140 // cmp i16 trunc.result, opnd2
2141 //
2142 if (isa<TruncInst>(User) &&
2143 shiftIsLegal
2144 // If the type of the truncate is legal, no truncate will be
2145 // introduced in other basic blocks.
2146 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2147 MadeChange =
2148 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2149
2150 continue;
2151 }
2152 // If we have already inserted a shift into this block, use it.
2153 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2154
2155 if (!InsertedShift) {
2156 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2157 assert(InsertPt != UserBB->end());
2158
2159 if (ShiftI->getOpcode() == Instruction::AShr)
2160 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
2161 "", &*InsertPt);
2162 else
2163 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
2164 "", &*InsertPt);
2165 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2166
2167 MadeChange = true;
2168 }
2169
2170 // Replace a use of the shift with a use of the new shift.
2171 TheUse = InsertedShift;
2172 }
2173
2174 // If we removed all uses, or there are none, nuke the shift.
2175 if (ShiftI->use_empty()) {
2176 salvageDebugInfo(*ShiftI);
2177 ShiftI->eraseFromParent();
2178 MadeChange = true;
2179 }
2180
2181 return MadeChange;
2182}
2183
2184/// If counting leading or trailing zeros is an expensive operation and a zero
2185/// input is defined, add a check for zero to avoid calling the intrinsic.
2186///
2187/// We want to transform:
2188/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2189///
2190/// into:
2191/// entry:
2192/// %cmpz = icmp eq i64 %A, 0
2193/// br i1 %cmpz, label %cond.end, label %cond.false
2194/// cond.false:
2195/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2196/// br label %cond.end
2197/// cond.end:
2198/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2199///
2200/// If the transform is performed, return true and set ModifiedDT to true.
2201static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2202 LoopInfo &LI,
2203 const TargetLowering *TLI,
2204 const DataLayout *DL, ModifyDT &ModifiedDT,
2206 bool IsHugeFunc) {
2207 // If a zero input is undefined, it doesn't make sense to despeculate that.
2208 if (match(CountZeros->getOperand(1), m_One()))
2209 return false;
2210
2211 // If it's cheap to speculate, there's nothing to do.
2212 Type *Ty = CountZeros->getType();
2213 auto IntrinsicID = CountZeros->getIntrinsicID();
2214 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2215 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2216 return false;
2217
2218 // Only handle legal scalar cases. Anything else requires too much work.
2219 unsigned SizeInBits = Ty->getScalarSizeInBits();
2220 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2221 return false;
2222
2223 // Bail if the value is never zero.
2224 Use &Op = CountZeros->getOperandUse(0);
2225 if (isKnownNonZero(Op, *DL))
2226 return false;
2227
2228 // The intrinsic will be sunk behind a compare against zero and branch.
2229 BasicBlock *StartBlock = CountZeros->getParent();
2230 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2231 if (IsHugeFunc)
2232 FreshBBs.insert(CallBlock);
2233
2234 // Create another block after the count zero intrinsic. A PHI will be added
2235 // in this block to select the result of the intrinsic or the bit-width
2236 // constant if the input to the intrinsic is zero.
2237 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2238 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2239 if (IsHugeFunc)
2240 FreshBBs.insert(EndBlock);
2241
2242 // Update the LoopInfo. The new blocks are in the same loop as the start
2243 // block.
2244 if (Loop *L = LI.getLoopFor(StartBlock)) {
2245 L->addBasicBlockToLoop(CallBlock, LI);
2246 L->addBasicBlockToLoop(EndBlock, LI);
2247 }
2248
2249 // Set up a builder to create a compare, conditional branch, and PHI.
2250 IRBuilder<> Builder(CountZeros->getContext());
2251 Builder.SetInsertPoint(StartBlock->getTerminator());
2252 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2253
2254 // Replace the unconditional branch that was created by the first split with
2255 // a compare against zero and a conditional branch.
2256 Value *Zero = Constant::getNullValue(Ty);
2257 // Avoid introducing branch on poison. This also replaces the ctz operand.
2259 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2260 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2261 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2262 StartBlock->getTerminator()->eraseFromParent();
2263
2264 // Create a PHI in the end block to select either the output of the intrinsic
2265 // or the bit width of the operand.
2266 Builder.SetInsertPoint(EndBlock, EndBlock->begin());
2267 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2268 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2269 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2270 PN->addIncoming(BitWidth, StartBlock);
2271 PN->addIncoming(CountZeros, CallBlock);
2272
2273 // We are explicitly handling the zero case, so we can set the intrinsic's
2274 // undefined zero argument to 'true'. This will also prevent reprocessing the
2275 // intrinsic; we only despeculate when a zero input is defined.
2276 CountZeros->setArgOperand(1, Builder.getTrue());
2277 ModifiedDT = ModifyDT::ModifyBBDT;
2278 return true;
2279}
2280
2281bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2282 BasicBlock *BB = CI->getParent();
2283
2284 // Lower inline assembly if we can.
2285 // If we found an inline asm expession, and if the target knows how to
2286 // lower it to normal LLVM code, do so now.
2287 if (CI->isInlineAsm()) {
2288 if (TLI->ExpandInlineAsm(CI)) {
2289 // Avoid invalidating the iterator.
2290 CurInstIterator = BB->begin();
2291 // Avoid processing instructions out of order, which could cause
2292 // reuse before a value is defined.
2293 SunkAddrs.clear();
2294 return true;
2295 }
2296 // Sink address computing for memory operands into the block.
2297 if (optimizeInlineAsmInst(CI))
2298 return true;
2299 }
2300
2301 // Align the pointer arguments to this call if the target thinks it's a good
2302 // idea
2303 unsigned MinSize;
2304 Align PrefAlign;
2305 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2306 for (auto &Arg : CI->args()) {
2307 // We want to align both objects whose address is used directly and
2308 // objects whose address is used in casts and GEPs, though it only makes
2309 // sense for GEPs if the offset is a multiple of the desired alignment and
2310 // if size - offset meets the size threshold.
2311 if (!Arg->getType()->isPointerTy())
2312 continue;
2313 APInt Offset(DL->getIndexSizeInBits(
2314 cast<PointerType>(Arg->getType())->getAddressSpace()),
2315 0);
2317 uint64_t Offset2 = Offset.getLimitedValue();
2318 if (!isAligned(PrefAlign, Offset2))
2319 continue;
2320 AllocaInst *AI;
2321 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
2322 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2323 AI->setAlignment(PrefAlign);
2324 // Global variables can only be aligned if they are defined in this
2325 // object (i.e. they are uniquely initialized in this object), and
2326 // over-aligning global variables that have an explicit section is
2327 // forbidden.
2328 GlobalVariable *GV;
2329 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2330 GV->getPointerAlignment(*DL) < PrefAlign &&
2331 DL->getTypeAllocSize(GV->getValueType()) >= MinSize + Offset2)
2332 GV->setAlignment(PrefAlign);
2333 }
2334 }
2335 // If this is a memcpy (or similar) then we may be able to improve the
2336 // alignment.
2337 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2338 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2339 MaybeAlign MIDestAlign = MI->getDestAlign();
2340 if (!MIDestAlign || DestAlign > *MIDestAlign)
2341 MI->setDestAlignment(DestAlign);
2342 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2343 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2344 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2345 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2346 MTI->setSourceAlignment(SrcAlign);
2347 }
2348 }
2349
2350 // If we have a cold call site, try to sink addressing computation into the
2351 // cold block. This interacts with our handling for loads and stores to
2352 // ensure that we can fold all uses of a potential addressing computation
2353 // into their uses. TODO: generalize this to work over profiling data
2354 if (CI->hasFnAttr(Attribute::Cold) && !OptSize &&
2355 !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2356 for (auto &Arg : CI->args()) {
2357 if (!Arg->getType()->isPointerTy())
2358 continue;
2359 unsigned AS = Arg->getType()->getPointerAddressSpace();
2360 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2361 return true;
2362 }
2363
2364 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2365 if (II) {
2366 switch (II->getIntrinsicID()) {
2367 default:
2368 break;
2369 case Intrinsic::assume:
2370 llvm_unreachable("llvm.assume should have been removed already");
2371 case Intrinsic::experimental_widenable_condition: {
2372 // Give up on future widening oppurtunties so that we can fold away dead
2373 // paths and merge blocks before going into block-local instruction
2374 // selection.
2375 if (II->use_empty()) {
2376 II->eraseFromParent();
2377 return true;
2378 }
2379 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2380 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2381 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2382 });
2383 return true;
2384 }
2385 case Intrinsic::objectsize:
2386 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2387 case Intrinsic::is_constant:
2388 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2389 case Intrinsic::aarch64_stlxr:
2390 case Intrinsic::aarch64_stxr: {
2391 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2392 if (!ExtVal || !ExtVal->hasOneUse() ||
2393 ExtVal->getParent() == CI->getParent())
2394 return false;
2395 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2396 ExtVal->moveBefore(CI);
2397 // Mark this instruction as "inserted by CGP", so that other
2398 // optimizations don't touch it.
2399 InsertedInsts.insert(ExtVal);
2400 return true;
2401 }
2402
2403 case Intrinsic::launder_invariant_group:
2404 case Intrinsic::strip_invariant_group: {
2405 Value *ArgVal = II->getArgOperand(0);
2406 auto it = LargeOffsetGEPMap.find(II);
2407 if (it != LargeOffsetGEPMap.end()) {
2408 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2409 // Make sure not to have to deal with iterator invalidation
2410 // after possibly adding ArgVal to LargeOffsetGEPMap.
2411 auto GEPs = std::move(it->second);
2412 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2413 LargeOffsetGEPMap.erase(II);
2414 }
2415
2416 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2417 II->eraseFromParent();
2418 return true;
2419 }
2420 case Intrinsic::cttz:
2421 case Intrinsic::ctlz:
2422 // If counting zeros is expensive, try to avoid it.
2423 return despeculateCountZeros(II, *LI, TLI, DL, ModifiedDT, FreshBBs,
2424 IsHugeFunc);
2425 case Intrinsic::fshl:
2426 case Intrinsic::fshr:
2427 return optimizeFunnelShift(II);
2428 case Intrinsic::dbg_assign:
2429 case Intrinsic::dbg_value:
2430 return fixupDbgValue(II);
2431 case Intrinsic::masked_gather:
2432 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2433 case Intrinsic::masked_scatter:
2434 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2435 }
2436
2438 Type *AccessTy;
2439 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2440 while (!PtrOps.empty()) {
2441 Value *PtrVal = PtrOps.pop_back_val();
2442 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2443 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2444 return true;
2445 }
2446 }
2447
2448 // From here on out we're working with named functions.
2449 if (!CI->getCalledFunction())
2450 return false;
2451
2452 // Lower all default uses of _chk calls. This is very similar
2453 // to what InstCombineCalls does, but here we are only lowering calls
2454 // to fortified library functions (e.g. __memcpy_chk) that have the default
2455 // "don't know" as the objectsize. Anything else should be left alone.
2456 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2457 IRBuilder<> Builder(CI);
2458 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2459 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2460 CI->eraseFromParent();
2461 return true;
2462 }
2463
2464 return false;
2465}
2466
2467/// Look for opportunities to duplicate return instructions to the predecessor
2468/// to enable tail call optimizations. The case it is currently looking for is:
2469/// @code
2470/// bb0:
2471/// %tmp0 = tail call i32 @f0()
2472/// br label %return
2473/// bb1:
2474/// %tmp1 = tail call i32 @f1()
2475/// br label %return
2476/// bb2:
2477/// %tmp2 = tail call i32 @f2()
2478/// br label %return
2479/// return:
2480/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2481/// ret i32 %retval
2482/// @endcode
2483///
2484/// =>
2485///
2486/// @code
2487/// bb0:
2488/// %tmp0 = tail call i32 @f0()
2489/// ret i32 %tmp0
2490/// bb1:
2491/// %tmp1 = tail call i32 @f1()
2492/// ret i32 %tmp1
2493/// bb2:
2494/// %tmp2 = tail call i32 @f2()
2495/// ret i32 %tmp2
2496/// @endcode
2497bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2498 ModifyDT &ModifiedDT) {
2499 if (!BB->getTerminator())
2500 return false;
2501
2502 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2503 if (!RetI)
2504 return false;
2505
2506 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2507
2508 PHINode *PN = nullptr;
2509 ExtractValueInst *EVI = nullptr;
2510 BitCastInst *BCI = nullptr;
2511 Value *V = RetI->getReturnValue();
2512 if (V) {
2513 BCI = dyn_cast<BitCastInst>(V);
2514 if (BCI)
2515 V = BCI->getOperand(0);
2516
2517 EVI = dyn_cast<ExtractValueInst>(V);
2518 if (EVI) {
2519 V = EVI->getOperand(0);
2520 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2521 return false;
2522 }
2523
2524 PN = dyn_cast<PHINode>(V);
2525 if (!PN)
2526 return false;
2527 }
2528
2529 if (PN && PN->getParent() != BB)
2530 return false;
2531
2532 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2533 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2534 if (BC && BC->hasOneUse())
2535 Inst = BC->user_back();
2536
2537 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2538 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2539 return false;
2540 };
2541
2542 // Make sure there are no instructions between the first instruction
2543 // and return.
2544 const Instruction *BI = BB->getFirstNonPHI();
2545 // Skip over debug and the bitcast.
2546 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
2547 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2548 BI = BI->getNextNode();
2549 if (BI != RetI)
2550 return false;
2551
2552 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2553 /// call.
2554 const Function *F = BB->getParent();
2555 SmallVector<BasicBlock *, 4> TailCallBBs;
2556 if (PN) {
2557 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2558 // Look through bitcasts.
2559 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2560 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2561 BasicBlock *PredBB = PN->getIncomingBlock(I);
2562 // Make sure the phi value is indeed produced by the tail call.
2563 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2564 TLI->mayBeEmittedAsTailCall(CI) &&
2565 attributesPermitTailCall(F, CI, RetI, *TLI))
2566 TailCallBBs.push_back(PredBB);
2567 }
2568 } else {
2570 for (BasicBlock *Pred : predecessors(BB)) {
2571 if (!VisitedBBs.insert(Pred).second)
2572 continue;
2573 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2574 CallInst *CI = dyn_cast<CallInst>(I);
2575 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2576 attributesPermitTailCall(F, CI, RetI, *TLI))
2577 TailCallBBs.push_back(Pred);
2578 }
2579 }
2580 }
2581
2582 bool Changed = false;
2583 for (auto const &TailCallBB : TailCallBBs) {
2584 // Make sure the call instruction is followed by an unconditional branch to
2585 // the return block.
2586 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2587 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2588 continue;
2589
2590 // Duplicate the return into TailCallBB.
2591 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2593 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
2594 BFI->setBlockFreq(
2595 BB,
2596 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
2597 ModifiedDT = ModifyDT::ModifyBBDT;
2598 Changed = true;
2599 ++NumRetsDup;
2600 }
2601
2602 // If we eliminated all predecessors of the block, delete the block now.
2603 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2604 BB->eraseFromParent();
2605
2606 return Changed;
2607}
2608
2609//===----------------------------------------------------------------------===//
2610// Memory Optimization
2611//===----------------------------------------------------------------------===//
2612
2613namespace {
2614
2615/// This is an extended version of TargetLowering::AddrMode
2616/// which holds actual Value*'s for register values.
2617struct ExtAddrMode : public TargetLowering::AddrMode {
2618 Value *BaseReg = nullptr;
2619 Value *ScaledReg = nullptr;
2620 Value *OriginalValue = nullptr;
2621 bool InBounds = true;
2622
2623 enum FieldName {
2624 NoField = 0x00,
2625 BaseRegField = 0x01,
2626 BaseGVField = 0x02,
2627 BaseOffsField = 0x04,
2628 ScaledRegField = 0x08,
2629 ScaleField = 0x10,
2630 MultipleFields = 0xff
2631 };
2632
2633 ExtAddrMode() = default;
2634
2635 void print(raw_ostream &OS) const;
2636 void dump() const;
2637
2638 FieldName compare(const ExtAddrMode &other) {
2639 // First check that the types are the same on each field, as differing types
2640 // is something we can't cope with later on.
2641 if (BaseReg && other.BaseReg &&
2642 BaseReg->getType() != other.BaseReg->getType())
2643 return MultipleFields;
2644 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
2645 return MultipleFields;
2646 if (ScaledReg && other.ScaledReg &&
2647 ScaledReg->getType() != other.ScaledReg->getType())
2648 return MultipleFields;
2649
2650 // Conservatively reject 'inbounds' mismatches.
2651 if (InBounds != other.InBounds)
2652 return MultipleFields;
2653
2654 // Check each field to see if it differs.
2655 unsigned Result = NoField;
2656 if (BaseReg != other.BaseReg)
2657 Result |= BaseRegField;
2658 if (BaseGV != other.BaseGV)
2659 Result |= BaseGVField;
2660 if (BaseOffs != other.BaseOffs)
2661 Result |= BaseOffsField;
2662 if (ScaledReg != other.ScaledReg)
2663 Result |= ScaledRegField;
2664 // Don't count 0 as being a different scale, because that actually means
2665 // unscaled (which will already be counted by having no ScaledReg).
2666 if (Scale && other.Scale && Scale != other.Scale)
2667 Result |= ScaleField;
2668
2669 if (llvm::popcount(Result) > 1)
2670 return MultipleFields;
2671 else
2672 return static_cast<FieldName>(Result);
2673 }
2674
2675 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2676 // with no offset.
2677 bool isTrivial() {
2678 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2679 // trivial if at most one of these terms is nonzero, except that BaseGV and
2680 // BaseReg both being zero actually means a null pointer value, which we
2681 // consider to be 'non-zero' here.
2682 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2683 }
2684
2685 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2686 switch (Field) {
2687 default:
2688 return nullptr;
2689 case BaseRegField:
2690 return BaseReg;
2691 case BaseGVField:
2692 return BaseGV;
2693 case ScaledRegField:
2694 return ScaledReg;
2695 case BaseOffsField:
2696 return ConstantInt::get(IntPtrTy, BaseOffs);
2697 }
2698 }
2699
2700 void SetCombinedField(FieldName Field, Value *V,
2701 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2702 switch (Field) {
2703 default:
2704 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2705 break;
2706 case ExtAddrMode::BaseRegField:
2707 BaseReg = V;
2708 break;
2709 case ExtAddrMode::BaseGVField:
2710 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2711 // in the BaseReg field.
2712 assert(BaseReg == nullptr);
2713 BaseReg = V;
2714 BaseGV = nullptr;
2715 break;
2716 case ExtAddrMode::ScaledRegField:
2717 ScaledReg = V;
2718 // If we have a mix of scaled and unscaled addrmodes then we want scale
2719 // to be the scale and not zero.
2720 if (!Scale)
2721 for (const ExtAddrMode &AM : AddrModes)
2722 if (AM.Scale) {
2723 Scale = AM.Scale;
2724 break;
2725 }
2726 break;
2727 case ExtAddrMode::BaseOffsField:
2728 // The offset is no longer a constant, so it goes in ScaledReg with a
2729 // scale of 1.
2730 assert(ScaledReg == nullptr);
2731 ScaledReg = V;
2732 Scale = 1;
2733 BaseOffs = 0;
2734 break;
2735 }
2736 }
2737};
2738
2739#ifndef NDEBUG
2740static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2741 AM.print(OS);
2742 return OS;
2743}
2744#endif
2745
2746#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2747void ExtAddrMode::print(raw_ostream &OS) const {
2748 bool NeedPlus = false;
2749 OS << "[";
2750 if (InBounds)
2751 OS << "inbounds ";
2752 if (BaseGV) {
2753 OS << "GV:";
2754 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2755 NeedPlus = true;
2756 }
2757
2758 if (BaseOffs) {
2759 OS << (NeedPlus ? " + " : "") << BaseOffs;
2760 NeedPlus = true;
2761 }
2762
2763 if (BaseReg) {
2764 OS << (NeedPlus ? " + " : "") << "Base:";
2765 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2766 NeedPlus = true;
2767 }
2768 if (Scale) {
2769 OS << (NeedPlus ? " + " : "") << Scale << "*";
2770 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2771 }
2772
2773 OS << ']';
2774}
2775
2776LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
2777 print(dbgs());
2778 dbgs() << '\n';
2779}
2780#endif
2781
2782} // end anonymous namespace
2783
2784namespace {
2785
2786/// This class provides transaction based operation on the IR.
2787/// Every change made through this class is recorded in the internal state and
2788/// can be undone (rollback) until commit is called.
2789/// CGP does not check if instructions could be speculatively executed when
2790/// moved. Preserving the original location would pessimize the debugging
2791/// experience, as well as negatively impact the quality of sample PGO.
2792class TypePromotionTransaction {
2793 /// This represents the common interface of the individual transaction.
2794 /// Each class implements the logic for doing one specific modification on
2795 /// the IR via the TypePromotionTransaction.
2796 class TypePromotionAction {
2797 protected:
2798 /// The Instruction modified.
2799 Instruction *Inst;
2800
2801 public:
2802 /// Constructor of the action.
2803 /// The constructor performs the related action on the IR.
2804 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2805
2806 virtual ~TypePromotionAction() = default;
2807
2808 /// Undo the modification done by this action.
2809 /// When this method is called, the IR must be in the same state as it was
2810 /// before this action was applied.
2811 /// \pre Undoing the action works if and only if the IR is in the exact same
2812 /// state as it was directly after this action was applied.
2813 virtual void undo() = 0;
2814
2815 /// Advocate every change made by this action.
2816 /// When the results on the IR of the action are to be kept, it is important
2817 /// to call this function, otherwise hidden information may be kept forever.
2818 virtual void commit() {
2819 // Nothing to be done, this action is not doing anything.
2820 }
2821 };
2822
2823 /// Utility to remember the position of an instruction.
2824 class InsertionHandler {
2825 /// Position of an instruction.
2826 /// Either an instruction:
2827 /// - Is the first in a basic block: BB is used.
2828 /// - Has a previous instruction: PrevInst is used.
2829 union {
2830 Instruction *PrevInst;
2831 BasicBlock *BB;
2832 } Point;
2833
2834 /// Remember whether or not the instruction had a previous instruction.
2835 bool HasPrevInstruction;
2836
2837 public:
2838 /// Record the position of \p Inst.
2839 InsertionHandler(Instruction *Inst) {
2840 BasicBlock::iterator It = Inst->getIterator();
2841 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2842 if (HasPrevInstruction)
2843 Point.PrevInst = &*--It;
2844 else
2845 Point.BB = Inst->getParent();
2846 }
2847
2848 /// Insert \p Inst at the recorded position.
2849 void insert(Instruction *Inst) {
2850 if (HasPrevInstruction) {
2851 if (Inst->getParent())
2852 Inst->removeFromParent();
2853 Inst->insertAfter(Point.PrevInst);
2854 } else {
2855 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2856 if (Inst->getParent())
2857 Inst->moveBefore(Position);
2858 else
2859 Inst->insertBefore(Position);
2860 }
2861 }
2862 };
2863
2864 /// Move an instruction before another.
2865 class InstructionMoveBefore : public TypePromotionAction {
2866 /// Original position of the instruction.
2867 InsertionHandler Position;
2868
2869 public:
2870 /// Move \p Inst before \p Before.
2871 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2872 : TypePromotionAction(Inst), Position(Inst) {
2873 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2874 << "\n");
2875 Inst->moveBefore(Before);
2876 }
2877
2878 /// Move the instruction back to its original position.
2879 void undo() override {
2880 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2881 Position.insert(Inst);
2882 }
2883 };
2884
2885 /// Set the operand of an instruction with a new value.
2886 class OperandSetter : public TypePromotionAction {
2887 /// Original operand of the instruction.
2888 Value *Origin;
2889
2890 /// Index of the modified instruction.
2891 unsigned Idx;
2892
2893 public:
2894 /// Set \p Idx operand of \p Inst with \p NewVal.
2895 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2896 : TypePromotionAction(Inst), Idx(Idx) {
2897 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2898 << "for:" << *Inst << "\n"
2899 << "with:" << *NewVal << "\n");
2900 Origin = Inst->getOperand(Idx);
2901 Inst->setOperand(Idx, NewVal);
2902 }
2903
2904 /// Restore the original value of the instruction.
2905 void undo() override {
2906 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2907 << "for: " << *Inst << "\n"
2908 << "with: " << *Origin << "\n");
2909 Inst->setOperand(Idx, Origin);
2910 }
2911 };
2912
2913 /// Hide the operands of an instruction.
2914 /// Do as if this instruction was not using any of its operands.
2915 class OperandsHider : public TypePromotionAction {
2916 /// The list of original operands.
2917 SmallVector<Value *, 4> OriginalValues;
2918
2919 public:
2920 /// Remove \p Inst from the uses of the operands of \p Inst.
2921 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2922 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2923 unsigned NumOpnds = Inst->getNumOperands();
2924 OriginalValues.reserve(NumOpnds);
2925 for (unsigned It = 0; It < NumOpnds; ++It) {
2926 // Save the current operand.
2927 Value *Val = Inst->getOperand(It);
2928 OriginalValues.push_back(Val);
2929 // Set a dummy one.
2930 // We could use OperandSetter here, but that would imply an overhead
2931 // that we are not willing to pay.
2932 Inst->setOperand(It, UndefValue::get(Val->getType()));
2933 }
2934 }
2935
2936 /// Restore the original list of uses.
2937 void undo() override {
2938 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2939 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2940 Inst->setOperand(It, OriginalValues[It]);
2941 }
2942 };
2943
2944 /// Build a truncate instruction.
2945 class TruncBuilder : public TypePromotionAction {
2946 Value *Val;
2947
2948 public:
2949 /// Build a truncate instruction of \p Opnd producing a \p Ty
2950 /// result.
2951 /// trunc Opnd to Ty.
2952 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2953 IRBuilder<> Builder(Opnd);
2954 Builder.SetCurrentDebugLocation(DebugLoc());
2955 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2956 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
2957 }
2958
2959 /// Get the built value.
2960 Value *getBuiltValue() { return Val; }
2961
2962 /// Remove the built instruction.
2963 void undo() override {
2964 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2965 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2966 IVal->eraseFromParent();
2967 }
2968 };
2969
2970 /// Build a sign extension instruction.
2971 class SExtBuilder : public TypePromotionAction {
2972 Value *Val;
2973
2974 public:
2975 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2976 /// result.
2977 /// sext Opnd to Ty.
2978 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2979 : TypePromotionAction(InsertPt) {
2980 IRBuilder<> Builder(InsertPt);
2981 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2982 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
2983 }
2984
2985 /// Get the built value.
2986 Value *getBuiltValue() { return Val; }
2987
2988 /// Remove the built instruction.
2989 void undo() override {
2990 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2991 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2992 IVal->eraseFromParent();
2993 }
2994 };
2995
2996 /// Build a zero extension instruction.
2997 class ZExtBuilder : public TypePromotionAction {
2998 Value *Val;
2999
3000 public:
3001 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3002 /// result.
3003 /// zext Opnd to Ty.
3004 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3005 : TypePromotionAction(InsertPt) {
3006 IRBuilder<> Builder(InsertPt);
3007 Builder.SetCurrentDebugLocation(DebugLoc());
3008 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3009 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3010 }
3011
3012 /// Get the built value.
3013 Value *getBuiltValue() { return Val; }
3014
3015 /// Remove the built instruction.
3016 void undo() override {
3017 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3018 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3019 IVal->eraseFromParent();
3020 }
3021 };
3022
3023 /// Mutate an instruction to another type.
3024 class TypeMutator : public TypePromotionAction {
3025 /// Record the original type.
3026 Type *OrigTy;
3027
3028 public:
3029 /// Mutate the type of \p Inst into \p NewTy.
3030 TypeMutator(Instruction *Inst, Type *NewTy)
3031 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3032 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3033 << "\n");
3034 Inst->mutateType(NewTy);
3035 }
3036
3037 /// Mutate the instruction back to its original type.
3038 void undo() override {
3039 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3040 << "\n");
3041 Inst->mutateType(OrigTy);
3042 }
3043 };
3044
3045 /// Replace the uses of an instruction by another instruction.
3046 class UsesReplacer : public TypePromotionAction {
3047 /// Helper structure to keep track of the replaced uses.
3048 struct InstructionAndIdx {
3049 /// The instruction using the instruction.
3050 Instruction *Inst;
3051
3052 /// The index where this instruction is used for Inst.
3053 unsigned Idx;
3054
3055 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3056 : Inst(Inst), Idx(Idx) {}
3057 };
3058
3059 /// Keep track of the original uses (pair Instruction, Index).
3061 /// Keep track of the debug users.
3063
3064 /// Keep track of the new value so that we can undo it by replacing
3065 /// instances of the new value with the original value.
3066 Value *New;
3067
3069
3070 public:
3071 /// Replace all the use of \p Inst by \p New.
3072 UsesReplacer(Instruction *Inst, Value *New)
3073 : TypePromotionAction(Inst), New(New) {
3074 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3075 << "\n");
3076 // Record the original uses.
3077 for (Use &U : Inst->uses()) {
3078 Instruction *UserI = cast<Instruction>(U.getUser());
3079 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3080 }
3081 // Record the debug uses separately. They are not in the instruction's
3082 // use list, but they are replaced by RAUW.
3083 findDbgValues(DbgValues, Inst);
3084
3085 // Now, we can replace the uses.
3086 Inst->replaceAllUsesWith(New);
3087 }
3088
3089 /// Reassign the original uses of Inst to Inst.
3090 void undo() override {
3091 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3092 for (InstructionAndIdx &Use : OriginalUses)
3093 Use.Inst->setOperand(Use.Idx, Inst);
3094 // RAUW has replaced all original uses with references to the new value,
3095 // including the debug uses. Since we are undoing the replacements,
3096 // the original debug uses must also be reinstated to maintain the
3097 // correctness and utility of debug value instructions.
3098 for (auto *DVI : DbgValues)
3099 DVI->replaceVariableLocationOp(New, Inst);
3100 }
3101 };
3102
3103 /// Remove an instruction from the IR.
3104 class InstructionRemover : public TypePromotionAction {
3105 /// Original position of the instruction.
3106 InsertionHandler Inserter;
3107
3108 /// Helper structure to hide all the link to the instruction. In other
3109 /// words, this helps to do as if the instruction was removed.
3110 OperandsHider Hider;
3111
3112 /// Keep track of the uses replaced, if any.
3113 UsesReplacer *Replacer = nullptr;
3114
3115 /// Keep track of instructions removed.
3116 SetOfInstrs &RemovedInsts;
3117
3118 public:
3119 /// Remove all reference of \p Inst and optionally replace all its
3120 /// uses with New.
3121 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3122 /// \pre If !Inst->use_empty(), then New != nullptr
3123 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3124 Value *New = nullptr)
3125 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3126 RemovedInsts(RemovedInsts) {
3127 if (New)
3128 Replacer = new UsesReplacer(Inst, New);
3129 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3130 RemovedInsts.insert(Inst);
3131 /// The instructions removed here will be freed after completing
3132 /// optimizeBlock() for all blocks as we need to keep track of the
3133 /// removed instructions during promotion.
3134 Inst->removeFromParent();
3135 }
3136
3137 ~InstructionRemover() override { delete Replacer; }
3138
3139 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3140 InstructionRemover(const InstructionRemover &other) = delete;
3141
3142 /// Resurrect the instruction and reassign it to the proper uses if
3143 /// new value was provided when build this action.
3144 void undo() override {
3145 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3146 Inserter.insert(Inst);
3147 if (Replacer)
3148 Replacer->undo();
3149 Hider.undo();
3150 RemovedInsts.erase(Inst);
3151 }
3152 };
3153
3154public:
3155 /// Restoration point.
3156 /// The restoration point is a pointer to an action instead of an iterator
3157 /// because the iterator may be invalidated but not the pointer.
3158 using ConstRestorationPt = const TypePromotionAction *;
3159
3160 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3161 : RemovedInsts(RemovedInsts) {}
3162
3163 /// Advocate every changes made in that transaction. Return true if any change
3164 /// happen.
3165 bool commit();
3166
3167 /// Undo all the changes made after the given point.
3168 void rollback(ConstRestorationPt Point);
3169
3170 /// Get the current restoration point.
3171 ConstRestorationPt getRestorationPoint() const;
3172
3173 /// \name API for IR modification with state keeping to support rollback.
3174 /// @{
3175 /// Same as Instruction::setOperand.
3176 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3177
3178 /// Same as Instruction::eraseFromParent.
3179 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3180
3181 /// Same as Value::replaceAllUsesWith.
3182 void replaceAllUsesWith(Instruction *Inst, Value *New);
3183
3184 /// Same as Value::mutateType.
3185 void mutateType(Instruction *Inst, Type *NewTy);
3186
3187 /// Same as IRBuilder::createTrunc.
3188 Value *createTrunc(Instruction *Opnd, Type *Ty);
3189
3190 /// Same as IRBuilder::createSExt.
3191 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3192
3193 /// Same as IRBuilder::createZExt.
3194 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3195
3196 /// Same as Instruction::moveBefore.
3197 void moveBefore(Instruction *Inst, Instruction *Before);
3198 /// @}
3199
3200private:
3201 /// The ordered list of actions made so far.
3203
3204 using CommitPt =
3206
3207 SetOfInstrs &RemovedInsts;
3208};
3209
3210} // end anonymous namespace
3211
3212void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3213 Value *NewVal) {
3214 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3215 Inst, Idx, NewVal));
3216}
3217
3218void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3219 Value *NewVal) {
3220 Actions.push_back(
3221 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3222 Inst, RemovedInsts, NewVal));
3223}
3224
3225void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3226 Value *New) {
3227 Actions.push_back(
3228 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3229}
3230
3231void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3232 Actions.push_back(
3233 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3234}
3235
3236Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3237 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3238 Value *Val = Ptr->getBuiltValue();
3239 Actions.push_back(std::move(Ptr));
3240 return Val;
3241}
3242
3243Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3244 Type *Ty) {
3245 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3246 Value *Val = Ptr->getBuiltValue();
3247 Actions.push_back(std::move(Ptr));
3248 return Val;
3249}
3250
3251Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3252 Type *Ty) {
3253 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3254 Value *Val = Ptr->getBuiltValue();
3255 Actions.push_back(std::move(Ptr));
3256 return Val;
3257}
3258
3259void TypePromotionTransaction::moveBefore(Instruction *Inst,
3261 Actions.push_back(
3262 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3263 Inst, Before));
3264}
3265
3266TypePromotionTransaction::ConstRestorationPt
3267TypePromotionTransaction::getRestorationPoint() const {
3268 return !Actions.empty() ? Actions.back().get() : nullptr;
3269}
3270
3271bool TypePromotionTransaction::commit() {
3272 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3273 Action->commit();
3274 bool Modified = !Actions.empty();
3275 Actions.clear();
3276 return Modified;
3277}
3278
3279void TypePromotionTransaction::rollback(
3280 TypePromotionTransaction::ConstRestorationPt Point) {
3281 while (!Actions.empty() && Point != Actions.back().get()) {
3282 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3283 Curr->undo();
3284 }
3285}
3286
3287namespace {
3288
3289/// A helper class for matching addressing modes.
3290///
3291/// This encapsulates the logic for matching the target-legal addressing modes.
3292class AddressingModeMatcher {
3293 SmallVectorImpl<Instruction *> &AddrModeInsts;
3294 const TargetLowering &TLI;
3295 const TargetRegisterInfo &TRI;
3296 const DataLayout &DL;
3297 const LoopInfo &LI;
3298 const std::function<const DominatorTree &()> getDTFn;
3299
3300 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3301 /// the memory instruction that we're computing this address for.
3302 Type *AccessTy;
3303 unsigned AddrSpace;
3304 Instruction *MemoryInst;
3305
3306 /// This is the addressing mode that we're building up. This is
3307 /// part of the return value of this addressing mode matching stuff.
3309
3310 /// The instructions inserted by other CodeGenPrepare optimizations.
3311 const SetOfInstrs &InsertedInsts;
3312
3313 /// A map from the instructions to their type before promotion.
3314 InstrToOrigTy &PromotedInsts;
3315
3316 /// The ongoing transaction where every action should be registered.
3317 TypePromotionTransaction &TPT;
3318
3319 // A GEP which has too large offset to be folded into the addressing mode.
3320 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3321
3322 /// This is set to true when we should not do profitability checks.
3323 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3324 bool IgnoreProfitability;
3325
3326 /// True if we are optimizing for size.
3327 bool OptSize = false;
3328
3329 ProfileSummaryInfo *PSI;
3331
3332 AddressingModeMatcher(
3334 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3335 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3336 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3337 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3338 TypePromotionTransaction &TPT,
3339 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3340 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3341 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3342 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3343 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3344 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3345 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3346 IgnoreProfitability = false;
3347 }
3348
3349public:
3350 /// Find the maximal addressing mode that a load/store of V can fold,
3351 /// give an access type of AccessTy. This returns a list of involved
3352 /// instructions in AddrModeInsts.
3353 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3354 /// optimizations.
3355 /// \p PromotedInsts maps the instructions to their type before promotion.
3356 /// \p The ongoing transaction where every action should be registered.
3357 static ExtAddrMode
3358 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3359 SmallVectorImpl<Instruction *> &AddrModeInsts,
3360 const TargetLowering &TLI, const LoopInfo &LI,
3361 const std::function<const DominatorTree &()> getDTFn,
3362 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3363 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3364 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3365 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3367
3368 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3369 AccessTy, AS, MemoryInst, Result,
3370 InsertedInsts, PromotedInsts, TPT,
3371 LargeOffsetGEP, OptSize, PSI, BFI)
3372 .matchAddr(V, 0);
3373 (void)Success;
3374 assert(Success && "Couldn't select *anything*?");
3375 return Result;
3376 }
3377
3378private:
3379 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3380 bool matchAddr(Value *Addr, unsigned Depth);
3381 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3382 bool *MovedAway = nullptr);
3383 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3384 ExtAddrMode &AMBefore,
3385 ExtAddrMode &AMAfter);
3386 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3387 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3388 Value *PromotedOperand) const;
3389};
3390
3391class PhiNodeSet;
3392
3393/// An iterator for PhiNodeSet.
3394class PhiNodeSetIterator {
3395 PhiNodeSet *const Set;
3396 size_t CurrentIndex = 0;
3397
3398public:
3399 /// The constructor. Start should point to either a valid element, or be equal
3400 /// to the size of the underlying SmallVector of the PhiNodeSet.
3401 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3402 PHINode *operator*() const;
3403 PhiNodeSetIterator &operator++();
3404 bool operator==(const PhiNodeSetIterator &RHS) const;
3405 bool operator!=(const PhiNodeSetIterator &RHS) const;
3406};
3407
3408/// Keeps a set of PHINodes.
3409///
3410/// This is a minimal set implementation for a specific use case:
3411/// It is very fast when there are very few elements, but also provides good
3412/// performance when there are many. It is similar to SmallPtrSet, but also
3413/// provides iteration by insertion order, which is deterministic and stable
3414/// across runs. It is also similar to SmallSetVector, but provides removing
3415/// elements in O(1) time. This is achieved by not actually removing the element
3416/// from the underlying vector, so comes at the cost of using more memory, but
3417/// that is fine, since PhiNodeSets are used as short lived objects.
3418class PhiNodeSet {
3419 friend class PhiNodeSetIterator;
3420
3422 using iterator = PhiNodeSetIterator;
3423
3424 /// Keeps the elements in the order of their insertion in the underlying
3425 /// vector. To achieve constant time removal, it never deletes any element.
3427
3428 /// Keeps the elements in the underlying set implementation. This (and not the
3429 /// NodeList defined above) is the source of truth on whether an element
3430 /// is actually in the collection.
3431 MapType NodeMap;
3432
3433 /// Points to the first valid (not deleted) element when the set is not empty
3434 /// and the value is not zero. Equals to the size of the underlying vector
3435 /// when the set is empty. When the value is 0, as in the beginning, the
3436 /// first element may or may not be valid.
3437 size_t FirstValidElement = 0;
3438
3439public:
3440 /// Inserts a new element to the collection.
3441 /// \returns true if the element is actually added, i.e. was not in the
3442 /// collection before the operation.
3443 bool insert(PHINode *Ptr) {
3444 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3445 NodeList.push_back(Ptr);
3446 return true;
3447 }
3448 return false;
3449 }
3450
3451 /// Removes the element from the collection.
3452 /// \returns whether the element is actually removed, i.e. was in the
3453 /// collection before the operation.
3454 bool erase(PHINode *Ptr) {
3455 if (NodeMap.erase(Ptr)) {
3456 SkipRemovedElements(FirstValidElement);
3457 return true;
3458 }
3459 return false;
3460 }
3461
3462 /// Removes all elements and clears the collection.
3463 void clear() {
3464 NodeMap.clear();
3465 NodeList.clear();
3466 FirstValidElement = 0;
3467 }
3468
3469 /// \returns an iterator that will iterate the elements in the order of
3470 /// insertion.
3471 iterator begin() {
3472 if (FirstValidElement == 0)
3473 SkipRemovedElements(FirstValidElement);
3474 return PhiNodeSetIterator(this, FirstValidElement);
3475 }
3476
3477 /// \returns an iterator that points to the end of the collection.
3478 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3479
3480 /// Returns the number of elements in the collection.
3481 size_t size() const { return NodeMap.size(); }
3482
3483 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3484 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3485
3486private:
3487 /// Updates the CurrentIndex so that it will point to a valid element.
3488 ///
3489 /// If the element of NodeList at CurrentIndex is valid, it does not
3490 /// change it. If there are no more valid elements, it updates CurrentIndex
3491 /// to point to the end of the NodeList.
3492 void SkipRemovedElements(size_t &CurrentIndex) {
3493 while (CurrentIndex < NodeList.size()) {
3494 auto it = NodeMap.find(NodeList[CurrentIndex]);
3495 // If the element has been deleted and added again later, NodeMap will
3496 // point to a different index, so CurrentIndex will still be invalid.
3497 if (it != NodeMap.end() && it->second == CurrentIndex)
3498 break;
3499 ++CurrentIndex;
3500 }
3501 }
3502};
3503
3504PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3505 : Set(Set), CurrentIndex(Start) {}
3506
3507PHINode *PhiNodeSetIterator::operator*() const {
3508 assert(CurrentIndex < Set->NodeList.size() &&
3509 "PhiNodeSet access out of range");
3510 return Set->NodeList[CurrentIndex];
3511}
3512
3513PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3514 assert(CurrentIndex < Set->NodeList.size() &&
3515 "PhiNodeSet access out of range");
3516 ++CurrentIndex;
3517 Set->SkipRemovedElements(CurrentIndex);
3518 return *this;
3519}
3520
3521bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3522 return CurrentIndex == RHS.CurrentIndex;
3523}
3524
3525bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3526 return !((*this) == RHS);
3527}
3528
3529/// Keep track of simplification of Phi nodes.
3530/// Accept the set of all phi nodes and erase phi node from this set
3531/// if it is simplified.
3532class SimplificationTracker {
3534 const SimplifyQuery &SQ;
3535 // Tracks newly created Phi nodes. The elements are iterated by insertion
3536 // order.
3537 PhiNodeSet AllPhiNodes;
3538 // Tracks newly created Select nodes.
3539 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3540
3541public:
3542 SimplificationTracker(const SimplifyQuery &sq) : SQ(sq) {}
3543
3544 Value *Get(Value *V) {
3545 do {
3546 auto SV = Storage.find(V);
3547 if (SV == Storage.end())
3548 return V;
3549 V = SV->second;
3550 } while (true);
3551 }
3552
3553 Value *Simplify(Value *Val) {
3554 SmallVector<Value *, 32> WorkList;
3556 WorkList.push_back(Val);
3557 while (!WorkList.empty()) {
3558 auto *P = WorkList.pop_back_val();
3559 if (!Visited.insert(P).second)
3560 continue;
3561 if (auto *PI = dyn_cast<Instruction>(P))
3562 if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
3563 for (auto *U : PI->users())
3564 WorkList.push_back(cast<Value>(U));
3565 Put(PI, V);
3566 PI->replaceAllUsesWith(V);
3567 if (auto *PHI = dyn_cast<PHINode>(PI))
3568 AllPhiNodes.erase(PHI);
3569 if (auto *Select = dyn_cast<SelectInst>(PI))
3570 AllSelectNodes.erase(Select);
3571 PI->eraseFromParent();
3572 }
3573 }
3574 return Get(Val);
3575 }
3576
3577 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3578
3579 void ReplacePhi(PHINode *From, PHINode *To) {
3580 Value *OldReplacement = Get(From);
3581 while (OldReplacement != From) {
3582 From = To;
3583 To = dyn_cast<PHINode>(OldReplacement);
3584 OldReplacement = Get(From);
3585 }
3586 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3587 Put(From, To);
3588 From->replaceAllUsesWith(To);
3589 AllPhiNodes.erase(From);
3590 From->eraseFromParent();
3591 }
3592
3593 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3594
3595 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3596
3597 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3598
3599 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3600
3601 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3602
3603 void destroyNewNodes(Type *CommonType) {
3604 // For safe erasing, replace the uses with dummy value first.
3605 auto *Dummy = PoisonValue::get(CommonType);
3606 for (auto *I : AllPhiNodes) {
3607 I->replaceAllUsesWith(Dummy);
3608 I->eraseFromParent();
3609 }
3610 AllPhiNodes.clear();
3611 for (auto *I : AllSelectNodes) {
3612 I->replaceAllUsesWith(Dummy);
3613 I->eraseFromParent();
3614 }
3615 AllSelectNodes.clear();
3616 }
3617};
3618
3619/// A helper class for combining addressing modes.
3620class AddressingModeCombiner {
3621 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3622 typedef std::pair<PHINode *, PHINode *> PHIPair;
3623
3624private:
3625 /// The addressing modes we've collected.
3627
3628 /// The field in which the AddrModes differ, when we have more than one.
3629 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3630
3631 /// Are the AddrModes that we have all just equal to their original values?
3632 bool AllAddrModesTrivial = true;
3633
3634 /// Common Type for all different fields in addressing modes.
3635 Type *CommonType = nullptr;
3636
3637 /// SimplifyQuery for simplifyInstruction utility.
3638 const SimplifyQuery &SQ;
3639
3640 /// Original Address.
3641 Value *Original;
3642
3643 /// Common value among addresses
3644 Value *CommonValue = nullptr;
3645
3646public:
3647 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3648 : SQ(_SQ), Original(OriginalValue) {}
3649
3650 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
3651
3652 /// Get the combined AddrMode
3653 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
3654
3655 /// Add a new AddrMode if it's compatible with the AddrModes we already
3656 /// have.
3657 /// \return True iff we succeeded in doing so.
3658 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3659 // Take note of if we have any non-trivial AddrModes, as we need to detect
3660 // when all AddrModes are trivial as then we would introduce a phi or select
3661 // which just duplicates what's already there.
3662 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3663
3664 // If this is the first addrmode then everything is fine.
3665 if (AddrModes.empty()) {
3666 AddrModes.emplace_back(NewAddrMode);
3667 return true;
3668 }
3669
3670 // Figure out how different this is from the other address modes, which we
3671 // can do just by comparing against the first one given that we only care
3672 // about the cumulative difference.
3673 ExtAddrMode::FieldName ThisDifferentField =
3674 AddrModes[0].compare(NewAddrMode);
3675 if (DifferentField == ExtAddrMode::NoField)
3676 DifferentField = ThisDifferentField;
3677 else if (DifferentField != ThisDifferentField)
3678 DifferentField = ExtAddrMode::MultipleFields;
3679
3680 // If NewAddrMode differs in more than one dimension we cannot handle it.
3681 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3682
3683 // If Scale Field is different then we reject.
3684 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3685
3686 // We also must reject the case when base offset is different and
3687 // scale reg is not null, we cannot handle this case due to merge of
3688 // different offsets will be used as ScaleReg.
3689 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3690 !NewAddrMode.ScaledReg);
3691
3692 // We also must reject the case when GV is different and BaseReg installed
3693 // due to we want to use base reg as a merge of GV values.
3694 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3695 !NewAddrMode.HasBaseReg);
3696
3697 // Even if NewAddMode is the same we still need to collect it due to
3698 // original value is different. And later we will need all original values
3699 // as anchors during finding the common Phi node.
3700 if (CanHandle)
3701 AddrModes.emplace_back(NewAddrMode);
3702 else
3703 AddrModes.clear();
3704
3705 return CanHandle;
3706 }
3707
3708 /// Combine the addressing modes we've collected into a single
3709 /// addressing mode.
3710 /// \return True iff we successfully combined them or we only had one so
3711 /// didn't need to combine them anyway.
3712 bool combineAddrModes() {
3713 // If we have no AddrModes then they can't be combined.
3714 if (AddrModes.size() == 0)
3715 return false;
3716
3717 // A single AddrMode can trivially be combined.
3718 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3719 return true;
3720
3721 // If the AddrModes we collected are all just equal to the value they are
3722 // derived from then combining them wouldn't do anything useful.
3723 if (AllAddrModesTrivial)
3724 return false;
3725
3726 if (!addrModeCombiningAllowed())
3727 return false;
3728
3729 // Build a map between <original value, basic block where we saw it> to
3730 // value of base register.
3731 // Bail out if there is no common type.
3732 FoldAddrToValueMapping Map;
3733 if (!initializeMap(Map))
3734 return false;
3735
3736 CommonValue = findCommon(Map);
3737 if (CommonValue)
3738 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3739 return CommonValue != nullptr;
3740 }
3741
3742private:
3743 /// `CommonValue` may be a placeholder inserted by us.
3744 /// If the placeholder is not used, we should remove this dead instruction.
3745 void eraseCommonValueIfDead() {
3746 if (CommonValue && CommonValue->getNumUses() == 0)
3747 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
3748 CommonInst->eraseFromParent();
3749 }
3750
3751 /// Initialize Map with anchor values. For address seen
3752 /// we set the value of different field saw in this address.
3753 /// At the same time we find a common type for different field we will
3754 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3755 /// Return false if there is no common type found.
3756 bool initializeMap(FoldAddrToValueMapping &Map) {
3757 // Keep track of keys where the value is null. We will need to replace it
3758 // with constant null when we know the common type.
3759 SmallVector<Value *, 2> NullValue;
3760 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3761 for (auto &AM : AddrModes) {
3762 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3763 if (DV) {
3764 auto *Type = DV->getType();
3765 if (CommonType && CommonType != Type)
3766 return false;
3767 CommonType = Type;
3768 Map[AM.OriginalValue] = DV;
3769 } else {
3770 NullValue.push_back(AM.OriginalValue);
3771 }
3772 }
3773 assert(CommonType && "At least one non-null value must be!");
3774 for (auto *V : NullValue)
3775 Map[V] = Constant::getNullValue(CommonType);
3776 return true;
3777 }
3778
3779 /// We have mapping between value A and other value B where B was a field in
3780 /// addressing mode represented by A. Also we have an original value C
3781 /// representing an address we start with. Traversing from C through phi and
3782 /// selects we ended up with A's in a map. This utility function tries to find
3783 /// a value V which is a field in addressing mode C and traversing through phi
3784 /// nodes and selects we will end up in corresponded values B in a map.
3785 /// The utility will create a new Phi/Selects if needed.
3786 // The simple example looks as follows:
3787 // BB1:
3788 // p1 = b1 + 40
3789 // br cond BB2, BB3
3790 // BB2:
3791 // p2 = b2 + 40
3792 // br BB3
3793 // BB3:
3794 // p = phi [p1, BB1], [p2, BB2]
3795 // v = load p
3796 // Map is
3797 // p1 -> b1
3798 // p2 -> b2
3799 // Request is
3800 // p -> ?
3801 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3802 Value *findCommon(FoldAddrToValueMapping &Map) {
3803 // Tracks the simplification of newly created phi nodes. The reason we use
3804 // this mapping is because we will add new created Phi nodes in AddrToBase.
3805 // Simplification of Phi nodes is recursive, so some Phi node may
3806 // be simplified after we added it to AddrToBase. In reality this
3807 // simplification is possible only if original phi/selects were not
3808 // simplified yet.
3809 // Using this mapping we can find the current value in AddrToBase.
3810 SimplificationTracker ST(SQ);
3811
3812 // First step, DFS to create PHI nodes for all intermediate blocks.
3813 // Also fill traverse order for the second step.
3814 SmallVector<Value *, 32> TraverseOrder;
3815 InsertPlaceholders(Map, TraverseOrder, ST);
3816
3817 // Second Step, fill new nodes by merged values and simplify if possible.
3818 FillPlaceholders(Map, TraverseOrder, ST);
3819
3820 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3821 ST.destroyNewNodes(CommonType);
3822 return nullptr;
3823 }
3824
3825 // Now we'd like to match New Phi nodes to existed ones.
3826 unsigned PhiNotMatchedCount = 0;
3827 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3828 ST.destroyNewNodes(CommonType);
3829 return nullptr;
3830 }
3831
3832 auto *Result = ST.Get(Map.find(Original)->second);
3833 if (Result) {
3834 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3835 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3836 }
3837 return Result;
3838 }
3839
3840 /// Try to match PHI node to Candidate.
3841 /// Matcher tracks the matched Phi nodes.
3842 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3844 PhiNodeSet &PhiNodesToMatch) {
3845 SmallVector<PHIPair, 8> WorkList;
3846 Matcher.insert({PHI, Candidate});
3847 SmallSet<PHINode *, 8> MatchedPHIs;
3848 MatchedPHIs.insert(PHI);
3849 WorkList.push_back({PHI, Candidate});
3850 SmallSet<PHIPair, 8> Visited;
3851 while (!WorkList.empty()) {
3852 auto Item = WorkList.pop_back_val();
3853 if (!Visited.insert(Item).second)
3854 continue;
3855 // We iterate over all incoming values to Phi to compare them.
3856 // If values are different and both of them Phi and the first one is a
3857 // Phi we added (subject to match) and both of them is in the same basic
3858 // block then we can match our pair if values match. So we state that
3859 // these values match and add it to work list to verify that.
3860 for (auto *B : Item.first->blocks()) {
3861 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3862 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3863 if (FirstValue == SecondValue)
3864 continue;
3865
3866 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3867 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3868
3869 // One of them is not Phi or
3870 // The first one is not Phi node from the set we'd like to match or
3871 // Phi nodes from different basic blocks then
3872 // we will not be able to match.
3873 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3874 FirstPhi->getParent() != SecondPhi->getParent())
3875 return false;
3876
3877 // If we already matched them then continue.
3878 if (Matcher.count({FirstPhi, SecondPhi}))
3879 continue;
3880 // So the values are different and does not match. So we need them to
3881 // match. (But we register no more than one match per PHI node, so that
3882 // we won't later try to replace them twice.)
3883 if (MatchedPHIs.insert(FirstPhi).second)
3884 Matcher.insert({FirstPhi, SecondPhi});
3885 // But me must check it.
3886 WorkList.push_back({FirstPhi, SecondPhi});
3887 }
3888 }
3889 return true;
3890 }
3891
3892 /// For the given set of PHI nodes (in the SimplificationTracker) try
3893 /// to find their equivalents.
3894 /// Returns false if this matching fails and creation of new Phi is disabled.
3895 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3896 unsigned &PhiNotMatchedCount) {
3897 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3898 // order, so the replacements (ReplacePhi) are also done in a deterministic
3899 // order.
3901 SmallPtrSet<PHINode *, 8> WillNotMatch;
3902 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3903 while (PhiNodesToMatch.size()) {
3904 PHINode *PHI = *PhiNodesToMatch.begin();
3905
3906 // Add us, if no Phi nodes in the basic block we do not match.
3907 WillNotMatch.clear();
3908 WillNotMatch.insert(PHI);
3909
3910 // Traverse all Phis until we found equivalent or fail to do that.
3911 bool IsMatched = false;
3912 for (auto &P : PHI->getParent()->phis()) {
3913 // Skip new Phi nodes.
3914 if (PhiNodesToMatch.count(&P))
3915 continue;
3916 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3917 break;
3918 // If it does not match, collect all Phi nodes from matcher.
3919 // if we end up with no match, them all these Phi nodes will not match
3920 // later.
3921 for (auto M : Matched)
3922 WillNotMatch.insert(M.first);
3923 Matched.clear();
3924 }
3925 if (IsMatched) {
3926 // Replace all matched values and erase them.
3927 for (auto MV : Matched)
3928 ST.ReplacePhi(MV.first, MV.second);
3929 Matched.clear();
3930 continue;
3931 }
3932 // If we are not allowed to create new nodes then bail out.
3933 if (!AllowNewPhiNodes)
3934 return false;
3935 // Just remove all seen values in matcher. They will not match anything.
3936 PhiNotMatchedCount += WillNotMatch.size();
3937 for (auto *P : WillNotMatch)
3938 PhiNodesToMatch.erase(P);
3939 }
3940 return true;
3941 }
3942 /// Fill the placeholders with values from predecessors and simplify them.
3943 void FillPlaceholders(FoldAddrToValueMapping &Map,
3944 SmallVectorImpl<Value *> &TraverseOrder,
3945 SimplificationTracker &ST) {
3946 while (!TraverseOrder.empty()) {
3947 Value *Current = TraverseOrder.pop_back_val();
3948 assert(Map.contains(Current) && "No node to fill!!!");
3949 Value *V = Map[Current];
3950
3951 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3952 // CurrentValue also must be Select.
3953 auto *CurrentSelect = cast<SelectInst>(Current);
3954 auto *TrueValue = CurrentSelect->getTrueValue();
3955 assert(Map.contains(TrueValue) && "No True Value!");
3956 Select->setTrueValue(ST.Get(Map[TrueValue]));
3957 auto *FalseValue = CurrentSelect->getFalseValue();
3958 assert(Map.contains(FalseValue) && "No False Value!");
3959 Select->setFalseValue(ST.Get(Map[FalseValue]));
3960 } else {
3961 // Must be a Phi node then.
3962 auto *PHI = cast<PHINode>(V);
3963 // Fill the Phi node with values from predecessors.
3964 for (auto *B : predecessors(PHI->getParent())) {
3965 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
3966 assert(Map.contains(PV) && "No predecessor Value!");
3967 PHI->addIncoming(ST.Get(Map[PV]), B);
3968 }
3969 }
3970 Map[Current] = ST.Simplify(V);
3971 }
3972 }
3973
3974 /// Starting from original value recursively iterates over def-use chain up to
3975 /// known ending values represented in a map. For each traversed phi/select
3976 /// inserts a placeholder Phi or Select.
3977 /// Reports all new created Phi/Select nodes by adding them to set.
3978 /// Also reports and order in what values have been traversed.
3979 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3980 SmallVectorImpl<Value *> &TraverseOrder,
3981 SimplificationTracker &ST) {
3982 SmallVector<Value *, 32> Worklist;
3983 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
3984 "Address must be a Phi or Select node");
3985 auto *Dummy = PoisonValue::get(CommonType);
3986 Worklist.push_back(Original);
3987 while (!Worklist.empty()) {
3988 Value *Current = Worklist.pop_back_val();
3989 // if it is already visited or it is an ending value then skip it.
3990 if (Map.contains(Current))
3991 continue;
3992 TraverseOrder.push_back(Current);
3993
3994 // CurrentValue must be a Phi node or select. All others must be covered
3995 // by anchors.
3996 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3997 // Is it OK to get metadata from OrigSelect?!
3998 // Create a Select placeholder with dummy value.
4000 CurrentSelect->getCondition(), Dummy, Dummy,
4001 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
4002 Map[Current] = Select;
4003 ST.insertNewSelect(Select);
4004 // We are interested in True and False values.
4005 Worklist.push_back(CurrentSelect->getTrueValue());
4006 Worklist.push_back(CurrentSelect->getFalseValue());
4007 } else {
4008 // It must be a Phi node then.
4009 PHINode *CurrentPhi = cast<PHINode>(Current);
4010 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4011 PHINode *PHI =
4012 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
4013 Map[Current] = PHI;
4014 ST.insertNewPhi(PHI);
4015 append_range(Worklist, CurrentPhi->incoming_values());
4016 }
4017 }
4018 }
4019
4020 bool addrModeCombiningAllowed() {
4022 return false;
4023 switch (DifferentField) {
4024 default:
4025 return false;
4026 case ExtAddrMode::BaseRegField:
4028 case ExtAddrMode::BaseGVField:
4029 return AddrSinkCombineBaseGV;
4030 case ExtAddrMode::BaseOffsField:
4032 case ExtAddrMode::ScaledRegField:
4034 }
4035 }
4036};
4037} // end anonymous namespace
4038
4039/// Try adding ScaleReg*Scale to the current addressing mode.
4040/// Return true and update AddrMode if this addr mode is legal for the target,
4041/// false if not.
4042bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4043 unsigned Depth) {
4044 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4045 // mode. Just process that directly.
4046 if (Scale == 1)
4047 return matchAddr(ScaleReg, Depth);
4048
4049 // If the scale is 0, it takes nothing to add this.
4050 if (Scale == 0)
4051 return true;
4052
4053 // If we already have a scale of this value, we can add to it, otherwise, we
4054 // need an available scale field.
4055 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4056 return false;
4057
4058 ExtAddrMode TestAddrMode = AddrMode;
4059
4060 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4061 // [A+B + A*7] -> [B+A*8].
4062 TestAddrMode.Scale += Scale;
4063 TestAddrMode.ScaledReg = ScaleReg;
4064
4065 // If the new address isn't legal, bail out.
4066 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4067 return false;
4068
4069 // It was legal, so commit it.
4070 AddrMode = TestAddrMode;
4071
4072 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4073 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4074 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4075 // go any further: we can reuse it and cannot eliminate it.
4076 ConstantInt *CI = nullptr;
4077 Value *AddLHS = nullptr;
4078 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4079 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4080 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4081 TestAddrMode.InBounds = false;
4082 TestAddrMode.ScaledReg = AddLHS;
4083 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4084
4085 // If this addressing mode is legal, commit it and remember that we folded
4086 // this instruction.
4087 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4088 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4089 AddrMode = TestAddrMode;
4090 return true;
4091 }
4092 // Restore status quo.
4093 TestAddrMode = AddrMode;
4094 }
4095
4096 // If this is an add recurrence with a constant step, return the increment
4097 // instruction and the canonicalized step.
4098 auto GetConstantStep =
4099 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4100 auto *PN = dyn_cast<PHINode>(V);
4101 if (!PN)
4102 return std::nullopt;
4103 auto IVInc = getIVIncrement(PN, &LI);
4104 if (!IVInc)
4105 return std::nullopt;
4106 // TODO: The result of the intrinsics above is two-complement. However when
4107 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4108 // If it has nuw or nsw flags, we need to make sure that these flags are
4109 // inferrable at the point of memory instruction. Otherwise we are replacing
4110 // well-defined two-complement computation with poison. Currently, to avoid
4111 // potentially complex analysis needed to prove this, we reject such cases.
4112 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4113 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4114 return std::nullopt;
4115 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4116 return std::make_pair(IVInc->first, ConstantStep->getValue());
4117 return std::nullopt;
4118 };
4119
4120 // Try to account for the following special case:
4121 // 1. ScaleReg is an inductive variable;
4122 // 2. We use it with non-zero offset;
4123 // 3. IV's increment is available at the point of memory instruction.
4124 //
4125 // In this case, we may reuse the IV increment instead of the IV Phi to
4126 // achieve the following advantages:
4127 // 1. If IV step matches the offset, we will have no need in the offset;
4128 // 2. Even if they don't match, we will reduce the overlap of living IV
4129 // and IV increment, that will potentially lead to better register
4130 // assignment.
4131 if (AddrMode.BaseOffs) {
4132 if (auto IVStep = GetConstantStep(ScaleReg)) {
4133 Instruction *IVInc = IVStep->first;
4134 // The following assert is important to ensure a lack of infinite loops.
4135 // This transforms is (intentionally) the inverse of the one just above.
4136 // If they don't agree on the definition of an increment, we'd alternate
4137 // back and forth indefinitely.
4138 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4139 APInt Step = IVStep->second;
4140 APInt Offset = Step * AddrMode.Scale;
4141 if (Offset.isSignedIntN(64)) {
4142 TestAddrMode.InBounds = false;
4143 TestAddrMode.ScaledReg = IVInc;
4144 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4145 // If this addressing mode is legal, commit it..
4146 // (Note that we defer the (expensive) domtree base legality check
4147 // to the very last possible point.)
4148 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4149 getDTFn().dominates(IVInc, MemoryInst)) {
4150 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4151 AddrMode = TestAddrMode;
4152 return true;
4153 }
4154 // Restore status quo.
4155 TestAddrMode = AddrMode;
4156 }
4157 }
4158 }
4159
4160 // Otherwise, just return what we have.
4161 return true;
4162}
4163
4164/// This is a little filter, which returns true if an addressing computation
4165/// involving I might be folded into a load/store accessing it.
4166/// This doesn't need to be perfect, but needs to accept at least
4167/// the set of instructions that MatchOperationAddr can.
4169 switch (I->getOpcode()) {
4170 case Instruction::BitCast:
4171 case Instruction::AddrSpaceCast:
4172 // Don't touch identity bitcasts.
4173 if (I->getType() == I->getOperand(0)->getType())
4174 return false;
4175 return I->getType()->isIntOrPtrTy();
4176 case Instruction::PtrToInt:
4177 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4178 return true;
4179 case Instruction::IntToPtr:
4180 // We know the input is intptr_t, so this is foldable.
4181 return true;
4182 case Instruction::Add:
4183 return true;
4184 case Instruction::Mul:
4185 case Instruction::Shl:
4186 // Can only handle X*C and X << C.
4187 return isa<ConstantInt>(I->getOperand(1));
4188 case Instruction::GetElementPtr:
4189 return true;
4190 default:
4191 return false;
4192 }
4193}
4194
4195/// Check whether or not \p Val is a legal instruction for \p TLI.
4196/// \note \p Val is assumed to be the product of some type promotion.
4197/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4198/// to be legal, as the non-promoted value would have had the same state.
4200 const DataLayout &DL, Value *Val) {
4201 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4202 if (!PromotedInst)
4203 return false;
4204 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4205 // If the ISDOpcode is undefined, it was undefined before the promotion.
4206 if (!ISDOpcode)
4207 return true;
4208 // Otherwise, check if the promoted instruction is legal or not.
4209 return TLI.isOperationLegalOrCustom(
4210 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4211}
4212
4213namespace {
4214
4215/// Hepler class to perform type promotion.
4216class TypePromotionHelper {
4217 /// Utility function to add a promoted instruction \p ExtOpnd to
4218 /// \p PromotedInsts and record the type of extension we have seen.
4219 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4220 Instruction *ExtOpnd, bool IsSExt) {
4221 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4222 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4223 if (It != PromotedInsts.end()) {
4224 // If the new extension is same as original, the information in
4225 // PromotedInsts[ExtOpnd] is still correct.
4226 if (It->second.getInt() == ExtTy)
4227 return;
4228
4229 // Now the new extension is different from old extension, we make
4230 // the type information invalid by setting extension type to
4231 // BothExtension.
4232 ExtTy = BothExtension;
4233 }
4234 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4235 }
4236
4237 /// Utility function to query the original type of instruction \p Opnd
4238 /// with a matched extension type. If the extension doesn't match, we
4239 /// cannot use the information we had on the original type.
4240 /// BothExtension doesn't match any extension type.
4241 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4242 Instruction *Opnd, bool IsSExt) {
4243 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4244 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4245 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4246 return It->second.getPointer();
4247 return nullptr;
4248 }
4249
4250 /// Utility function to check whether or not a sign or zero extension
4251 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4252 /// either using the operands of \p Inst or promoting \p Inst.
4253 /// The type of the extension is defined by \p IsSExt.
4254 /// In other words, check if:
4255 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4256 /// #1 Promotion applies:
4257 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4258 /// #2 Operand reuses:
4259 /// ext opnd1 to ConsideredExtType.
4260 /// \p PromotedInsts maps the instructions to their type before promotion.
4261 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4262 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4263
4264 /// Utility function to determine if \p OpIdx should be promoted when
4265 /// promoting \p Inst.
4266 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4267 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4268 }
4269
4270 /// Utility function to promote the operand of \p Ext when this
4271 /// operand is a promotable trunc or sext or zext.
4272 /// \p PromotedInsts maps the instructions to their type before promotion.
4273 /// \p CreatedInstsCost[out] contains the cost of all instructions
4274 /// created to promote the operand of Ext.
4275 /// Newly added extensions are inserted in \p Exts.
4276 /// Newly added truncates are inserted in \p Truncs.
4277 /// Should never be called directly.
4278 /// \return The promoted value which is used instead of Ext.
4279 static Value *promoteOperandForTruncAndAnyExt(
4280 Instruction *Ext, TypePromotionTransaction &TPT,
4281 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4284
4285 /// Utility function to promote the operand of \p Ext when this
4286 /// operand is promotable and is not a supported trunc or sext.
4287 /// \p PromotedInsts maps the instructions to their type before promotion.
4288 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4289 /// created to promote the operand of Ext.
4290 /// Newly added extensions are inserted in \p Exts.
4291 /// Newly added truncates are inserted in \p Truncs.
4292 /// Should never be called directly.
4293 /// \return The promoted value which is used instead of Ext.
4294 static Value *promoteOperandForOther(Instruction *Ext,
4295 TypePromotionTransaction &TPT,
4296 InstrToOrigTy &PromotedInsts,
4297 unsigned &CreatedInstsCost,
4300 const TargetLowering &TLI, bool IsSExt);
4301
4302 /// \see promoteOperandForOther.
4303 static Value *signExtendOperandForOther(
4304 Instruction *Ext, TypePromotionTransaction &TPT,
4305 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4307 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4308 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4309 Exts, Truncs, TLI, true);
4310 }
4311
4312 /// \see promoteOperandForOther.
4313 static Value *zeroExtendOperandForOther(
4314 Instruction *Ext, TypePromotionTransaction &TPT,
4315 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4317 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4318 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4319 Exts, Truncs, TLI, false);
4320 }
4321
4322public:
4323 /// Type for the utility function that promotes the operand of Ext.
4324 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4325 InstrToOrigTy &PromotedInsts,
4326 unsigned &CreatedInstsCost,
4329 const TargetLowering &TLI);
4330
4331 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4332 /// action to promote the operand of \p Ext instead of using Ext.
4333 /// \return NULL if no promotable action is possible with the current
4334 /// sign extension.
4335 /// \p InsertedInsts keeps track of all the instructions inserted by the
4336 /// other CodeGenPrepare optimizations. This information is important
4337 /// because we do not want to promote these instructions as CodeGenPrepare
4338 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4339 /// \p PromotedInsts maps the instructions to their type before promotion.
4340 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4341 const TargetLowering &TLI,
4342 const InstrToOrigTy &PromotedInsts);
4343};
4344
4345} // end anonymous namespace
4346
4347bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4348 Type *ConsideredExtType,
4349 const InstrToOrigTy &PromotedInsts,
4350 bool IsSExt) {
4351 // The promotion helper does not know how to deal with vector types yet.
4352 // To be able to fix that, we would need to fix the places where we
4353 // statically extend, e.g., constants and such.
4354 if (Inst->getType()->isVectorTy())
4355 return false;
4356
4357 // We can always get through zext.
4358 if (isa<ZExtInst>(Inst))
4359 return true;
4360
4361 // sext(sext) is ok too.
4362 if (IsSExt && isa<SExtInst>(Inst))
4363 return true;
4364
4365 // We can get through binary operator, if it is legal. In other words, the
4366 // binary operator must have a nuw or nsw flag.
4367 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4368 if (isa<OverflowingBinaryOperator>(BinOp) &&
4369 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4370 (IsSExt && BinOp->hasNoSignedWrap())))
4371 return true;
4372
4373 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4374 if ((Inst->getOpcode() == Instruction::And ||
4375 Inst->getOpcode() == Instruction::Or))
4376 return true;
4377
4378 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4379 if (Inst->getOpcode() == Instruction::Xor) {
4380 // Make sure it is not a NOT.
4381 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4382 if (!Cst->getValue().isAllOnes())
4383 return true;
4384 }
4385
4386 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4387 // It may change a poisoned value into a regular value, like
4388 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4389 // poisoned value regular value
4390 // It should be OK since undef covers valid value.
4391 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4392 return true;
4393
4394 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4395 // It may change a poisoned value into a regular value, like
4396 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4397 // poisoned value regular value
4398 // It should be OK since undef covers valid value.
4399 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4400 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4401 if (ExtInst->hasOneUse()) {
4402 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4403 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4404 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4405 if (Cst &&
4406 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4407 return true;
4408 }
4409 }
4410 }
4411
4412 // Check if we can do the following simplification.
4413 // ext(trunc(opnd)) --> ext(opnd)
4414 if (!isa<TruncInst>(Inst))
4415 return false;
4416
4417 Value *OpndVal = Inst->getOperand(0);
4418 // Check if we can use this operand in the extension.
4419 // If the type is larger than the result type of the extension, we cannot.
4420 if (!OpndVal->getType()->isIntegerTy() ||
4421 OpndVal->getType()->getIntegerBitWidth() >
4422 ConsideredExtType->getIntegerBitWidth())
4423 return false;
4424
4425 // If the operand of the truncate is not an instruction, we will not have
4426 // any information on the dropped bits.
4427 // (Actually we could for constant but it is not worth the extra logic).
4428 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4429 if (!Opnd)
4430 return false;
4431
4432 // Check if the source of the type is narrow enough.
4433 // I.e., check that trunc just drops extended bits of the same kind of
4434 // the extension.
4435 // #1 get the type of the operand and check the kind of the extended bits.
4436 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4437 if (OpndType)
4438 ;
4439 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4440 OpndType = Opnd->getOperand(0)->getType();
4441 else
4442 return false;
4443
4444 // #2 check that the truncate just drops extended bits.
4445 return Inst->getType()->getIntegerBitWidth() >=
4446 OpndType->getIntegerBitWidth();
4447}
4448
4449TypePromotionHelper::Action TypePromotionHelper::getAction(
4450 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4451 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4452 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4453 "Unexpected instruction type");
4454 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4455 Type *ExtTy = Ext->getType();
4456 bool IsSExt = isa<SExtInst>(Ext);
4457 // If the operand of the extension is not an instruction, we cannot
4458 // get through.
4459 // If it, check we can get through.
4460 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4461 return nullptr;
4462
4463 // Do not promote if the operand has been added by codegenprepare.
4464 // Otherwise, it means we are undoing an optimization that is likely to be
4465 // redone, thus causing potential infinite loop.
4466 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4467 return nullptr;
4468
4469 // SExt or Trunc instructions.
4470 // Return the related handler.
4471 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4472 isa<ZExtInst>(ExtOpnd))
4473 return promoteOperandForTruncAndAnyExt;
4474
4475 // Regular instruction.
4476 // Abort early if we will have to insert non-free instructions.
4477 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4478 return nullptr;
4479 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4480}
4481
4482Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4483 Instruction *SExt, TypePromotionTransaction &TPT,
4484 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4486 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4487 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4488 // get through it and this method should not be called.
4489 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4490 Value *ExtVal = SExt;
4491 bool HasMergedNonFreeExt = false;
4492 if (isa<ZExtInst>(SExtOpnd)) {
4493 // Replace s|zext(zext(opnd))
4494 // => zext(opnd).
4495 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4496 Value *ZExt =
4497 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4498 TPT.replaceAllUsesWith(SExt, ZExt);
4499 TPT.eraseInstruction(SExt);
4500 ExtVal = ZExt;
4501 } else {
4502 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4503 // => z|sext(opnd).
4504 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4505 }
4506 CreatedInstsCost = 0;
4507
4508 // Remove dead code.
4509 if (SExtOpnd->use_empty())
4510 TPT.eraseInstruction(SExtOpnd);
4511
4512 // Check if the extension is still needed.
4513 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4514 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4515 if (ExtInst) {
4516 if (Exts)
4517 Exts->push_back(ExtInst);
4518 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4519 }
4520 return ExtVal;
4521 }
4522
4523 // At this point we have: ext ty opnd to ty.
4524 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4525 Value *NextVal = ExtInst->getOperand(0);
4526 TPT.eraseInstruction(ExtInst, NextVal);
4527 return NextVal;
4528}
4529
4530Value *TypePromotionHelper::promoteOperandForOther(
4531 Instruction *Ext, TypePromotionTransaction &TPT,
4532 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4535 bool IsSExt) {
4536 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4537 // get through it and this method should not be called.
4538 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4539 CreatedInstsCost = 0;
4540 if (!ExtOpnd->hasOneUse()) {
4541 // ExtOpnd will be promoted.
4542 // All its uses, but Ext, will need to use a truncated value of the
4543 // promoted version.
4544 // Create the truncate now.
4545 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4546 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4547 // Insert it just after the definition.
4548 ITrunc->moveAfter(ExtOpnd);
4549 if (Truncs)
4550 Truncs->push_back(ITrunc);
4551 }
4552
4553 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4554 // Restore the operand of Ext (which has been replaced by the previous call
4555 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4556 TPT.setOperand(Ext, 0, ExtOpnd);
4557 }
4558
4559 // Get through the Instruction:
4560 // 1. Update its type.
4561 // 2. Replace the uses of Ext by Inst.
4562 // 3. Extend each operand that needs to be extended.
4563
4564 // Remember the original type of the instruction before promotion.
4565 // This is useful to know that the high bits are sign extended bits.
4566 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4567 // Step #1.
4568 TPT.mutateType(ExtOpnd, Ext->getType());
4569 // Step #2.
4570 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4571 // Step #3.
4572 Instruction *ExtForOpnd = Ext;
4573
4574 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4575 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4576 ++OpIdx) {
4577 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4578 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4579 !shouldExtOperand(ExtOpnd, OpIdx)) {
4580 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4581 continue;
4582 }
4583 // Check if we can statically extend the operand.
4584 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4585 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4586 LLVM_DEBUG(dbgs() << "Statically extend\n");
4587 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4588 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4589 : Cst->getValue().zext(BitWidth);
4590 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4591 continue;
4592 }
4593 // UndefValue are typed, so we have to statically sign extend them.
4594 if (isa<UndefValue>(Opnd)) {
4595 LLVM_DEBUG(dbgs() << "Statically extend\n");
4596 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4597 continue;
4598 }
4599
4600 // Otherwise we have to explicitly sign extend the operand.
4601 // Check if Ext was reused to extend an operand.
4602 if (!ExtForOpnd) {
4603 // If yes, create a new one.
4604 LLVM_DEBUG(dbgs() << "More operands to ext\n");
4605 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4606 : TPT.createZExt(Ext, Opnd, Ext->getType());
4607 if (!isa<Instruction>(ValForExtOpnd)) {
4608 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4609 continue;
4610 }
4611 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4612 }
4613 if (Exts)
4614 Exts->push_back(ExtForOpnd);
4615 TPT.setOperand(ExtForOpnd, 0, Opnd);
4616
4617 // Move the sign extension before the insertion point.
4618 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4619 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4620 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4621 // If more sext are required, new instructions will have to be created.
4622 ExtForOpnd = nullptr;
4623 }
4624 if (ExtForOpnd == Ext) {
4625 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
4626 TPT.eraseInstruction(Ext);
4627 }
4628 return ExtOpnd;
4629}
4630
4631/// Check whether or not promoting an instruction to a wider type is profitable.
4632/// \p NewCost gives the cost of extension instructions created by the
4633/// promotion.
4634/// \p OldCost gives the cost of extension instructions before the promotion
4635/// plus the number of instructions that have been
4636/// matched in the addressing mode the promotion.
4637/// \p PromotedOperand is the value that has been promoted.
4638/// \return True if the promotion is profitable, false otherwise.
4639bool AddressingModeMatcher::isPromotionProfitable(
4640 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4641 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
4642 << '\n');
4643 // The cost of the new extensions is greater than the cost of the
4644 // old extension plus what we folded.
4645 // This is not profitable.
4646 if (NewCost > OldCost)
4647 return false;
4648 if (NewCost < OldCost)
4649 return true;
4650 // The promotion is neutral but it may help folding the sign extension in
4651 // loads for instance.
4652 // Check that we did not create an illegal instruction.
4653 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4654}
4655
4656/// Given an instruction or constant expr, see if we can fold the operation
4657/// into the addressing mode. If so, update the addressing mode and return
4658/// true, otherwise return false without modifying AddrMode.
4659/// If \p MovedAway is not NULL, it contains the information of whether or
4660/// not AddrInst has to be folded into the addressing mode on success.
4661/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4662/// because it has been moved away.
4663/// Thus AddrInst must not be added in the matched instructions.
4664/// This state can happen when AddrInst is a sext, since it may be moved away.
4665/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4666/// not be referenced anymore.
4667bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4668 unsigned Depth,
4669 bool *MovedAway) {
4670 // Avoid exponential behavior on extremely deep expression trees.
4671 if (Depth >= 5)
4672 return false;
4673
4674 // By default, all matched instructions stay in place.
4675 if (MovedAway)
4676 *MovedAway = false;
4677
4678 switch (Opcode) {
4679 case Instruction::PtrToInt:
4680 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4681 return matchAddr(AddrInst->getOperand(0), Depth);
4682 case Instruction::IntToPtr: {
4683 auto AS = AddrInst->getType()->getPointerAddressSpace();
4684 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4685 // This inttoptr is a no-op if the integer type is pointer sized.
4686 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4687 return matchAddr(AddrInst->getOperand(0), Depth);
4688 return false;
4689 }
4690 case Instruction::BitCast:
4691 // BitCast is always a noop, and we can handle it as long as it is
4692 // int->int or pointer->pointer (we don't want int<->fp or something).
4693 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4694 // Don't touch identity bitcasts. These were probably put here by LSR,
4695 // and we don't want to mess around with them. Assume it knows what it
4696 // is doing.
4697 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4698 return matchAddr(AddrInst->getOperand(0), Depth);
4699 return false;
4700 case Instruction::AddrSpaceCast: {
4701 unsigned SrcAS =
4702 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4703 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4704 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4705 return matchAddr(AddrInst->getOperand(0), Depth);
4706 return false;
4707 }
4708 case Instruction::Add: {
4709 // Check to see if we can merge in one operand, then the other. If so, we
4710 // win.
4711 ExtAddrMode BackupAddrMode = AddrMode;
4712 unsigned OldSize = AddrModeInsts.size();
4713 // Start a transaction at this point.
4714 // The LHS may match but not the RHS.
4715 // Therefore, we need a higher level restoration point to undo partially
4716 // matched operation.
4717 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4718 TPT.getRestorationPoint();
4719
4720 // Try to match an integer constant second to increase its chance of ending
4721 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
4722 int First = 0, Second = 1;
4723 if (isa<ConstantInt>(AddrInst->getOperand(First))
4724 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
4725 std::swap(First, Second);
4726 AddrMode.InBounds = false;
4727 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
4728 matchAddr(AddrInst->getOperand(Second), Depth + 1))
4729 return true;
4730
4731 // Restore the old addr mode info.
4732 AddrMode = BackupAddrMode;
4733 AddrModeInsts.resize(OldSize);
4734 TPT.rollback(LastKnownGood);
4735
4736 // Otherwise this was over-aggressive. Try merging operands in the opposite
4737 // order.
4738 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
4739 matchAddr(AddrInst->getOperand(First), Depth + 1))
4740 return true;
4741
4742 // Otherwise we definitely can't merge the ADD in.
4743 AddrMode = BackupAddrMode;
4744 AddrModeInsts.resize(OldSize);
4745 TPT.rollback(LastKnownGood);
4746 break;
4747 }
4748 // case Instruction::Or:
4749 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4750 // break;
4751 case Instruction::Mul:
4752 case Instruction::Shl: {
4753 // Can only handle X*C and X << C.
4754 AddrMode.InBounds = false;
4755 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4756 if (!RHS || RHS->getBitWidth() > 64)
4757 return false;
4758 int64_t Scale = Opcode == Instruction::Shl
4759 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
4760 : RHS->getSExtValue();
4761
4762 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4763 }
4764 case Instruction::GetElementPtr: {
4765 // Scan the GEP. We check it if it contains constant offsets and at most
4766 // one variable offset.
4767 int VariableOperand = -1;
4768 unsigned VariableScale = 0;
4769
4770 int64_t ConstantOffset = 0;
4771 gep_type_iterator GTI = gep_type_begin(AddrInst);
4772 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4773 if (StructType *STy = GTI.getStructTypeOrNull()) {
4774 const StructLayout *SL = DL.getStructLayout(STy);
4775 unsigned Idx =
4776 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4777 ConstantOffset += SL->getElementOffset(Idx);
4778 } else {
4779 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
4780 if (TS.isNonZero()) {
4781 // The optimisations below currently only work for fixed offsets.
4782 if (TS.isScalable())
4783 return false;
4784 int64_t TypeSize = TS.getFixedValue();
4785 if (ConstantInt *CI =
4786 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4787 const APInt &CVal = CI->getValue();
4788 if (CVal.getSignificantBits() <= 64) {
4789 ConstantOffset += CVal.getSExtValue() * TypeSize;
4790 continue;
4791 }
4792 }
4793 // We only allow one variable index at the moment.
4794 if (VariableOperand != -1)
4795 return false;
4796
4797 // Remember the variable index.
4798 VariableOperand = i;
4799 VariableScale = TypeSize;
4800 }
4801 }
4802 }
4803
4804 // A common case is for the GEP to only do a constant offset. In this case,
4805 // just add it to the disp field and check validity.
4806 if (VariableOperand == -1) {
4807 AddrMode.BaseOffs += ConstantOffset;
4808 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4809 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4810 AddrMode.InBounds = false;
4811 return true;
4812 }
4813 AddrMode.BaseOffs -= ConstantOffset;
4814
4815 if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4816 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4817 ConstantOffset > 0) {
4818 // Record GEPs with non-zero offsets as candidates for splitting in
4819 // the event that the offset cannot fit into the r+i addressing mode.
4820 // Simple and common case that only one GEP is used in calculating the
4821 // address for the memory access.
4822 Value *Base = AddrInst->getOperand(0);
4823 auto *BaseI = dyn_cast<Instruction>(Base);
4824 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4825 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4826 (BaseI && !isa<CastInst>(BaseI) &&
4827 !isa<GetElementPtrInst>(BaseI))) {
4828 // Make sure the parent block allows inserting non-PHI instructions
4829 // before the terminator.
4830 BasicBlock *Parent = BaseI ? BaseI->getParent()
4831 : &GEP->getFunction()->getEntryBlock();
4832 if (!Parent->getTerminator()->isEHPad())
4833 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4834 }
4835 }
4836
4837 return false;
4838 }
4839
4840 // Save the valid addressing mode in case we can't match.
4841 ExtAddrMode BackupAddrMode = AddrMode;
4842 unsigned OldSize = AddrModeInsts.size();
4843
4844 // See if the scale and offset amount is valid for this target.
4845 AddrMode.BaseOffs += ConstantOffset;
4846 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4847 AddrMode.InBounds = false;
4848
4849 // Match the base operand of the GEP.
4850 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
4851 // If it couldn't be matched, just stuff the value in a register.
4852 if (AddrMode.HasBaseReg) {
4853 AddrMode = BackupAddrMode;
4854 AddrModeInsts.resize(OldSize);
4855 return false;
4856 }
4857 AddrMode.HasBaseReg = true;
4858 AddrMode.BaseReg = AddrInst->getOperand(0);
4859 }
4860
4861 // Match the remaining variable portion of the GEP.
4862 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4863 Depth)) {
4864 // If it couldn't be matched, try stuffing the base into a register
4865 // instead of matching it, and retrying the match of the scale.
4866 AddrMode = BackupAddrMode;
4867 AddrModeInsts.resize(OldSize);
4868 if (AddrMode.HasBaseReg)
4869 return false;
4870 AddrMode.HasBaseReg = true;
4871 AddrMode.BaseReg = AddrInst->getOperand(0);
4872 AddrMode.BaseOffs += ConstantOffset;
4873 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4874 VariableScale, Depth)) {
4875 // If even that didn't work, bail.
4876 AddrMode = BackupAddrMode;
4877 AddrModeInsts.resize(OldSize);
4878 return false;
4879 }
4880 }
4881
4882 return true;
4883 }
4884 case Instruction::SExt:
4885 case Instruction::ZExt: {
4886 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4887 if (!Ext)
4888 return false;
4889
4890 // Try to move this ext out of the way of the addressing mode.
4891 // Ask for a method for doing so.
4892 TypePromotionHelper::Action TPH =
4893 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4894 if (!TPH)
4895 return false;
4896
4897 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4898 TPT.getRestorationPoint();
4899 unsigned CreatedInstsCost = 0;
4900 unsigned ExtCost = !TLI.isExtFree(Ext);
4901 Value *PromotedOperand =
4902 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4903 // SExt has been moved away.
4904 // Thus either it will be rematched later in the recursive calls or it is
4905 // gone. Anyway, we must not fold it into the addressing mode at this point.
4906 // E.g.,
4907 // op = add opnd, 1
4908 // idx = ext op
4909 // addr = gep base, idx
4910 // is now:
4911 // promotedOpnd = ext opnd <- no match here
4912 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4913 // addr = gep base, op <- match
4914 if (MovedAway)
4915 *MovedAway = true;
4916
4917 assert(PromotedOperand &&
4918 "TypePromotionHelper should have filtered out those cases");
4919
4920 ExtAddrMode BackupAddrMode = AddrMode;
4921 unsigned OldSize = AddrModeInsts.size();
4922
4923 if (!matchAddr(PromotedOperand, Depth) ||
4924 // The total of the new cost is equal to the cost of the created
4925 // instructions.
4926 // The total of the old cost is equal to the cost of the extension plus
4927 // what we have saved in the addressing mode.
4928 !isPromotionProfitable(CreatedInstsCost,
4929 ExtCost + (AddrModeInsts.size() - OldSize),
4930 PromotedOperand)) {
4931 AddrMode = BackupAddrMode;
4932 AddrModeInsts.resize(OldSize);
4933 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
4934 TPT.rollback(LastKnownGood);
4935 return false;
4936 }
4937 return true;
4938 }
4939 }
4940 return false;
4941}
4942
4943/// If we can, try to add the value of 'Addr' into the current addressing mode.
4944/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4945/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4946/// for the target.
4947///
4948bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4949 // Start a transaction at this point that we will rollback if the matching
4950 // fails.
4951 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4952 TPT.getRestorationPoint();
4953 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4954 if (CI->getValue().isSignedIntN(64)) {
4955 // Fold in immediates if legal for the target.
4956 AddrMode.BaseOffs += CI->getSExtValue();
4957 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4958 return true;
4959 AddrMode.BaseOffs -= CI->getSExtValue();
4960 }
4961 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4962 // If this is a global variable, try to fold it into the addressing mode.
4963 if (!AddrMode.BaseGV) {
4964 AddrMode.BaseGV = GV;
4965 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4966 return true;
4967 AddrMode.BaseGV = nullptr;
4968 }
4969 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4970 ExtAddrMode BackupAddrMode = AddrMode;
4971 unsigned OldSize = AddrModeInsts.size();
4972
4973 // Check to see if it is possible to fold this operation.
4974 bool MovedAway = false;
4975 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4976 // This instruction may have been moved away. If so, there is nothing
4977 // to check here.
4978 if (MovedAway)
4979 return true;
4980 // Okay, it's possible to fold this. Check to see if it is actually
4981 // *profitable* to do so. We use a simple cost model to avoid increasing
4982 // register pressure too much.
4983 if (I->hasOneUse() ||
4984 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4985 AddrModeInsts.push_back(I);
4986 return true;
4987 }
4988
4989 // It isn't profitable to do this, roll back.
4990 AddrMode = BackupAddrMode;
4991 AddrModeInsts.resize(OldSize);
4992 TPT.rollback(LastKnownGood);
4993 }
4994 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4995 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4996 return true;
4997 TPT.rollback(LastKnownGood);
4998 } else if (isa<ConstantPointerNull>(Addr)) {
4999 // Null pointer gets folded without affecting the addressing mode.
5000 return true;
5001 }
5002
5003 // Worse case, the target should support [reg] addressing modes. :)
5004 if (!AddrMode.HasBaseReg) {
5005 AddrMode.HasBaseReg = true;
5006 AddrMode.BaseReg = Addr;
5007 // Still check for legality in case the target supports [imm] but not [i+r].
5008 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5009 return true;
5010 AddrMode.HasBaseReg = false;
5011 AddrMode.BaseReg = nullptr;
5012 }
5013
5014 // If the base register is already taken, see if we can do [r+r].
5015 if (AddrMode.Scale == 0) {
5016 AddrMode.Scale = 1;
5017 AddrMode.ScaledReg = Addr;
5018 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5019 return true;
5020 AddrMode.Scale = 0;
5021 AddrMode.ScaledReg = nullptr;
5022 }
5023 // Couldn't match.
5024 TPT.rollback(LastKnownGood);
5025 return false;
5026}
5027
5028/// Check to see if all uses of OpVal by the specified inline asm call are due
5029/// to memory operands. If so, return true, otherwise return false.
5031 const TargetLowering &TLI,
5032 const TargetRegisterInfo &TRI) {
5033 const Function *F = CI->getFunction();
5034 TargetLowering::AsmOperandInfoVector TargetConstraints =
5035 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
5036
5037 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5038 // Compute the constraint code and ConstraintType to use.
5039 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5040
5041 // If this asm operand is our Value*, and if it isn't an indirect memory
5042 // operand, we can't fold it! TODO: Also handle C_Address?
5043 if (OpInfo.CallOperandVal == OpVal &&
5044 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5045 !OpInfo.isIndirect))
5046 return false;
5047 }
5048
5049 return true;
5050}
5051
5052/// Recursively walk all the uses of I until we find a memory use.
5053/// If we find an obviously non-foldable instruction, return true.
5054/// Add accessed addresses and types to MemoryUses.
5056 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5057 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5058 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5059 BlockFrequencyInfo *BFI, unsigned &SeenInsts) {
5060 // If we already considered this instruction, we're done.
5061 if (!ConsideredInsts.insert(I).second)
5062 return false;
5063
5064 // If this is an obviously unfoldable instruction, bail out.
5065 if (!MightBeFoldableInst(I))
5066 return true;
5067
5068 // Loop over all the uses, recursively processing them.
5069 for (Use &U : I->uses()) {
5070 // Conservatively return true if we're seeing a large number or a deep chain
5071 // of users. This avoids excessive compilation times in pathological cases.
5072 if (SeenInsts++ >= MaxAddressUsersToScan)
5073 return true;
5074
5075 Instruction *UserI = cast<Instruction>(U.getUser());
5076 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5077 MemoryUses.push_back({&U, LI->getType()});
5078 continue;
5079 }
5080
5081 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5082 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5083 return true; // Storing addr, not into addr.
5084 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5085 continue;
5086 }
5087
5088 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5089 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5090 return true; // Storing addr, not into addr.
5091 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5092 continue;
5093 }
5094
5095 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
5096 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5097 return true; // Storing addr, not into addr.
5098 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5099 continue;
5100 }
5101
5102 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5103 if (CI->hasFnAttr(Attribute::Cold)) {
5104 // If this is a cold call, we can sink the addressing calculation into
5105 // the cold path. See optimizeCallInst
5106 bool OptForSize =
5107 OptSize || llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
5108 if (!OptForSize)
5109 continue;
5110 }
5111
5112 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5113 if (!IA)
5114 return true;
5115
5116 // If this is a memory operand, we're cool, otherwise bail out.
5117 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5118 return true;
5119 continue;
5120 }
5121
5122 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5123 PSI, BFI, SeenInsts))
5124 return true;
5125 }
5126
5127 return false;
5128}
5129
5131 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5132 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5134 unsigned SeenInsts = 0;
5135 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5136 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5137 PSI, BFI, SeenInsts);
5138}
5139
5140
5141/// Return true if Val is already known to be live at the use site that we're
5142/// folding it into. If so, there is no cost to include it in the addressing
5143/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5144/// instruction already.
5145bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5146 Value *KnownLive1,
5147 Value *KnownLive2) {
5148 // If Val is either of the known-live values, we know it is live!
5149 if (Val ==