LLVM 24.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
16#include "CodeGenOptions.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
22#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/Statistic.h"
47#include "llvm/Config/llvm-config.h"
48#include "llvm/IR/Argument.h"
49#include "llvm/IR/Attributes.h"
50#include "llvm/IR/BasicBlock.h"
51#include "llvm/IR/CFG.h"
52#include "llvm/IR/Constant.h"
53#include "llvm/IR/Constants.h"
54#include "llvm/IR/CycleInfo.h"
55#include "llvm/IR/DataLayout.h"
56#include "llvm/IR/DebugInfo.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
61#include "llvm/IR/GlobalValue.h"
63#include "llvm/IR/IRBuilder.h"
64#include "llvm/IR/InlineAsm.h"
65#include "llvm/IR/InstrTypes.h"
66#include "llvm/IR/Instruction.h"
69#include "llvm/IR/Intrinsics.h"
70#include "llvm/IR/IntrinsicsAArch64.h"
71#include "llvm/IR/LLVMContext.h"
72#include "llvm/IR/MDBuilder.h"
73#include "llvm/IR/Module.h"
74#include "llvm/IR/Operator.h"
77#include "llvm/IR/Statepoint.h"
78#include "llvm/IR/Type.h"
79#include "llvm/IR/Use.h"
80#include "llvm/IR/User.h"
81#include "llvm/IR/Value.h"
82#include "llvm/IR/ValueHandle.h"
83#include "llvm/IR/ValueMap.h"
85#include "llvm/Pass.h"
91#include "llvm/Support/Debug.h"
101#include <algorithm>
102#include <cassert>
103#include <cstdint>
104#include <iterator>
105#include <limits>
106#include <memory>
107#include <optional>
108#include <utility>
109#include <vector>
110
111using namespace llvm;
112using namespace llvm::PatternMatch;
113
114#define DEBUG_TYPE "codegenprepare"
115
116STATISTIC(NumBlocksElim, "Number of blocks eliminated");
117STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
118STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
119STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
120 "sunken Cmps");
121STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
122 "of sunken Casts");
123STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
124 "computations were sunk");
125STATISTIC(NumMemoryInstsPhiCreated,
126 "Number of phis created when address "
127 "computations were sunk to memory instructions");
128STATISTIC(NumMemoryInstsSelectCreated,
129 "Number of select created when address "
130 "computations were sunk to memory instructions");
131STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
132STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
133STATISTIC(NumAndsAdded,
134 "Number of and mask instructions added to form ext loads");
135STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
136STATISTIC(NumRetsDup, "Number of return instructions duplicated");
137STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
138STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
139STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
140
141namespace {
142
143enum ExtType {
144 ZeroExtension, // Zero extension has been seen.
145 SignExtension, // Sign extension has been seen.
146 BothExtension // This extension type is used if we saw sext after
147 // ZeroExtension had been set, or if we saw zext after
148 // SignExtension had been set. It makes the type
149 // information of a promoted instruction invalid.
150};
151
152enum ModifyDT {
153 NotModifyDT, // Not Modify any DT.
154 ModifyBBDT, // Modify the Basic Block Dominator Tree.
155 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
156 // This usually means we move/delete/insert instruction
157 // in a Basic Block. So we should re-iterate instructions
158 // in such Basic Block.
159};
160
161using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
162using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
163using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
165using ValueToSExts = MapVector<Value *, SExts>;
166
167class TypePromotionTransaction;
168
169class CodeGenPrepare {
170 friend class CodeGenPrepareLegacyPass;
171 const CodeGenOptions &Opts;
172 const TargetMachine *TM = nullptr;
173 const TargetSubtargetInfo *SubtargetInfo = nullptr;
174 const TargetLowering *TLI = nullptr;
175 const TargetRegisterInfo *TRI = nullptr;
176 const TargetTransformInfo *TTI = nullptr;
177 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
178 const TargetLibraryInfo *TLInfo = nullptr;
179 DomTreeUpdater *DTU = nullptr;
180 LoopInfo *LI = nullptr;
181 BlockFrequencyInfo *BFI;
182 BranchProbabilityInfo *BPI;
183 ProfileSummaryInfo *PSI = nullptr;
184
185 /// As we scan instructions optimizing them, this is the next instruction
186 /// to optimize. Transforms that can invalidate this should update it.
187 BasicBlock::iterator CurInstIterator;
188
189 /// Keeps track of non-local addresses that have been sunk into a block.
190 /// This allows us to avoid inserting duplicate code for blocks with
191 /// multiple memory accesses of the same address. The usage of WeakTrackingVH
192 /// enables SunkAddrs to be treated as a cache whose entries can be
193 /// invalidated if a sunken address computation has been erased.
194 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
195
196 /// Keeps track of all instructions inserted for the current function.
197 SetOfInstrs InsertedInsts;
198
199 /// Keeps track of the type of the related instruction before their
200 /// promotion for the current function.
201 InstrToOrigTy PromotedInsts;
202
203 /// Keep track of instructions removed during promotion.
204 SetOfInstrs RemovedInsts;
205
206 /// Keep track of sext chains based on their initial value.
207 DenseMap<Value *, Instruction *> SeenChainsForSExt;
208
209 /// Keep track of GEPs accessing the same data structures such as structs or
210 /// arrays that are candidates to be split later because of their large
211 /// size.
212 MapVector<AssertingVH<Value>,
214 LargeOffsetGEPMap;
215
216 /// Keep track of new GEP base after splitting the GEPs having large offset.
217 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
218
219 /// Map serial numbers to Large offset GEPs.
220 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
221
222 /// Keep track of SExt promoted.
223 ValueToSExts ValToSExtendedUses;
224
225 /// True if the function has the OptSize attribute.
226 bool OptSize;
227
228 /// DataLayout for the Function being processed.
229 const DataLayout *DL = nullptr;
230
231public:
232 CodeGenPrepare(const TargetMachine *TM)
233 : Opts(cl::LibraryOptionsContext::get<CodeGenOptions>(
234 TM->Options.MCOptions.LibraryOptions)),
235 TM(TM) {}
236 /// If encounter huge function, we need to limit the build time.
237 bool IsHugeFunc = false;
238
239 /// FreshBBs is like worklist, it collected the updated BBs which need
240 /// to be optimized again.
241 /// Note: Consider building time in this pass, when a BB updated, we need
242 /// to insert such BB into FreshBBs for huge function.
243 SmallPtrSet<BasicBlock *, 32> FreshBBs;
244
245 void releaseMemory() {
246 // Clear per function information.
247 InsertedInsts.clear();
248 PromotedInsts.clear();
249 FreshBBs.clear();
250 }
251
253
254private:
255 template <typename F>
256 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
257 // Substituting can cause recursive simplifications, which can invalidate
258 // our iterator. Use a WeakTrackingVH to hold onto it in case this
259 // happens.
260 Value *CurValue = &*CurInstIterator;
261 WeakTrackingVH IterHandle(CurValue);
262
263 f();
264
265 // If the iterator instruction was recursively deleted, start over at the
266 // start of the block.
267 if (IterHandle != CurValue) {
268 CurInstIterator = BB->begin();
269 SunkAddrs.clear();
270 }
271 }
272
273 // Get the DominatorTree, updating it if necessary.
274 DominatorTree &getDT() { return DTU->getDomTree(); }
275
276 void removeAllAssertingVHReferences(Value *V);
277 bool eliminateAssumptions(Function &F);
278 bool eliminateFallThrough(Function &F);
279 bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
280 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
281 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
282 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
283 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
284 bool isPreheader);
285 bool makeBitReverse(Instruction &I);
286 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
287 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
288 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
289 unsigned AddrSpace);
290 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
291 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
292 ModifyDT &ModifiedDT);
293 bool optimizeInlineAsmInst(CallInst *CS);
294 bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
295 bool optimizeExt(Instruction *&I);
296 bool optimizeExtUses(Instruction *I);
297 bool optimizeLoadExt(LoadInst *Load);
298 bool optimizeShiftInst(BinaryOperator *BO);
299 bool optimizeFunnelShift(IntrinsicInst *Fsh);
300 bool optimizeSelectInst(SelectInst *SI);
301 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
302 bool optimizeSwitchType(SwitchInst *SI);
303 bool optimizeSwitchPhiConstants(SwitchInst *SI);
304 bool optimizeSwitchInst(SwitchInst *SI);
305 bool optimizeExtractElementInst(Instruction *Inst);
306 bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
307 bool fixupDbgVariableRecord(DbgVariableRecord &I);
308 bool fixupDbgVariableRecordsOnInst(Instruction &I);
309 bool placeDbgValues(Function &F);
310 bool placePseudoProbes(Function &F);
311 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
312 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
313 bool tryToPromoteExts(TypePromotionTransaction &TPT,
314 const SmallVectorImpl<Instruction *> &Exts,
315 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
316 unsigned CreatedInstsCost = 0);
317 bool mergeSExts(Function &F);
318 bool splitLargeGEPOffsets();
319 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
320 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
321 bool optimizePhiTypes(Function &F);
322 bool performAddressTypePromotion(
323 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
324 bool HasPromoted, TypePromotionTransaction &TPT,
325 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
326 bool splitBranchCondition(Function &F);
327 bool simplifyOffsetableRelocate(GCStatepointInst &I);
328
329 bool tryToSinkFreeOperands(Instruction *I);
330 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
331 CmpInst *Cmp, Intrinsic::ID IID);
332 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
333 bool optimizeURem(Instruction *Rem);
334 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
335 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
336 bool unfoldPowerOf2Test(CmpInst *Cmp);
337 void verifyBFIUpdates(Function &F);
338 bool _run(Function &F);
339};
340
341class CodeGenPrepareLegacyPass : public FunctionPass {
342public:
343 static char ID; // Pass identification, replacement for typeid
344
345 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
346
347 bool runOnFunction(Function &F) override;
348
349 StringRef getPassName() const override { return "CodeGen Prepare"; }
350
351 void getAnalysisUsage(AnalysisUsage &AU) const override {
352 // FIXME: When we can selectively preserve passes, preserve the domtree.
353 AU.addRequired<ProfileSummaryInfoWrapperPass>();
354 AU.addRequired<TargetLibraryInfoWrapperPass>();
355 AU.addRequired<TargetPassConfig>();
356 AU.addRequired<TargetTransformInfoWrapperPass>();
357 AU.addRequired<DominatorTreeWrapperPass>();
358 AU.addRequired<LoopInfoWrapperPass>();
359 AU.addRequired<BranchProbabilityInfoWrapperPass>();
360 AU.addRequired<BlockFrequencyInfoWrapperPass>();
361 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
362 }
363};
364
365} // end anonymous namespace
366
367char CodeGenPrepareLegacyPass::ID = 0;
368
369bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
370 if (skipFunction(F))
371 return false;
372 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
373 CodeGenPrepare CGP(TM);
374 CGP.DL = &F.getDataLayout();
375 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
376 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
377 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
378 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
379 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
380 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
381 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
382 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
383 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
384 auto BBSPRWP =
385 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
386 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
387 DomTreeUpdater DTUpdater(
388 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
389 DomTreeUpdater::UpdateStrategy::Lazy);
390 CGP.DTU = &DTUpdater;
391
392 return CGP._run(F);
393}
394
395INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
396 "Optimize for code generation", false, false)
404INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
405 "Optimize for code generation", false, false)
406
408 return new CodeGenPrepareLegacyPass();
409}
410
413 CodeGenPrepare CGP(TM);
414
415 bool Changed = CGP.run(F, AM);
416 if (!Changed)
417 return PreservedAnalyses::all();
418
422 return PA;
423}
424
425bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
426 DL = &F.getDataLayout();
427 SubtargetInfo = TM->getSubtargetImpl(F);
428 TLI = SubtargetInfo->getTargetLowering();
429 TRI = SubtargetInfo->getRegisterInfo();
430 TLInfo = &AM.getResult<TargetLibraryAnalysis>(F);
432 LI = &AM.getResult<LoopAnalysis>(F);
435 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
436 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
437 if (!PSI)
438 reportFatalUsageError("this pass requires the profile-summary module "
439 "analysis to be available");
440 BBSectionsProfileReader =
443 DomTreeUpdater::UpdateStrategy::Lazy);
444 DTU = &DTUpdater;
445 return _run(F);
446}
447
448bool CodeGenPrepare::_run(Function &F) {
449 bool EverMadeChange = false;
450
451 OptSize = F.hasOptSize();
452 // Use the basic-block-sections profile to promote hot functions to .text.hot
453 // if requested.
454 if (Opts.bbsections_guided_section_prefix && BBSectionsProfileReader &&
455 BBSectionsProfileReader->isFunctionHot(F.getName())) {
456 (void)F.setSectionPrefix("hot");
457 } else if (Opts.profile_guided_section_prefix) {
458 // The hot attribute overwrites profile count based hotness while profile
459 // counts based hotness overwrite the cold attribute.
460 // This is a conservative behabvior.
461 if (F.hasFnAttribute(Attribute::Hot) ||
462 PSI->isFunctionHotInCallGraph(&F, *BFI))
463 (void)F.setSectionPrefix("hot");
464 // If PSI shows this function is not hot, we will placed the function
465 // into unlikely section if (1) PSI shows this is a cold function, or
466 // (2) the function has a attribute of cold.
467 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
468 F.hasFnAttribute(Attribute::Cold))
469 (void)F.setSectionPrefix("unlikely");
470 else if (Opts.profile_unknown_in_special_section &&
471 PSI->hasPartialSampleProfile() && PSI->isFunctionHotnessUnknown(F))
472 (void)F.setSectionPrefix("unknown");
473 }
474
475 /// This optimization identifies DIV instructions that can be
476 /// profitably bypassed and carried out with a shorter, faster divide.
477 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
478 const DenseMap<unsigned int, unsigned int> &BypassWidths =
480 BasicBlock *BB = &*F.begin();
481 while (BB != nullptr) {
482 // bypassSlowDivision may create new BBs, but we don't want to reapply the
483 // optimization to those blocks.
484 BasicBlock *Next = BB->getNextNode();
485 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
486 EverMadeChange |= bypassSlowDivision(BB, BypassWidths, DTU, LI, BPI);
487 BB = Next;
488 }
489 }
490
491 // Get rid of @llvm.assume builtins before attempting to eliminate empty
492 // blocks, since there might be blocks that only contain @llvm.assume calls
493 // (plus arguments that we can get rid of).
494 EverMadeChange |= eliminateAssumptions(F);
495
496 auto resetLoopInfo = [this]() {
497 LI->releaseMemory();
498 LI->analyze(DTU->getDomTree());
499 };
500
501 // Eliminate blocks that contain only PHI nodes and an
502 // unconditional branch.
503 bool ResetLI = false;
504 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
505 if (ResetLI)
506 resetLoopInfo();
507
508 if (Opts.cgp_branch_opts)
509 EverMadeChange |= splitBranchCondition(F);
510
511 // Split some critical edges where one of the sources is an indirect branch,
512 // to help generate sane code for PHIs involving such edges.
513 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
514 BPI, BFI, DTU);
515 EverMadeChange |= Split;
516 if (Split)
517 resetLoopInfo();
518
519#ifndef NDEBUG
520 if (VerifyDomInfo)
521 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
522 "Incorrect DominatorTree updates in CGP");
523
524 if (VerifyLoopInfo)
525 LI->verify();
526#endif
527
528 // If we are optimzing huge function, we need to consider the build time.
529 // Because the basic algorithm's complex is near O(N!).
530 IsHugeFunc = F.size() > Opts.cgp_huge_func;
531
532 bool MadeChange = true;
533 bool FuncIterated = false;
534 while (MadeChange) {
535 MadeChange = false;
536
537 // This is required because optimizeBlock() calls getDT() inside the loop
538 // below, which flushes pending updates and may delete dead blocks, leading
539 // to iterator invalidation.
540 DTU->flush();
541
542 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
543 if (FuncIterated && !FreshBBs.contains(&BB))
544 continue;
545
546 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
547 bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
548
549 MadeChange |= Changed;
550 if (IsHugeFunc) {
551 // If the BB is updated, it may still has chance to be optimized.
552 // This usually happen at sink optimization.
553 // For example:
554 //
555 // bb0:
556 // %and = and i32 %a, 4
557 // %cmp = icmp eq i32 %and, 0
558 //
559 // If the %cmp sink to other BB, the %and will has chance to sink.
560 if (Changed)
561 FreshBBs.insert(&BB);
562 else if (FuncIterated)
563 FreshBBs.erase(&BB);
564 } else {
565 // For small/normal functions, we restart BB iteration if the dominator
566 // tree of the Function was changed.
567 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
568 break;
569 }
570 }
571 // We have iterated all the BB in the (only work for huge) function.
572 FuncIterated = IsHugeFunc;
573
574 if (Opts.cgp_type_promotion_merge && !ValToSExtendedUses.empty())
575 MadeChange |= mergeSExts(F);
576 if (!LargeOffsetGEPMap.empty())
577 MadeChange |= splitLargeGEPOffsets();
578 MadeChange |= optimizePhiTypes(F);
579
580 if (MadeChange)
581 eliminateFallThrough(F);
582
583#ifndef NDEBUG
584 if (VerifyDomInfo)
585 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
586 "Incorrect DominatorTree updates in CGP");
587
588 if (VerifyLoopInfo)
589 LI->verify();
590#endif
591
592 // Really free removed instructions during promotion.
593 for (Instruction *I : RemovedInsts)
594 I->deleteValue();
595
596 EverMadeChange |= MadeChange;
597 SeenChainsForSExt.clear();
598 ValToSExtendedUses.clear();
599 RemovedInsts.clear();
600 LargeOffsetGEPMap.clear();
601 LargeOffsetGEPID.clear();
602 }
603
604 NewGEPBases.clear();
605 SunkAddrs.clear();
606
607 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
608 LI = nullptr;
609
610 if (Opts.cgp_branch_opts) {
611 MadeChange = false;
612 // Use a set vector to get deterministic iteration order. The order the
613 // blocks are removed may affect whether or not PHI nodes in successors
614 // are removed.
615 SmallSetVector<BasicBlock *, 8> WorkList;
616 for (BasicBlock &BB : F) {
618 MadeChange |= ConstantFoldTerminator(&BB, true, nullptr, DTU);
619 if (!MadeChange)
620 continue;
621
622 for (BasicBlock *Succ : Successors)
623 if (pred_empty(Succ))
624 WorkList.insert(Succ);
625 }
626
627 // Delete the dead blocks and any of their dead successors.
628 MadeChange |= !WorkList.empty();
629 while (!WorkList.empty()) {
630 BasicBlock *BB = WorkList.pop_back_val();
632
633 DeleteDeadBlock(BB, DTU);
634
635 for (BasicBlock *Succ : Successors)
636 if (pred_empty(Succ))
637 WorkList.insert(Succ);
638 }
639
640 // Flush pending DT updates in order to finalise deletion of dead blocks.
641 DTU->flush();
642
643 // Merge pairs of basic blocks with unconditional branches, connected by
644 // a single edge.
645 if (EverMadeChange || MadeChange)
646 MadeChange |= eliminateFallThrough(F);
647
648 EverMadeChange |= MadeChange;
649 }
650
651 if (Opts.cgp_gc_opts) {
653 for (BasicBlock &BB : F)
654 for (Instruction &I : BB)
655 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
656 Statepoints.push_back(SP);
657 for (auto &I : Statepoints)
658 EverMadeChange |= simplifyOffsetableRelocate(*I);
659 }
660
661 // Do this last to clean up use-before-def scenarios introduced by other
662 // preparatory transforms.
663 EverMadeChange |= placeDbgValues(F);
664 EverMadeChange |= placePseudoProbes(F);
665
666#ifndef NDEBUG
667 if (Opts.cgp_verify_bfi_updates)
668 verifyBFIUpdates(F);
669#endif
670
671 return EverMadeChange;
672}
673
674bool CodeGenPrepare::eliminateAssumptions(Function &F) {
675 bool MadeChange = false;
676 for (BasicBlock &BB : F) {
677 CurInstIterator = BB.begin();
678 while (CurInstIterator != BB.end()) {
679 Instruction *I = &*(CurInstIterator++);
680 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
681 MadeChange = true;
682 Value *Operand = Assume->getOperand(0);
683 Assume->eraseFromParent();
684
685 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
686 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
687 });
688 }
689 }
690 }
691 return MadeChange;
692}
693
694/// An instruction is about to be deleted, so remove all references to it in our
695/// GEP-tracking data strcutures.
696void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
697 LargeOffsetGEPMap.erase(V);
698 NewGEPBases.erase(V);
699
701 if (!GEP)
702 return;
703
704 LargeOffsetGEPID.erase(GEP);
705
706 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
707 if (VecI == LargeOffsetGEPMap.end())
708 return;
709
710 auto &GEPVector = VecI->second;
711 llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
712
713 if (GEPVector.empty())
714 LargeOffsetGEPMap.erase(VecI);
715}
716
717// Verify BFI has been updated correctly by recomputing BFI and comparing them.
718[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
719 CycleInfo NewCI;
720 NewCI.compute(F);
721 BranchProbabilityInfo NewBPI(F, NewCI, TLInfo);
722 BlockFrequencyInfo NewBFI(F, NewBPI, NewCI);
723 NewBFI.verifyMatch(*BFI);
724}
725
726/// Merge basic blocks which are connected by a single edge, where one of the
727/// basic blocks has a single successor pointing to the other basic block,
728/// which has a single predecessor.
729bool CodeGenPrepare::eliminateFallThrough(Function &F) {
730 bool Changed = false;
731 SmallPtrSet<BasicBlock *, 8> Preds;
732 // Scan all of the blocks in the function, except for the entry block.
733 for (auto &Block : llvm::drop_begin(F)) {
734 auto *BB = &Block;
735 if (DTU->isBBPendingDeletion(BB))
736 continue;
737 // If the destination block has a single pred, then this is a trivial
738 // edge, just collapse it.
739 BasicBlock *SinglePred = BB->getSinglePredecessor();
740
741 // Don't merge if BB's address is taken.
742 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
743 continue;
744
745 if (isa<UncondBrInst>(SinglePred->getTerminator())) {
746 Changed = true;
747 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
748
749 // Merge BB into SinglePred and delete it.
750 MergeBlockIntoPredecessor(BB, DTU, LI);
751 Preds.insert(SinglePred);
752
753 if (IsHugeFunc) {
754 // Update FreshBBs to optimize the merged BB.
755 FreshBBs.insert(SinglePred);
756 FreshBBs.erase(BB);
757 }
758 }
759 }
760
761 // (Repeatedly) merging blocks into their predecessors can create redundant
762 // debug intrinsics.
763 for (auto *Pred : Preds)
764 if (!DTU->isBBPendingDeletion(Pred))
766
767 return Changed;
768}
769
770/// Find a destination block from BB if BB is mergeable empty block.
771BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
772 // If this block doesn't end with an uncond branch, ignore it.
773 UncondBrInst *BI = dyn_cast<UncondBrInst>(BB->getTerminator());
774 if (!BI)
775 return nullptr;
776
777 // If the instruction before the branch (skipping debug info) isn't a phi
778 // node, then other stuff is happening here.
780 if (BBI != BB->begin()) {
781 --BBI;
782 if (!isa<PHINode>(BBI))
783 return nullptr;
784 }
785
786 // Do not break infinite loops.
787 BasicBlock *DestBB = BI->getSuccessor();
788 if (DestBB == BB)
789 return nullptr;
790
791 if (!canMergeBlocks(BB, DestBB))
792 DestBB = nullptr;
793
794 return DestBB;
795}
796
797/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
798/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
799/// edges in ways that are non-optimal for isel. Start by eliminating these
800/// blocks so we can split them the way we want them.
801bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
802 SmallPtrSet<BasicBlock *, 16> Preheaders;
803 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
804 while (!LoopList.empty()) {
805 Loop *L = LoopList.pop_back_val();
806 llvm::append_range(LoopList, *L);
807 if (BasicBlock *Preheader = L->getLoopPreheader())
808 Preheaders.insert(Preheader);
809 }
810
811 ResetLI = false;
812 bool MadeChange = false;
813 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
814 // Note that this intentionally skips the entry block.
815 for (auto &Block : llvm::drop_begin(F)) {
816 // Delete phi nodes that could block deleting other empty blocks.
817 if (Opts.cgp_delete_phis)
818 MadeChange |= DeleteDeadPHIs(&Block, TLInfo, nullptr, &KnownNonDeadPHIs);
819 }
820
821 for (auto &Block : llvm::drop_begin(F)) {
822 auto *BB = &Block;
823 if (DTU->isBBPendingDeletion(BB))
824 continue;
825 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
826 if (!DestBB ||
827 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
828 continue;
829
830 ResetLI |= eliminateMostlyEmptyBlock(BB);
831 MadeChange = true;
832 }
833 return MadeChange;
834}
835
836bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
837 BasicBlock *DestBB,
838 bool isPreheader) {
839 // Do not delete loop preheaders if doing so would create a critical edge.
840 // Loop preheaders can be good locations to spill registers. If the
841 // preheader is deleted and we create a critical edge, registers may be
842 // spilled in the loop body instead.
843 if (Opts.cgp_preheader_prot && isPreheader &&
844 !(BB->getSinglePredecessor() &&
846 return false;
847
848 // Skip merging if the block's successor is also a successor to any callbr
849 // that leads to this block.
850 // FIXME: Is this really needed? Is this a correctness issue?
851 for (BasicBlock *Pred : predecessors(BB)) {
852 if (isa<CallBrInst>(Pred->getTerminator()) &&
854 return false;
855 }
856
857 // Try to skip merging if the unique predecessor of BB is terminated by a
858 // switch or indirect branch instruction, and BB is used as an incoming block
859 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
860 // add COPY instructions in the predecessor of BB instead of BB (if it is not
861 // merged). Note that the critical edge created by merging such blocks wont be
862 // split in MachineSink because the jump table is not analyzable. By keeping
863 // such empty block (BB), ISel will place COPY instructions in BB, not in the
864 // predecessor of BB.
866 if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
867 isa<IndirectBrInst>(Pred->getTerminator())))
868 return true;
869
870 if (BB->getTerminator() != &*BB->getFirstNonPHIOrPseudoProbe())
871 return true;
872
873 // We use a simple cost heuristic which determine skipping merging is
874 // profitable if the cost of skipping merging is less than the cost of
875 // merging : Cost(skipping merging) < Cost(merging BB), where the
876 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
877 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
878 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
879 // Freq(Pred) / Freq(BB) > 2.
880 // Note that if there are multiple empty blocks sharing the same incoming
881 // value for the PHIs in the DestBB, we consider them together. In such
882 // case, Cost(merging BB) will be the sum of their frequencies.
883
884 if (!isa<PHINode>(DestBB->begin()))
885 return true;
886
887 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
888
889 // Find all other incoming blocks from which incoming values of all PHIs in
890 // DestBB are the same as the ones from BB.
891 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
892 if (DestBBPred == BB)
893 continue;
894
895 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
896 return DestPN.getIncomingValueForBlock(BB) ==
897 DestPN.getIncomingValueForBlock(DestBBPred);
898 }))
899 SameIncomingValueBBs.insert(DestBBPred);
900 }
901
902 // See if all BB's incoming values are same as the value from Pred. In this
903 // case, no reason to skip merging because COPYs are expected to be place in
904 // Pred already.
905 if (SameIncomingValueBBs.count(Pred))
906 return true;
907
908 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
909 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
910
911 for (auto *SameValueBB : SameIncomingValueBBs)
912 if (SameValueBB->getUniquePredecessor() == Pred &&
913 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
914 BBFreq += BFI->getBlockFreq(SameValueBB);
915
916 std::optional<BlockFrequency> Limit =
917 BBFreq.mul(Opts.cgp_freq_ratio_to_skip_merge);
918 return !Limit || PredFreq <= *Limit;
919}
920
921/// Return true if we can merge BB into DestBB if there is a single
922/// unconditional branch between them, and BB contains no other non-phi
923/// instructions.
924bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
925 const BasicBlock *DestBB) const {
926 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
927 // the successor. If there are more complex condition (e.g. preheaders),
928 // don't mess around with them.
929 for (const PHINode &PN : BB->phis()) {
930 for (const Instruction *UI : PN.users()) {
931 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
932 return false;
933 // If User is inside DestBB block and it is a PHINode then check
934 // incoming value. If incoming value is not from BB then this is
935 // a complex condition (e.g. preheaders) we want to avoid here.
936 if (UI->getParent() == DestBB) {
937 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
938 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
939 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
940 if (Insn && Insn->getParent() == BB &&
941 Insn->getParent() != UPN->getIncomingBlock(I))
942 return false;
943 }
944 }
945 }
946 }
947
948 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
949 // and DestBB may have conflicting incoming values for the block. If so, we
950 // can't merge the block.
951 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
952 if (!DestBBPN)
953 return true; // no conflict.
954
955 // Collect the preds of BB.
956 SmallPtrSet<const BasicBlock *, 16> BBPreds;
957 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
958 // It is faster to get preds from a PHI than with pred_iterator.
959 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
960 BBPreds.insert(BBPN->getIncomingBlock(i));
961 } else {
962 BBPreds.insert_range(predecessors(BB));
963 }
964
965 // Walk the preds of DestBB.
966 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
967 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
968 if (BBPreds.count(Pred)) { // Common predecessor?
969 for (const PHINode &PN : DestBB->phis()) {
970 const Value *V1 = PN.getIncomingValueForBlock(Pred);
971 const Value *V2 = PN.getIncomingValueForBlock(BB);
972
973 // If V2 is a phi node in BB, look up what the mapped value will be.
974 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
975 if (V2PN->getParent() == BB)
976 V2 = V2PN->getIncomingValueForBlock(Pred);
977
978 // If there is a conflict, bail out.
979 if (V1 != V2)
980 return false;
981 }
982 }
983 }
984
985 return true;
986}
987
988/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
989static void replaceAllUsesWith(Value *Old, Value *New,
991 bool IsHuge) {
992 auto *OldI = dyn_cast<Instruction>(Old);
993 if (OldI && IsHuge) {
994 for (Instruction *User : OldI->users())
995 FreshBBs.insert(User->getParent());
996 }
997 Old->replaceAllUsesWith(New);
998}
999
1000/// Eliminate a basic block that has only phi's and an unconditional branch in
1001/// it.
1002/// Indicate that the LoopInfo was modified only if it wasn't updated.
1003bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1004 UncondBrInst *BI = cast<UncondBrInst>(BB->getTerminator());
1005 BasicBlock *DestBB = BI->getSuccessor();
1006
1007 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1008 << *BB << *DestBB);
1009
1010 // If the destination block has a single pred, then this is a trivial edge,
1011 // just collapse it.
1012 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1013 if (SinglePred != DestBB) {
1014 assert(SinglePred == BB &&
1015 "Single predecessor not the same as predecessor");
1016 // Merge DestBB into SinglePred/BB and delete it.
1017 MergeBlockIntoPredecessor(DestBB, DTU, LI);
1018 // Note: BB(=SinglePred) will not be deleted on this path.
1019 // DestBB(=its single successor) is the one that was deleted.
1020 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1021
1022 if (IsHugeFunc) {
1023 // Update FreshBBs to optimize the merged BB.
1024 FreshBBs.insert(SinglePred);
1025 FreshBBs.erase(DestBB);
1026 }
1027 return false;
1028 }
1029 }
1030
1031 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1032 // to handle the new incoming edges it is about to have.
1033 for (PHINode &PN : DestBB->phis()) {
1034 // Remove the incoming value for BB, and remember it.
1035 Value *InVal = PN.removeIncomingValue(BB, false);
1036
1037 // Two options: either the InVal is a phi node defined in BB or it is some
1038 // value that dominates BB.
1039 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
1040 if (InValPhi && InValPhi->getParent() == BB) {
1041 // Add all of the input values of the input PHI as inputs of this phi.
1042 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1043 PN.addIncoming(InValPhi->getIncomingValue(i),
1044 InValPhi->getIncomingBlock(i));
1045 } else {
1046 // Otherwise, add one instance of the dominating value for each edge that
1047 // we will be adding.
1048 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
1049 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1050 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
1051 } else {
1052 for (BasicBlock *Pred : predecessors(BB))
1053 PN.addIncoming(InVal, Pred);
1054 }
1055 }
1056 }
1057
1058 // Preserve loop Metadata.
1059 if (BI->hasMetadata(LLVMContext::MD_loop)) {
1060 for (auto *Pred : predecessors(BB))
1061 Pred->getTerminator()->copyMetadata(*BI, LLVMContext::MD_loop);
1062 }
1063
1064 // The PHIs are now updated, change everything that refers to BB to use
1065 // DestBB and remove BB.
1067 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1068 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1069 predecessors(DestBB));
1070 for (auto *Pred : predecessors(BB)) {
1071 if (!PredOfDestBB.contains(Pred)) {
1072 if (SeenPreds.insert(Pred).second)
1073 DTUpdates.push_back({DominatorTree::Insert, Pred, DestBB});
1074 }
1075 }
1076 SeenPreds.clear();
1077 for (auto *Pred : predecessors(BB)) {
1078 if (SeenPreds.insert(Pred).second)
1079 DTUpdates.push_back({DominatorTree::Delete, Pred, BB});
1080 }
1081 DTUpdates.push_back({DominatorTree::Delete, BB, DestBB});
1082 BB->replaceAllUsesWith(DestBB);
1083 DTU->applyUpdates(DTUpdates);
1084 DTU->deleteBB(BB);
1085 ++NumBlocksElim;
1086
1087 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1088 return true;
1089}
1090
1091// Computes a map of base pointer relocation instructions to corresponding
1092// derived pointer relocation instructions given a vector of all relocate calls
1094 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1096 &RelocateInstMap) {
1097 // Collect information in two maps: one primarily for locating the base object
1098 // while filling the second map; the second map is the final structure holding
1099 // a mapping between Base and corresponding Derived relocate calls
1101 for (auto *ThisRelocate : AllRelocateCalls) {
1102 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1103 ThisRelocate->getDerivedPtrIndex());
1104 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1105 }
1106 for (auto &Item : RelocateIdxMap) {
1107 std::pair<unsigned, unsigned> Key = Item.first;
1108 if (Key.first == Key.second)
1109 // Base relocation: nothing to insert
1110 continue;
1111
1112 GCRelocateInst *I = Item.second;
1113 auto BaseKey = std::make_pair(Key.first, Key.first);
1114
1115 // We're iterating over RelocateIdxMap so we cannot modify it.
1116 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1117 if (MaybeBase == RelocateIdxMap.end())
1118 // TODO: We might want to insert a new base object relocate and gep off
1119 // that, if there are enough derived object relocates.
1120 continue;
1121
1122 RelocateInstMap[MaybeBase->second].push_back(I);
1123 }
1124}
1125
1126// Accepts a GEP and extracts the operands into a vector provided they're all
1127// small integer constants
1129 SmallVectorImpl<Value *> &OffsetV) {
1130 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1131 // Only accept small constant integer operands
1132 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1133 if (!Op || Op->getZExtValue() > 20)
1134 return false;
1135 }
1136
1137 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1138 OffsetV.push_back(GEP->getOperand(i));
1139 return true;
1140}
1141
1142// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1143// replace, computes a replacement, and affects it.
1144static bool
1146 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1147 bool MadeChange = false;
1148 // We must ensure the relocation of derived pointer is defined after
1149 // relocation of base pointer. If we find a relocation corresponding to base
1150 // defined earlier than relocation of base then we move relocation of base
1151 // right before found relocation. We consider only relocation in the same
1152 // basic block as relocation of base. Relocations from other basic block will
1153 // be skipped by optimization and we do not care about them.
1154 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1155 &*R != RelocatedBase; ++R)
1156 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1157 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1158 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1159 RelocatedBase->moveBefore(RI->getIterator());
1160 MadeChange = true;
1161 break;
1162 }
1163
1164 for (GCRelocateInst *ToReplace : Targets) {
1165 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1166 "Not relocating a derived object of the original base object");
1167 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1168 // A duplicate relocate call. TODO: coalesce duplicates.
1169 continue;
1170 }
1171
1172 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1173 // Base and derived relocates are in different basic blocks.
1174 // In this case transform is only valid when base dominates derived
1175 // relocate. However it would be too expensive to check dominance
1176 // for each such relocate, so we skip the whole transformation.
1177 continue;
1178 }
1179
1180 Value *Base = ToReplace->getBasePtr();
1181 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1182 if (!Derived || Derived->getPointerOperand() != Base)
1183 continue;
1184
1186 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1187 continue;
1188
1189 // Create a Builder and replace the target callsite with a gep
1190 assert(RelocatedBase->getNextNode() &&
1191 "Should always have one since it's not a terminator");
1192
1193 // Insert after RelocatedBase
1194 IRBuilder<> Builder(RelocatedBase->getNextNode());
1195 Builder.disableGEPCanonicalization();
1196 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1197
1198 Value *Replacement = Builder.CreateGEP(Derived->getSourceElementType(),
1199 RelocatedBase, ArrayRef(OffsetV));
1200 Replacement->takeName(ToReplace);
1201 ToReplace->replaceAllUsesWith(Replacement);
1202 ToReplace->eraseFromParent();
1203
1204 MadeChange = true;
1205 }
1206 return MadeChange;
1207}
1208
1209// Turns this:
1210//
1211// %base = ...
1212// %ptr = gep %base + 15
1213// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1214// %base' = relocate(%tok, i32 4, i32 4)
1215// %ptr' = relocate(%tok, i32 4, i32 5)
1216// %val = load %ptr'
1217//
1218// into this:
1219//
1220// %base = ...
1221// %ptr = gep %base + 15
1222// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1223// %base' = gc.relocate(%tok, i32 4, i32 4)
1224// %ptr' = gep %base' + 15
1225// %val = load %ptr'
1226bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1227 bool MadeChange = false;
1228 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1229 for (auto *U : I.users())
1230 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1231 // Collect all the relocate calls associated with a statepoint
1232 AllRelocateCalls.push_back(Relocate);
1233
1234 // We need at least one base pointer relocation + one derived pointer
1235 // relocation to mangle
1236 if (AllRelocateCalls.size() < 2)
1237 return false;
1238
1239 // RelocateInstMap is a mapping from the base relocate instruction to the
1240 // corresponding derived relocate instructions
1241 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1242 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1243 if (RelocateInstMap.empty())
1244 return false;
1245
1246 for (auto &Item : RelocateInstMap)
1247 // Item.first is the RelocatedBase to offset against
1248 // Item.second is the vector of Targets to replace
1249 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1250 return MadeChange;
1251}
1252
1253/// Sink the specified cast instruction into its user blocks.
1254static bool SinkCast(CastInst *CI) {
1255 BasicBlock *DefBB = CI->getParent();
1256
1257 /// InsertedCasts - Only insert a cast in each block once.
1259
1260 bool MadeChange = false;
1261 for (Instruction::user_iterator UI = CI->user_begin(), E = CI->user_end();
1262 UI != E;) {
1263 Use &TheUse = UI.getUse();
1264 Instruction *User = *UI;
1265
1266 // Figure out which BB this cast is used in. For PHI's this is the
1267 // appropriate predecessor block.
1268 BasicBlock *UserBB = User->getParent();
1269 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1270 UserBB = PN->getIncomingBlock(TheUse);
1271 }
1272
1273 // Preincrement use iterator so we don't invalidate it.
1274 ++UI;
1275
1276 // The first insertion point of a block containing an EH pad is after the
1277 // pad. If the pad is the user, we cannot sink the cast past the pad.
1278 if (User->isEHPad())
1279 continue;
1280
1281 // If the block selected to receive the cast is an EH pad that does not
1282 // allow non-PHI instructions before the terminator, we can't sink the
1283 // cast.
1284 if (UserBB->getTerminator()->isEHPad())
1285 continue;
1286
1287 // If this user is in the same block as the cast, don't change the cast.
1288 if (UserBB == DefBB)
1289 continue;
1290
1291 // If we have already inserted a cast into this block, use it.
1292 CastInst *&InsertedCast = InsertedCasts[UserBB];
1293
1294 if (!InsertedCast) {
1295 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1296 assert(InsertPt != UserBB->end());
1297 InsertedCast = cast<CastInst>(CI->clone());
1298 InsertedCast->insertBefore(*UserBB, InsertPt);
1299 }
1300
1301 // Replace a use of the cast with a use of the new cast.
1302 TheUse = InsertedCast;
1303 MadeChange = true;
1304 ++NumCastUses;
1305 }
1306
1307 // If we removed all uses, nuke the cast.
1308 if (CI->use_empty()) {
1309 salvageDebugInfo(*CI);
1310 CI->eraseFromParent();
1311 MadeChange = true;
1312 }
1313
1314 return MadeChange;
1315}
1316
1317/// Hoists bitcasts to the source block to reduce register pressure
1319 const DataLayout &DL) {
1320 auto *SrcInst = dyn_cast<Instruction>(BCI->getOperand(0));
1321 if (!SrcInst || SrcInst->getParent() == BCI->getParent() ||
1322 SrcInst->isTerminator())
1323 return false;
1324
1325 Type *DestTy = BCI->getType();
1326 Type *SrcTy = SrcInst->getType();
1327 EVT SrcVT = TLI.getValueType(DL, SrcTy);
1328 EVT DestVT = TLI.getValueType(DL, DestTy);
1329
1330 // Bail out on scalable vectors and illegal destination types
1331 if (SrcVT.isScalableVector() || DestVT.isScalableVector())
1332 return false;
1333
1334 // Only hoist if it reduces physical register count
1335 if (TLI.getNumRegisters(BCI->getContext(), SrcVT) <=
1336 TLI.getNumRegisters(BCI->getContext(), DestVT))
1337 return false;
1338
1339 // Block large or cross-domain scalars to prevent spills and broken atomics.
1340 bool IsCrossDomain = DestTy->isFPOrFPVectorTy() != SrcTy->isFPOrFPVectorTy();
1341
1342 // A scalar is large if it requires more than one native register.
1343 unsigned NativeWidth = DL.getPointerSizeInBits();
1344 bool IsLargeScalar =
1345 !DestTy->isVectorTy() &&
1346 DL.getTypeSizeInBits(DestTy).getFixedValue() > NativeWidth;
1347
1348 if (IsCrossDomain || IsLargeScalar)
1349 return false;
1350
1351 // Hoist the bitcast
1352 BasicBlock *SrcBB = SrcInst->getParent();
1353 auto InsertPt = isa<PHINode>(SrcInst) ? SrcBB->getFirstInsertionPt()
1354 : std::next(SrcInst->getIterator());
1355 BCI->moveBefore(*SrcBB, InsertPt);
1356
1357 return true;
1358}
1359
1360/// If the specified cast instruction is a noop copy (e.g. it's casting from
1361/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1362/// reduce the number of virtual registers that must be created and coalesced.
1363///
1364/// Return true if any changes are made.
1366 const DataLayout &DL) {
1367 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1368 // than sinking only nop casts, but is helpful on some platforms.
1369 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1370 if (!TLI.isFreeAddrSpaceCast(DL, ASC->getSrcAddressSpace(),
1371 ASC->getDestAddressSpace()))
1372 return false;
1373 }
1374
1375 // If this is a noop copy,
1376 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1377 EVT DstVT = TLI.getValueType(DL, CI->getType());
1378
1379 // This is an fp<->int conversion?
1380 if (SrcVT.isInteger() != DstVT.isInteger())
1381 return false;
1382
1383 // If this is an extension, it will be a zero or sign extension, which
1384 // isn't a noop.
1385 if (SrcVT.bitsLT(DstVT))
1386 return false;
1387
1388 // If these values will be promoted, find out what they will be promoted
1389 // to. This helps us consider truncates on PPC as noop copies when they
1390 // are.
1391 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1393 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1394 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1396 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1397
1398 // If, after promotion, these are the same types, this is a noop copy.
1399 if (SrcVT != DstVT)
1400 return false;
1401
1402 return SinkCast(CI);
1403}
1404
1405// Match a simple increment by constant operation. Note that if a sub is
1406// matched, the step is negated (as if the step had been canonicalized to
1407// an add, even though we leave the instruction alone.)
1408static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1409 Constant *&Step) {
1410 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1412 m_Instruction(LHS), m_Constant(Step)))))
1413 return true;
1414 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1416 m_Instruction(LHS), m_Constant(Step))))) {
1417 Step = ConstantExpr::getNeg(Step);
1418 return true;
1419 }
1420 return false;
1421}
1422
1423/// If given \p PN is an inductive variable with value IVInc coming from the
1424/// backedge, and on each iteration it gets increased by Step, return pair
1425/// <IVInc, Step>. Otherwise, return std::nullopt.
1426static std::optional<std::pair<Instruction *, Constant *>>
1427getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1428 const Loop *L = LI->getLoopFor(PN->getParent());
1429 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1430 return std::nullopt;
1431 auto *IVInc =
1432 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1433 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1434 return std::nullopt;
1435 Instruction *LHS = nullptr;
1436 Constant *Step = nullptr;
1437 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1438 return std::make_pair(IVInc, Step);
1439 return std::nullopt;
1440}
1441
1442static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1443 auto *I = dyn_cast<Instruction>(V);
1444 if (!I)
1445 return false;
1446 Instruction *LHS = nullptr;
1447 Constant *Step = nullptr;
1448 if (!matchIncrement(I, LHS, Step))
1449 return false;
1450 if (auto *PN = dyn_cast<PHINode>(LHS))
1451 if (auto IVInc = getIVIncrement(PN, LI))
1452 return IVInc->first == I;
1453 return false;
1454}
1455
1456bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1457 Value *Arg0, Value *Arg1,
1458 CmpInst *Cmp,
1459 Intrinsic::ID IID) {
1460 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1461 if (!isIVIncrement(BO, LI))
1462 return false;
1463 const Loop *L = LI->getLoopFor(BO->getParent());
1464 assert(L && "L should not be null after isIVIncrement()");
1465 // Do not risk on moving increment into a child loop.
1466 if (LI->getLoopFor(Cmp->getParent()) != L)
1467 return false;
1468
1469 // Finally, we need to ensure that the insert point will dominate all
1470 // existing uses of the increment.
1471
1472 auto &DT = getDT();
1473 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1474 // If we're moving up the dom tree, all uses are trivially dominated.
1475 // (This is the common case for code produced by LSR.)
1476 return true;
1477
1478 // Otherwise, special case the single use in the phi recurrence.
1479 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1480 };
1481 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1482 // We used to use a dominator tree here to allow multi-block optimization.
1483 // But that was problematic because:
1484 // 1. It could cause a perf regression by hoisting the math op into the
1485 // critical path.
1486 // 2. It could cause a perf regression by creating a value that was live
1487 // across multiple blocks and increasing register pressure.
1488 // 3. Use of a dominator tree could cause large compile-time regression.
1489 // This is because we recompute the DT on every change in the main CGP
1490 // run-loop. The recomputing is probably unnecessary in many cases, so if
1491 // that was fixed, using a DT here would be ok.
1492 //
1493 // There is one important particular case we still want to handle: if BO is
1494 // the IV increment. Important properties that make it profitable:
1495 // - We can speculate IV increment anywhere in the loop (as long as the
1496 // indvar Phi is its only user);
1497 // - Upon computing Cmp, we effectively compute something equivalent to the
1498 // IV increment (despite it loops differently in the IR). So moving it up
1499 // to the cmp point does not really increase register pressure.
1500 return false;
1501 }
1502
1503 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1504 if (BO->getOpcode() == Instruction::Add &&
1505 IID == Intrinsic::usub_with_overflow) {
1506 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1508 }
1509
1510 // Insert at the first instruction of the pair.
1511 Instruction *InsertPt = nullptr;
1512 for (Instruction &Iter : *Cmp->getParent()) {
1513 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1514 // the overflow intrinsic are defined.
1515 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1516 InsertPt = &Iter;
1517 break;
1518 }
1519 }
1520 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1521
1522 IRBuilder<> Builder(InsertPt);
1523 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1524 if (BO->getOpcode() != Instruction::Xor) {
1525 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1526 replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
1527 } else
1528 assert(BO->hasOneUse() &&
1529 "Patterns with XOr should use the BO only in the compare");
1530 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1531 replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
1532 Cmp->eraseFromParent();
1533 BO->eraseFromParent();
1534 return true;
1535}
1536
1537/// Match special-case patterns that check for unsigned add overflow.
1539 BinaryOperator *&Add) {
1540 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1541 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1542 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1543
1544 // We are not expecting non-canonical/degenerate code. Just bail out.
1545 if (isa<Constant>(A))
1546 return false;
1547
1548 ICmpInst::Predicate Pred = Cmp->getPredicate();
1549 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1550 B = ConstantInt::get(B->getType(), 1);
1551 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1552 B = Constant::getAllOnesValue(B->getType());
1553 else
1554 return false;
1555
1556 // Check the users of the variable operand of the compare looking for an add
1557 // with the adjusted constant.
1558 for (User *U : A->users()) {
1559 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1561 return true;
1562 }
1563 }
1564 return false;
1565}
1566
1567/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1568/// intrinsic. Return true if any changes were made.
1569bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1570 ModifyDT &ModifiedDT) {
1571 bool EdgeCase = false;
1572 Value *A, *B;
1573 BinaryOperator *Add;
1574 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1576 return false;
1577 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1578 A = Add->getOperand(0);
1579 B = Add->getOperand(1);
1580 EdgeCase = true;
1581 }
1582
1584 TLI->getValueType(*DL, Add->getType()),
1585 Add->hasNUsesOrMore(EdgeCase ? 1 : 2)))
1586 return false;
1587
1588 // We don't want to move around uses of condition values this late, so we
1589 // check if it is legal to create the call to the intrinsic in the basic
1590 // block containing the icmp.
1591 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1592 return false;
1593
1594 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1595 Intrinsic::uadd_with_overflow))
1596 return false;
1597
1598 // Reset callers - do not crash by iterating over a dead instruction.
1599 ModifiedDT = ModifyDT::ModifyInstDT;
1600 return true;
1601}
1602
1603bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1604 ModifyDT &ModifiedDT) {
1605 // We are not expecting non-canonical/degenerate code. Just bail out.
1606 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1607 if (isa<Constant>(A) && isa<Constant>(B))
1608 return false;
1609
1610 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1611 ICmpInst::Predicate Pred = Cmp->getPredicate();
1612 if (Pred == ICmpInst::ICMP_UGT) {
1613 std::swap(A, B);
1614 Pred = ICmpInst::ICMP_ULT;
1615 }
1616 // Convert special-case: (A == 0) is the same as (A u< 1).
1617 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1618 B = ConstantInt::get(B->getType(), 1);
1619 Pred = ICmpInst::ICMP_ULT;
1620 }
1621 // Convert special-case: (A != 0) is the same as (0 u< A).
1622 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1623 std::swap(A, B);
1624 Pred = ICmpInst::ICMP_ULT;
1625 }
1626 if (Pred != ICmpInst::ICMP_ULT)
1627 return false;
1628
1629 // Walk the users of a variable operand of a compare looking for a subtract or
1630 // add with that same operand. Also match the 2nd operand of the compare to
1631 // the add/sub, but that may be a negated constant operand of an add.
1632 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1633 BinaryOperator *Sub = nullptr;
1634 for (User *U : CmpVariableOperand->users()) {
1635 // A - B, A u< B --> usubo(A, B)
1636 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1638 break;
1639 }
1640
1641 // A + (-C), A u< C (canonicalized form of (sub A, C))
1642 const APInt *CmpC, *AddC;
1643 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1644 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1646 break;
1647 }
1648 }
1649 if (!Sub)
1650 return false;
1651
1653 TLI->getValueType(*DL, Sub->getType()),
1654 Sub->hasNUsesOrMore(1)))
1655 return false;
1656
1657 // We don't want to move around uses of condition values this late, so we
1658 // check if it is legal to create the call to the intrinsic in the basic
1659 // block containing the icmp.
1660 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1661 return false;
1662
1663 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1664 Cmp, Intrinsic::usub_with_overflow))
1665 return false;
1666
1667 // Reset callers - do not crash by iterating over a dead instruction.
1668 ModifiedDT = ModifyDT::ModifyInstDT;
1669 return true;
1670}
1671
1672// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1673// The same transformation exists in DAG combiner, but we repeat it here because
1674// DAG builder can break the pattern by moving icmp into a successor block.
1675bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1676 CmpPredicate Pred;
1677 Value *X;
1678 const APInt *C;
1679
1680 // (icmp (ctpop x), c)
1682 return false;
1683
1684 // We're only interested in "is power of 2 [or zero]" patterns.
1685 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(Pred) && *C == 1;
1686 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1687 (Pred == CmpInst::ICMP_UGT && *C == 1);
1688 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1689 return false;
1690
1691 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1692 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1693 // and otherwise expand ctpop into a few simple instructions.
1694 Type *OpTy = X->getType();
1695 if (TLI->isCtpopFast(TLI->getValueType(*DL, OpTy))) {
1696 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1697 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(Cmp->getOperand(0), *DL))
1698 return false;
1699
1700 // ctpop(x) == 1 -> ctpop(x) u< 2
1701 // ctpop(x) != 1 -> ctpop(x) u> 1
1702 if (Pred == ICmpInst::ICMP_EQ) {
1703 Cmp->setOperand(1, ConstantInt::get(OpTy, 2));
1704 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1705 } else {
1706 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1707 }
1708 return true;
1709 }
1710
1711 Value *NewCmp;
1712 if (IsPowerOf2OrZeroTest ||
1713 (IsStrictlyPowerOf2Test && isKnownNonZero(Cmp->getOperand(0), *DL))) {
1714 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1715 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1716 IRBuilder<> Builder(Cmp);
1717 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1718 Value *And = Builder.CreateAnd(X, Sub);
1719 CmpInst::Predicate NewPred =
1722 : CmpInst::ICMP_NE;
1723 NewCmp = Builder.CreateICmp(NewPred, And, ConstantInt::getNullValue(OpTy));
1724 } else {
1725 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1726 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1727 IRBuilder<> Builder(Cmp);
1728 Value *Sub = Builder.CreateAdd(X, Constant::getAllOnesValue(OpTy));
1729 Value *Xor = Builder.CreateXor(X, Sub);
1730 CmpInst::Predicate NewPred =
1732 NewCmp = Builder.CreateICmp(NewPred, Xor, Sub);
1733 }
1734
1735 Cmp->replaceAllUsesWith(NewCmp);
1737 return true;
1738}
1739
1740/// Sink the given CmpInst into user blocks to reduce the number of virtual
1741/// registers that must be created and coalesced. This is a clear win except on
1742/// targets with multiple condition code registers (PowerPC), where it might
1743/// lose; some adjustment may be wanted there.
1744///
1745/// Return true if any changes are made.
1747 const DataLayout &DL) {
1748 if (TLI.hasMultipleConditionRegisters(EVT::getEVT(Cmp->getType())))
1749 return false;
1750
1751 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1752 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1753 return false;
1754
1755 bool UsedInPhiOrCurrentBlock = any_of(Cmp->users(), [Cmp](User *U) {
1756 return isa<PHINode>(U) ||
1757 cast<Instruction>(U)->getParent() == Cmp->getParent();
1758 });
1759
1760 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1761 // another BB.
1762 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(0)->getType()->isIntegerTy() &&
1763 Cmp->getOperand(0)->getType()->getScalarSizeInBits() >
1764 DL.getLargestLegalIntTypeSizeInBits())
1765 return false;
1766
1767 // Only insert a cmp in each block once.
1769
1770 bool MadeChange = false;
1771 for (Instruction::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1772 UI != E;) {
1773 Use &TheUse = UI.getUse();
1774 Instruction *User = *UI;
1775
1776 // Preincrement use iterator so we don't invalidate it.
1777 ++UI;
1778
1779 // Don't bother for PHI nodes.
1780 if (isa<PHINode>(User))
1781 continue;
1782
1783 // Figure out which BB this cmp is used in.
1784 BasicBlock *UserBB = User->getParent();
1785 BasicBlock *DefBB = Cmp->getParent();
1786
1787 // If this user is in the same block as the cmp, don't change the cmp.
1788 if (UserBB == DefBB)
1789 continue;
1790
1791 // If we have already inserted a cmp into this block, use it.
1792 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1793
1794 if (!InsertedCmp) {
1795 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1796 assert(InsertPt != UserBB->end());
1797 InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1798 Cmp->getOperand(0), Cmp->getOperand(1), "");
1799 InsertedCmp->insertBefore(*UserBB, InsertPt);
1800 // Propagate the debug info.
1801 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1802 }
1803
1804 // Replace a use of the cmp with a use of the new cmp.
1805 TheUse = InsertedCmp;
1806 MadeChange = true;
1807 ++NumCmpUses;
1808 }
1809
1810 // If we removed all uses, nuke the cmp.
1811 if (Cmp->use_empty()) {
1812 Cmp->eraseFromParent();
1813 MadeChange = true;
1814 }
1815
1816 return MadeChange;
1817}
1818
1819/// For pattern like:
1820///
1821/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1822/// ...
1823/// DomBB:
1824/// ...
1825/// br DomCond, TrueBB, CmpBB
1826/// CmpBB: (with DomBB being the single predecessor)
1827/// ...
1828/// Cmp = icmp eq CmpOp0, CmpOp1
1829/// ...
1830///
1831/// It would use two comparison on targets that lowering of icmp sgt/slt is
1832/// different from lowering of icmp eq (PowerPC). This function try to convert
1833/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1834/// After that, DomCond and Cmp can use the same comparison so reduce one
1835/// comparison.
1836///
1837/// Return true if any changes are made.
1839 bool EnableICmpEqToICmpSt) {
1840 if (!EnableICmpEqToICmpSt && TLI.isEqualityCmpFoldedWithSignedCmp())
1841 return false;
1842
1843 ICmpInst::Predicate Pred = Cmp->getPredicate();
1844 if (Pred != ICmpInst::ICMP_EQ)
1845 return false;
1846
1847 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
1848 // icmp slt/sgt would introduce more redundant LLVM IR.
1849 for (User *U : Cmp->users()) {
1850 if (isa<CondBrInst>(U))
1851 continue;
1852 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1853 continue;
1854 return false;
1855 }
1856
1857 // This is a cheap/incomplete check for dominance - just match a single
1858 // predecessor with a conditional branch.
1859 BasicBlock *CmpBB = Cmp->getParent();
1860 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1861 if (!DomBB)
1862 return false;
1863
1864 // We want to ensure that the only way control gets to the comparison of
1865 // interest is that a less/greater than comparison on the same operands is
1866 // false.
1867 Value *DomCond;
1868 BasicBlock *TrueBB, *FalseBB;
1869 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1870 return false;
1871 if (CmpBB != FalseBB)
1872 return false;
1873
1874 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1875 CmpPredicate DomPred;
1876 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1877 return false;
1878 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1879 return false;
1880
1881 // Convert the equality comparison to the opposite of the dominating
1882 // comparison and swap the direction for all branch/select users.
1883 // We have conceptually converted:
1884 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1885 // to
1886 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1887 // And similarly for branches.
1888 for (User *U : Cmp->users()) {
1889 if (auto *BI = dyn_cast<CondBrInst>(U)) {
1890 BI->swapSuccessors();
1891 continue;
1892 }
1893 if (auto *SI = dyn_cast<SelectInst>(U)) {
1894 // Swap operands
1895 SI->swapValues();
1896 SI->swapProfMetadata();
1897 continue;
1898 }
1899 llvm_unreachable("Must be a branch or a select");
1900 }
1901 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1902 return true;
1903}
1904
1905/// Many architectures use the same instruction for both subtract and cmp. Try
1906/// to swap cmp operands to match subtract operations to allow for CSE.
1908 Value *Op0 = Cmp->getOperand(0);
1909 Value *Op1 = Cmp->getOperand(1);
1910 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Op0) ||
1911 isa<Constant>(Op1) || Op0 == Op1)
1912 return false;
1913
1914 // If a subtract already has the same operands as a compare, swapping would be
1915 // bad. If a subtract has the same operands as a compare but in reverse order,
1916 // then swapping is good.
1917 int GoodToSwap = 0;
1918 unsigned NumInspected = 0;
1919 for (const User *U : Op0->users()) {
1920 // Avoid walking many users.
1921 if (++NumInspected > 128)
1922 return false;
1923 if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
1924 GoodToSwap++;
1925 else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
1926 GoodToSwap--;
1927 }
1928
1929 if (GoodToSwap > 0) {
1930 Cmp->swapOperands();
1931 return true;
1932 }
1933 return false;
1934}
1935
1937 const DataLayout &DL) {
1938 FCmpInst *FCmp = dyn_cast<FCmpInst>(Cmp);
1939 if (!FCmp)
1940 return false;
1941
1942 // Don't fold if the target offers free fabs and the predicate is legal.
1943 EVT VT = TLI.getValueType(DL, Cmp->getOperand(0)->getType());
1944 if (TLI.isFAbsFree(VT) &&
1945 TLI.isCondCodeLegal(getFCmpCondCode(FCmp->getPredicate()),
1946 VT.getSimpleVT()))
1947 return false;
1948
1949 // Reverse the canonicalization if it is a FP class test
1950 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
1951 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
1952 };
1953 auto [ClassVal, ClassTest] =
1954 fcmpToClassTest(FCmp->getPredicate(), *FCmp->getParent()->getParent(),
1955 FCmp->getOperand(0), FCmp->getOperand(1));
1956 if (!ClassVal)
1957 return false;
1958
1959 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
1960 return false;
1961
1962 IRBuilder<> Builder(Cmp);
1963 Value *IsFPClass = Builder.createIsFPClass(ClassVal, ClassTest);
1964 Cmp->replaceAllUsesWith(IsFPClass);
1966 return true;
1967}
1968
1970 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
1971 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut, Constant *&StepOut) {
1972 Value *Incr, *RemAmt;
1973 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
1974 if (!match(Rem, m_URem(m_Value(Incr), m_Value(RemAmt))))
1975 return false;
1976
1977 Value *AddInst, *AddOffset;
1978 // Find out loop increment PHI.
1979 PHINode *PN = dyn_cast<PHINode>(Incr);
1980 if (PN != nullptr) {
1981 AddInst = nullptr;
1982 AddOffset = nullptr;
1983 } else {
1984 // Search through a NUW add (or disjoint or) on top of the loop increment.
1985 if (!match(Incr, m_c_NUWAddLike(m_Phi(PN), m_Value(AddOffset))))
1986 return false;
1987 AddInst = Incr;
1988 }
1989
1990 if (!PN)
1991 return false;
1992
1993 // This isn't strictly necessary, what we really need is one increment and any
1994 // amount of initial values all being the same.
1995 if (PN->getNumIncomingValues() != 2)
1996 return false;
1997
1998 // Only trivially analyzable loops.
1999 Loop *L = LI->getLoopFor(PN->getParent());
2000 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2001 return false;
2002
2003 // Req that the remainder is in the loop
2004 if (!L->contains(Rem))
2005 return false;
2006
2007 // Only works if the remainder amount is a loop invaraint
2008 if (!L->isLoopInvariant(RemAmt))
2009 return false;
2010
2011 // Only works if the AddOffset is a loop invaraint
2012 if (AddOffset && !L->isLoopInvariant(AddOffset))
2013 return false;
2014
2015 // Is the PHI a loop increment?
2016 auto LoopIncrInfo = getIVIncrement(PN, LI);
2017 if (!LoopIncrInfo)
2018 return false;
2019
2020 // The remainder must wrap at most once per iteration. That needs a known
2021 // remainder amount unless the step is one.
2022 Constant *Step = LoopIncrInfo->second;
2023 if (!match(Step, m_One())) {
2024 auto *StepC = dyn_cast<ConstantInt>(Step);
2025 auto *RemC = dyn_cast<ConstantInt>(RemAmt);
2026 if (!StepC || !RemC || StepC->isZero() ||
2027 StepC->getValue().uge(RemC->getValue()))
2028 return false;
2029 // `rem + Step` must not overflow.
2030 bool Overflow;
2031 (void)(RemC->getValue() - 1).uadd_ov(StepC->getValue(), Overflow);
2032 if (Overflow)
2033 return false;
2034 }
2035
2036 // Need the increment to not overflow.
2037 if (!match(LoopIncrInfo->first, m_c_NUWAdd(m_Specific(PN), m_Value())))
2038 return false;
2039
2040 // Set output variables.
2041 RemAmtOut = RemAmt;
2042 LoopIncrPNOut = PN;
2043 AddInstOut = AddInst;
2044 AddOffsetOut = AddOffset;
2045 StepOut = Step;
2046
2047 return true;
2048}
2049
2050// Try to transform:
2051//
2052// for(i = Start; i < End; i += Step)
2053// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2054//
2055// ->
2056//
2057// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2058// for(i = Start; i < End; i += Step, rem += Step)
2059// Rem = rem u>= RemAmtLoopInvariant ? rem - RemAmtLoopInvariant : rem;
2060//
2061// Step must be 1 unless RemAmtLoopInvariant is a constant greater than Step.
2063 const LoopInfo *LI, DominatorTree &DT,
2065 bool IsHuge) {
2066 Value *AddOffset, *RemAmt, *AddInst;
2067 PHINode *LoopIncrPN;
2068 Constant *Step;
2069 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmt, AddInst,
2070 AddOffset, LoopIncrPN, Step))
2071 return false;
2072
2073 Loop *L = LI->getLoopFor(LoopIncrPN->getParent());
2074 Type *Ty = Rem->getType();
2075
2076 // `urem` of a constant ends up as `mul` + `shift` + `sub`, so the extra IV
2077 // is only worth it if the `urem` runs every iteration.
2078 //
2079 // Potential TODO: Should we have a check for how "nested" a non-constant
2080 // remainder operation is? The new code runs every iteration so if the
2081 // remainder is guarded behind unlikely conditions this might not be worth
2082 // it.
2083 bool IsConstRem = isa<ConstantInt>(RemAmt);
2084 if (match(RemAmt, m_ImmConstant())) {
2085 // A power-of-2 `urem` is a single mask.
2086 if (!IsConstRem || cast<ConstantInt>(RemAmt)->getValue().isPowerOf2() ||
2087 !DT.dominates(Rem->getParent(), L->getLoopLatch()))
2088 return false;
2089 }
2090
2091 Value *Start = LoopIncrPN->getIncomingValueForBlock(L->getLoopPreheader());
2092 // If we have add create initial value for remainder.
2093 // The logic here is:
2094 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2095 //
2096 // For a non-constant remainder amount, only proceed if the expression
2097 // simplifies (otherwise we can't fully optimize out the urem). A constant
2098 // one is cheap enough to compute once in the preheader.
2099 IRBuilder<> PHBuilder(L->getLoopPreheader()->getTerminator());
2100 if (AddInst) {
2101 assert(AddOffset && "We found an add but missing values");
2102 // Without dom-condition/assumption cache we aren't likely to get much out
2103 // of a context instruction.
2104 Value *NewStart = simplifyAddInst(
2105 Start, AddOffset, match(AddInst, m_NSWAdd(m_Value(), m_Value())),
2106 /*IsNUW=*/true, *DL);
2107 if (!NewStart && !IsConstRem)
2108 return false;
2109 Start = NewStart ? NewStart : PHBuilder.CreateNUWAdd(Start, AddOffset);
2110 }
2111
2112 Value *StartRem = simplifyURemInst(Start, RemAmt, *DL);
2113 if (!StartRem) {
2114 // If we can't fully optimize out the `rem`, skip this transform.
2115 if (!IsConstRem)
2116 return false;
2117 StartRem = PHBuilder.CreateURem(Start, RemAmt);
2118 }
2119
2120 // Create new remainder with induction variable.
2121 IRBuilder<> Builder(LoopIncrPN);
2122 PHINode *NewRem = Builder.CreatePHI(Ty, 2);
2123
2124 Builder.SetInsertPoint(cast<Instruction>(
2125 LoopIncrPN->getIncomingValueForBlock(L->getLoopLatch())));
2126 // `(add (urem x, y), Step)` is nuw, see
2127 // isRemOfLoopIncrementWithLoopInvariant.
2128 Value *RemAdd = Builder.CreateNUWAdd(NewRem, Step);
2129 Value *RemSel;
2130 if (match(Step, m_One())) {
2131 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, RemAdd, RemAmt);
2132 RemSel = Builder.CreateSelect(RemCmp, Constant::getNullValue(Ty), RemAdd);
2133 } else {
2134 Value *RemCmp = Builder.CreateICmp(ICmpInst::ICMP_UGE, RemAdd, RemAmt);
2135 Value *RemSub = Builder.CreateNUWSub(RemAdd, RemAmt);
2136 RemSel = Builder.CreateSelect(RemCmp, RemSub, RemAdd);
2137 }
2138 if (auto *SI = dyn_cast<SelectInst>(RemSel))
2140
2141 NewRem->addIncoming(StartRem, L->getLoopPreheader());
2142 NewRem->addIncoming(RemSel, L->getLoopLatch());
2143
2144 // Insert all touched BBs.
2145 FreshBBs.insert(L->getLoopPreheader());
2146 FreshBBs.insert(LoopIncrPN->getParent());
2147 FreshBBs.insert(L->getLoopLatch());
2148 FreshBBs.insert(Rem->getParent());
2149 if (AddInst)
2150 FreshBBs.insert(cast<Instruction>(AddInst)->getParent());
2151 replaceAllUsesWith(Rem, NewRem, FreshBBs, IsHuge);
2152 Rem->eraseFromParent();
2153 if (AddInst && AddInst->use_empty())
2154 cast<Instruction>(AddInst)->eraseFromParent();
2155 return true;
2156}
2157
2158bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2159 if (foldURemOfLoopIncrement(Rem, DL, LI, getDT(), FreshBBs, IsHugeFunc))
2160 return true;
2161 return false;
2162}
2163
2164bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2165 if (sinkCmpExpression(Cmp, *TLI, *DL))
2166 return true;
2167
2168 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2169 return true;
2170
2171 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2172 return true;
2173
2174 if (unfoldPowerOf2Test(Cmp))
2175 return true;
2176
2177 if (foldICmpWithDominatingICmp(Cmp, *TLI, Opts.cgp_icmp_eq2icmp_st))
2178 return true;
2179
2181 return true;
2182
2183 if (foldFCmpToFPClassTest(Cmp, *TLI, *DL))
2184 return true;
2185
2186 return false;
2187}
2188
2189/// Duplicate and sink the given 'and' instruction into user blocks where it is
2190/// used in a compare to allow isel to generate better code for targets where
2191/// this operation can be combined.
2192///
2193/// Return true if any changes are made.
2195 SetOfInstrs &InsertedInsts) {
2196 // Double-check that we're not trying to optimize an instruction that was
2197 // already optimized by some other part of this pass.
2198 assert(!InsertedInsts.count(AndI) &&
2199 "Attempting to optimize already optimized and instruction");
2200 (void)InsertedInsts;
2201
2202 // Nothing to do for single use in same basic block.
2203 if (AndI->hasOneUse() &&
2204 AndI->getParent() == (*AndI->user_begin())->getParent())
2205 return false;
2206
2207 // Try to avoid cases where sinking/duplicating is likely to increase register
2208 // pressure.
2209 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
2210 !isa<ConstantInt>(AndI->getOperand(1)) &&
2211 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
2212 return false;
2213
2214 for (Instruction *User : AndI->users()) {
2215 // Only sink 'and' feeding icmp with 0.
2216 if (!isa<ICmpInst>(User))
2217 return false;
2218
2219 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
2220 if (!CmpC || !CmpC->isZero())
2221 return false;
2222 }
2223
2224 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
2225 return false;
2226
2227 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2228 LLVM_DEBUG(AndI->getParent()->dump());
2229
2230 // Push the 'and' into the same block as the icmp 0. There should only be
2231 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2232 // others, so we don't need to keep track of which BBs we insert into.
2233 for (Instruction::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2234 UI != E;) {
2235 Use &TheUse = UI.getUse();
2236 Instruction *User = *UI;
2237
2238 // Preincrement use iterator so we don't invalidate it.
2239 ++UI;
2240
2241 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2242
2243 // Keep the 'and' in the same place if the use is already in the same block.
2244 Instruction *InsertPt =
2245 User->getParent() == AndI->getParent() ? AndI : User;
2246 Instruction *InsertedAnd = BinaryOperator::Create(
2247 Instruction::And, AndI->getOperand(0), AndI->getOperand(1), "",
2248 InsertPt->getIterator());
2249 // Propagate the debug info.
2250 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2251
2252 // Replace a use of the 'and' with a use of the new 'and'.
2253 TheUse = InsertedAnd;
2254 ++NumAndUses;
2255 LLVM_DEBUG(User->getParent()->dump());
2256 }
2257
2258 // We removed all uses, nuke the and.
2259 AndI->eraseFromParent();
2260 return true;
2261}
2262
2263/// Check if the candidates could be combined with a shift instruction, which
2264/// includes:
2265/// 1. Truncate instruction
2266/// 2. And instruction and the imm is a mask of the low bits:
2267/// imm & (imm+1) == 0
2269 if (!isa<TruncInst>(User)) {
2270 if (User->getOpcode() != Instruction::And ||
2272 return false;
2273
2274 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
2275
2276 if ((Cimm & (Cimm + 1)).getBoolValue())
2277 return false;
2278 }
2279 return true;
2280}
2281
2282/// Sink both shift and truncate instruction to the use of truncate's BB.
2283static bool
2286 const TargetLowering &TLI, const DataLayout &DL) {
2287 BasicBlock *UserBB = User->getParent();
2289 auto *TruncI = cast<TruncInst>(User);
2290 bool MadeChange = false;
2291
2292 for (Instruction::user_iterator TruncUI = TruncI->user_begin(),
2293 TruncE = TruncI->user_end();
2294 TruncUI != TruncE;) {
2295
2296 Use &TruncTheUse = TruncUI.getUse();
2297 Instruction *TruncUser = *TruncUI;
2298 // Preincrement use iterator so we don't invalidate it.
2299
2300 ++TruncUI;
2301
2302 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
2303 if (!ISDOpcode)
2304 continue;
2305
2306 // If the use is actually a legal node, there will not be an
2307 // implicit truncate.
2308 // FIXME: always querying the result type is just an
2309 // approximation; some nodes' legality is determined by the
2310 // operand or other means. There's no good way to find out though.
2311 if (TLI.isOperationLegalOrCustom(
2312 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
2313 continue;
2314
2315 // Don't bother for PHI nodes.
2316 if (isa<PHINode>(TruncUser))
2317 continue;
2318
2319 BasicBlock *TruncUserBB = TruncUser->getParent();
2320
2321 if (UserBB == TruncUserBB)
2322 continue;
2323
2324 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2325 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2326
2327 if (!InsertedShift && !InsertedTrunc) {
2328 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2329 assert(InsertPt != TruncUserBB->end());
2330 // Sink the shift
2331 if (ShiftI->getOpcode() == Instruction::AShr)
2332 InsertedShift =
2333 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2334 else
2335 InsertedShift =
2336 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2337 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2338 InsertedShift->insertBefore(*TruncUserBB, InsertPt);
2339
2340 // Sink the trunc
2341 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2342 TruncInsertPt++;
2343 // It will go ahead of any debug-info.
2344 TruncInsertPt.setHeadBit(true);
2345 assert(TruncInsertPt != TruncUserBB->end());
2346
2347 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
2348 TruncI->getType(), "");
2349 InsertedTrunc->insertBefore(*TruncUserBB, TruncInsertPt);
2350 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2351
2352 MadeChange = true;
2353
2354 TruncTheUse = InsertedTrunc;
2355 }
2356 }
2357 return MadeChange;
2358}
2359
2360/// Sink the shift *right* instruction into user blocks if the uses could
2361/// potentially be combined with this shift instruction and generate BitExtract
2362/// instruction. It will only be applied if the architecture supports BitExtract
2363/// instruction. Here is an example:
2364/// BB1:
2365/// %x.extract.shift = lshr i64 %arg1, 32
2366/// BB2:
2367/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2368/// ==>
2369///
2370/// BB2:
2371/// %x.extract.shift.1 = lshr i64 %arg1, 32
2372/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2373///
2374/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2375/// instruction.
2376/// Return true if any changes are made.
2378 const TargetLowering &TLI,
2379 const DataLayout &DL) {
2380 BasicBlock *DefBB = ShiftI->getParent();
2381
2382 /// Only insert instructions in each block once.
2384
2385 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
2386
2387 bool MadeChange = false;
2388 for (Instruction::user_iterator UI = ShiftI->user_begin(),
2389 E = ShiftI->user_end();
2390 UI != E;) {
2391 Use &TheUse = UI.getUse();
2392 Instruction *User = *UI;
2393 // Preincrement use iterator so we don't invalidate it.
2394 ++UI;
2395
2396 // Don't bother for PHI nodes.
2397 if (isa<PHINode>(User))
2398 continue;
2399
2401 continue;
2402
2403 BasicBlock *UserBB = User->getParent();
2404
2405 if (UserBB == DefBB) {
2406 // If the shift and truncate instruction are in the same BB. The use of
2407 // the truncate(TruncUse) may still introduce another truncate if not
2408 // legal. In this case, we would like to sink both shift and truncate
2409 // instruction to the BB of TruncUse.
2410 // for example:
2411 // BB1:
2412 // i64 shift.result = lshr i64 opnd, imm
2413 // trunc.result = trunc shift.result to i16
2414 //
2415 // BB2:
2416 // ----> We will have an implicit truncate here if the architecture does
2417 // not have i16 compare.
2418 // cmp i16 trunc.result, opnd2
2419 //
2420 if (isa<TruncInst>(User) &&
2421 shiftIsLegal
2422 // If the type of the truncate is legal, no truncate will be
2423 // introduced in other basic blocks.
2424 && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
2425 MadeChange =
2426 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2427
2428 continue;
2429 }
2430 // If we have already inserted a shift into this block, use it.
2431 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2432
2433 if (!InsertedShift) {
2434 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2435 assert(InsertPt != UserBB->end());
2436
2437 if (ShiftI->getOpcode() == Instruction::AShr)
2438 InsertedShift =
2439 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "");
2440 else
2441 InsertedShift =
2442 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "");
2443 InsertedShift->insertBefore(*UserBB, InsertPt);
2444 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2445
2446 MadeChange = true;
2447 }
2448
2449 // Replace a use of the shift with a use of the new shift.
2450 TheUse = InsertedShift;
2451 }
2452
2453 // If we removed all uses, or there are none, nuke the shift.
2454 if (ShiftI->use_empty()) {
2455 salvageDebugInfo(*ShiftI);
2456 ShiftI->eraseFromParent();
2457 MadeChange = true;
2458 }
2459
2460 return MadeChange;
2461}
2462
2463/// If counting leading or trailing zeros is an expensive operation and a zero
2464/// input is defined, add a check for zero to avoid calling the intrinsic.
2465///
2466/// We want to transform:
2467/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2468///
2469/// into:
2470/// entry:
2471/// %cmpz = icmp eq i64 %A, 0
2472/// br i1 %cmpz, label %cond.end, label %cond.false
2473/// cond.false:
2474/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2475/// br label %cond.end
2476/// cond.end:
2477/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2478///
2479/// If the transform is performed, return true and set ModifiedDT to true.
2480static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2481 DomTreeUpdater *DTU, LoopInfo *LI,
2482 const TargetLowering *TLI,
2483 const DataLayout *DL, ModifyDT &ModifiedDT,
2485 bool IsHugeFunc) {
2486 // If a zero input is undefined, it doesn't make sense to despeculate that.
2487 if (match(CountZeros->getOperand(1), m_One()))
2488 return false;
2489
2490 // If it's cheap to speculate, there's nothing to do.
2491 Type *Ty = CountZeros->getType();
2492 auto IntrinsicID = CountZeros->getIntrinsicID();
2493 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2494 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2495 return false;
2496
2497 // Only handle scalar cases. Anything else requires too much work.
2498 unsigned SizeInBits = Ty->getScalarSizeInBits();
2499 if (Ty->isVectorTy())
2500 return false;
2501
2502 // Bail if the value is never zero.
2503 Use &Op = CountZeros->getOperandUse(0);
2504 if (isKnownNonZero(Op, *DL))
2505 return false;
2506
2507 // The intrinsic will be sunk behind a compare against zero and branch.
2508 BasicBlock *StartBlock = CountZeros->getParent();
2509 BasicBlock *CallBlock = SplitBlock(StartBlock, CountZeros, DTU, LI,
2510 /* MSSAU */ nullptr, "cond.false");
2511 if (IsHugeFunc)
2512 FreshBBs.insert(CallBlock);
2513
2514 // Create another block after the count zero intrinsic. A PHI will be added
2515 // in this block to select the result of the intrinsic or the bit-width
2516 // constant if the input to the intrinsic is zero.
2517 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(CountZeros));
2518 // Any debug-info after CountZeros should not be included.
2519 SplitPt.setHeadBit(true);
2520 BasicBlock *EndBlock = SplitBlock(CallBlock, &*SplitPt, DTU, LI,
2521 /* MSSAU */ nullptr, "cond.end");
2522 if (IsHugeFunc)
2523 FreshBBs.insert(EndBlock);
2524
2525 // Set up a builder to create a compare, conditional branch, and PHI.
2526 IRBuilder<> Builder(StartBlock->getTerminator());
2527 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2528
2529 // Replace the unconditional branch that was created by the first split with
2530 // a compare against zero and a conditional branch.
2532 // Avoid introducing branch on poison. This also replaces the ctz operand.
2534 Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
2535 Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
2536 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2537 StartBlock->getTerminator()->eraseFromParent();
2538 DTU->applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock}});
2539
2540 // Create a PHI in the end block to select either the output of the intrinsic
2541 // or the bit width of the operand.
2542 Builder.SetInsertPoint(EndBlock->begin());
2543 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2544 replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
2545 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2546 PN->addIncoming(BitWidth, StartBlock);
2547 PN->addIncoming(CountZeros, CallBlock);
2548
2549 // We are explicitly handling the zero case, so we can set the intrinsic's
2550 // undefined zero argument to 'true'. This will also prevent reprocessing the
2551 // intrinsic; we only despeculate when a zero input is defined.
2552 CountZeros->setArgOperand(1, Builder.getTrue());
2553 ModifiedDT = ModifyDT::ModifyBBDT;
2554 return true;
2555}
2556
2557bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2558 BasicBlock *BB = CI->getParent();
2559
2560 // Sink address computing for memory operands into the block.
2561 if (CI->isInlineAsm() && optimizeInlineAsmInst(CI))
2562 return true;
2563
2564 // Align the pointer arguments to this call if the target thinks it's a good
2565 // idea
2566 unsigned MinSize;
2567 Align PrefAlign;
2568 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2569 for (auto &Arg : CI->args()) {
2570 // We want to align both objects whose address is used directly and
2571 // objects whose address is used in casts and GEPs, though it only makes
2572 // sense for GEPs if the offset is a multiple of the desired alignment and
2573 // if size - offset meets the size threshold.
2574 if (!Arg->getType()->isPointerTy())
2575 continue;
2576 APInt Offset(DL->getIndexSizeInBits(
2577 cast<PointerType>(Arg->getType())->getAddressSpace()),
2578 0);
2579 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2580 uint64_t Offset2 = Offset.getLimitedValue();
2581 if (!isAligned(PrefAlign, Offset2))
2582 continue;
2583 AllocaInst *AI;
2584 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2585 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(*DL);
2586 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2587 AI->setAlignment(PrefAlign);
2588 }
2589 // Global variables can only be aligned if they are defined in this
2590 // object (i.e. they are uniquely initialized in this object), and
2591 // over-aligning global variables that have an explicit section is
2592 // forbidden.
2593 GlobalVariable *GV;
2594 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2595 GV->getPointerAlignment(*DL) < PrefAlign &&
2596 GV->getGlobalSize(*DL) >= MinSize + Offset2)
2597 GV->setAlignment(PrefAlign);
2598 }
2599 }
2600 // If this is a memcpy (or similar) then we may be able to improve the
2601 // alignment.
2602 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2603 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2604 MaybeAlign MIDestAlign = MI->getDestAlign();
2605 if (!MIDestAlign || DestAlign > *MIDestAlign)
2606 MI->setDestAlignment(DestAlign);
2607 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2608 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2609 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2610 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2611 MTI->setSourceAlignment(SrcAlign);
2612 }
2613 }
2614
2615 // If we have a cold call site, try to sink addressing computation into the
2616 // cold block. This interacts with our handling for loads and stores to
2617 // ensure that we can fold all uses of a potential addressing computation
2618 // into their uses. TODO: generalize this to work over profiling data
2619 if (CI->hasFnAttr(Attribute::Cold) &&
2620 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2621 for (auto &Arg : CI->args()) {
2622 if (!Arg->getType()->isPointerTy())
2623 continue;
2624 unsigned AS = Arg->getType()->getPointerAddressSpace();
2625 if (optimizeMemoryInst(CI, Arg, Arg->getType(), AS))
2626 return true;
2627 }
2628
2629 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2630 if (II) {
2631 switch (II->getIntrinsicID()) {
2632 default:
2633 break;
2634 case Intrinsic::assume:
2635 llvm_unreachable("llvm.assume should have been removed already");
2636 case Intrinsic::allow_runtime_check:
2637 case Intrinsic::allow_ubsan_check:
2638 case Intrinsic::experimental_widenable_condition: {
2639 // Give up on future widening opportunities so that we can fold away dead
2640 // paths and merge blocks before going into block-local instruction
2641 // selection.
2642 if (II->use_empty()) {
2643 II->eraseFromParent();
2644 return true;
2645 }
2646 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2647 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2648 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2649 });
2650 return true;
2651 }
2652 case Intrinsic::objectsize:
2653 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2654 case Intrinsic::is_constant:
2655 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2656 case Intrinsic::aarch64_stlxr:
2657 case Intrinsic::aarch64_stxr: {
2658 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2659 if (!ExtVal || !ExtVal->hasOneUse() ||
2660 ExtVal->getParent() == CI->getParent())
2661 return false;
2662 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2663 ExtVal->moveBefore(CI->getIterator());
2664 // Mark this instruction as "inserted by CGP", so that other
2665 // optimizations don't touch it.
2666 InsertedInsts.insert(ExtVal);
2667 return true;
2668 }
2669
2670 case Intrinsic::launder_invariant_group: {
2671 Value *ArgVal = II->getArgOperand(0);
2672 auto it = LargeOffsetGEPMap.find(II);
2673 if (it != LargeOffsetGEPMap.end()) {
2674 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2675 // Make sure not to have to deal with iterator invalidation
2676 // after possibly adding ArgVal to LargeOffsetGEPMap.
2677 auto GEPs = std::move(it->second);
2678 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2679 LargeOffsetGEPMap.erase(II);
2680 }
2681
2682 replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
2683 II->eraseFromParent();
2684 return true;
2685 }
2686 case Intrinsic::cttz:
2687 case Intrinsic::ctlz:
2688 // If counting zeros is expensive, try to avoid it.
2689 return despeculateCountZeros(II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2690 IsHugeFunc);
2691 case Intrinsic::fshl:
2692 case Intrinsic::fshr:
2693 return optimizeFunnelShift(II);
2694 case Intrinsic::masked_gather:
2695 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2696 case Intrinsic::masked_scatter:
2697 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2698 case Intrinsic::masked_load:
2699 // Treat v1X masked load as load X type.
2700 if (auto *VT = dyn_cast<FixedVectorType>(II->getType())) {
2701 if (VT->getNumElements() == 1) {
2702 Value *PtrVal = II->getArgOperand(0);
2703 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2704 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2705 return true;
2706 }
2707 }
2708 return false;
2709 case Intrinsic::masked_store:
2710 // Treat v1X masked store as store X type.
2711 if (auto *VT =
2712 dyn_cast<FixedVectorType>(II->getArgOperand(0)->getType())) {
2713 if (VT->getNumElements() == 1) {
2714 Value *PtrVal = II->getArgOperand(1);
2715 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2716 if (optimizeMemoryInst(II, PtrVal, VT->getElementType(), AS))
2717 return true;
2718 }
2719 }
2720 return false;
2721 case Intrinsic::umul_with_overflow:
2722 return optimizeMulWithOverflow(II, /*IsSigned=*/false, ModifiedDT);
2723 case Intrinsic::smul_with_overflow:
2724 return optimizeMulWithOverflow(II, /*IsSigned=*/true, ModifiedDT);
2725 }
2726
2727 SmallVector<Value *, 2> PtrOps;
2728 Type *AccessTy;
2729 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2730 while (!PtrOps.empty()) {
2731 Value *PtrVal = PtrOps.pop_back_val();
2732 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2733 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2734 return true;
2735 }
2736 }
2737
2738 // From here on out we're working with named functions.
2739 auto *Callee = CI->getCalledFunction();
2740 if (!Callee)
2741 return false;
2742
2743 // Lower all default uses of _chk calls. This is very similar
2744 // to what InstCombineCalls does, but here we are only lowering calls
2745 // to fortified library functions (e.g. __memcpy_chk) that have the default
2746 // "don't know" as the objectsize. Anything else should be left alone.
2747 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2748 IRBuilder<> Builder(CI);
2749 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2750 replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
2751 CI->eraseFromParent();
2752 return true;
2753 }
2754
2755 // SCCP may have propagated, among other things, C++ static variables across
2756 // calls. If this happens to be the case, we may want to undo it in order to
2757 // avoid redundant pointer computation of the constant, as the function method
2758 // returning the constant needs to be executed anyways.
2759 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2760 if (!F->getReturnType()->isPointerTy())
2761 return nullptr;
2762
2763 GlobalVariable *UniformValue = nullptr;
2764 for (auto &BB : *F) {
2765 if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
2766 if (auto *V = dyn_cast<GlobalVariable>(RI->getReturnValue())) {
2767 if (!UniformValue)
2768 UniformValue = V;
2769 else if (V != UniformValue)
2770 return nullptr;
2771 } else {
2772 return nullptr;
2773 }
2774 }
2775 }
2776
2777 return UniformValue;
2778 };
2779
2780 if (Callee->hasExactDefinition()) {
2781 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2782 bool MadeChange = false;
2783 for (Use &U : make_early_inc_range(RV->uses())) {
2784 auto *I = dyn_cast<Instruction>(U.getUser());
2785 if (!I || I->getParent() != CI->getParent()) {
2786 // Limit to the same basic block to avoid extending the call-site live
2787 // range, which otherwise could increase register pressure.
2788 continue;
2789 }
2790 if (CI->comesBefore(I)) {
2791 U.set(CI);
2792 MadeChange = true;
2793 }
2794 }
2795
2796 return MadeChange;
2797 }
2798 }
2799
2800 return false;
2801}
2802
2804 const CallInst *CI) {
2805 assert(CI && CI->use_empty());
2806
2807 if (const auto *II = dyn_cast<IntrinsicInst>(CI))
2808 switch (II->getIntrinsicID()) {
2809 case Intrinsic::memset:
2810 case Intrinsic::memcpy:
2811 case Intrinsic::memmove:
2812 return true;
2813 default:
2814 return false;
2815 }
2816
2817 Function *Callee = CI->getCalledFunction();
2818 if (Callee && TLInfo)
2819 switch (TLInfo->getLibFunc(*Callee)) {
2820 case LibFunc_strcpy:
2821 case LibFunc_strncpy:
2822 case LibFunc_strcat:
2823 case LibFunc_strncat:
2824 return true;
2825 default:
2826 return false;
2827 }
2828
2829 return false;
2830}
2831
2832/// Look for opportunities to duplicate return instructions to the predecessor
2833/// to enable tail call optimizations. The case it is currently looking for is
2834/// the following one. Known intrinsics or library function that may be tail
2835/// called are taken into account as well.
2836/// @code
2837/// bb0:
2838/// %tmp0 = tail call i32 @f0()
2839/// br label %return
2840/// bb1:
2841/// %tmp1 = tail call i32 @f1()
2842/// br label %return
2843/// bb2:
2844/// %tmp2 = tail call i32 @f2()
2845/// br label %return
2846/// return:
2847/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2848/// ret i32 %retval
2849/// @endcode
2850///
2851/// =>
2852///
2853/// @code
2854/// bb0:
2855/// %tmp0 = tail call i32 @f0()
2856/// ret i32 %tmp0
2857/// bb1:
2858/// %tmp1 = tail call i32 @f1()
2859/// ret i32 %tmp1
2860/// bb2:
2861/// %tmp2 = tail call i32 @f2()
2862/// ret i32 %tmp2
2863/// @endcode
2864bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2865 ModifyDT &ModifiedDT) {
2866 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2867 if (!RetI)
2868 return false;
2869
2870 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2871
2872 PHINode *PN = nullptr;
2873 ExtractValueInst *EVI = nullptr;
2874 BitCastInst *BCI = nullptr;
2875 Value *V = RetI->getReturnValue();
2876 if (V) {
2877 BCI = dyn_cast<BitCastInst>(V);
2878 if (BCI)
2879 V = BCI->getOperand(0);
2880
2882 if (EVI) {
2883 V = EVI->getOperand(0);
2884 if (!llvm::all_of(EVI->indices(), equal_to(0)))
2885 return false;
2886 }
2887
2888 PN = dyn_cast<PHINode>(V);
2889 }
2890
2891 if (PN && PN->getParent() != BB)
2892 return false;
2893
2895
2896 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
2897 if (auto *II = dyn_cast<IntrinsicInst>(Inst);
2898 II && II->getIntrinsicID() == Intrinsic::fake_use) {
2899 // Record the instruction so it can be preserved when the exit block is
2900 // removed. Do not preserve the fake use that uses the result of the
2901 // PHI instruction.
2902 // Do not copy fake uses that use the result of a PHI node.
2903 // FIXME: If we do want to copy the fake use into the return blocks, we
2904 // have to figure out which of the PHI node operands to use for each
2905 // copy.
2906 if (!isa<PHINode>(II->getOperand(0))) {
2907 FakeUses.push_back(II);
2908 }
2909 return true;
2910 }
2911
2912 return false;
2913 };
2914
2915 // Make sure there are no instructions between the first instruction
2916 // and return.
2918 // Skip over pseudo-probes and the bitcast.
2919 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(BI) ||
2920 match(&*BI, m_Intrinsic<Intrinsic::lifetime_end>()) || isFakeUse(&*BI))
2921 BI = std::next(BI);
2922 if (&*BI != RetI)
2923 return false;
2924
2925 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2926 // call.
2927 auto MayBePermittedAsTailCall = [&](const auto *CI) {
2928 return TLI->mayBeEmittedAsTailCall(CI) &&
2929 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
2930 };
2931
2932 SmallVector<BasicBlock *, 4> TailCallBBs;
2933 // Record the call instructions so we can insert any fake uses
2934 // that need to be preserved before them.
2936 if (PN) {
2937 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2938 // Look through bitcasts.
2939 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2940 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2941 BasicBlock *PredBB = PN->getIncomingBlock(I);
2942 // Make sure the phi value is indeed produced by the tail call.
2943 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2944 MayBePermittedAsTailCall(CI)) {
2945 TailCallBBs.push_back(PredBB);
2946 CallInsts.push_back(CI);
2947 } else {
2948 // Consider the cases in which the phi value is indirectly produced by
2949 // the tail call, for example when encountering memset(), memmove(),
2950 // strcpy(), whose return value may have been optimized out. In such
2951 // cases, the value needs to be the first function argument.
2952 //
2953 // bb0:
2954 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
2955 // br label %return
2956 // return:
2957 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
2958 if (PredBB && PredBB->getSingleSuccessor() == BB)
2960 PredBB->getTerminator()->getPrevNode());
2961
2962 if (CI && CI->use_empty() &&
2963 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2964 IncomingVal == CI->getArgOperand(0) &&
2965 MayBePermittedAsTailCall(CI)) {
2966 TailCallBBs.push_back(PredBB);
2967 CallInsts.push_back(CI);
2968 }
2969 }
2970 }
2971 } else {
2972 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
2973 for (BasicBlock *Pred : predecessors(BB)) {
2974 if (!VisitedBBs.insert(Pred).second)
2975 continue;
2976 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
2977 CallInst *CI = dyn_cast<CallInst>(I);
2978 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
2979 // Either we return void or the return value must be the first
2980 // argument of a known intrinsic or library function.
2981 if (!V || isa<UndefValue>(V) ||
2982 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
2983 V == CI->getArgOperand(0))) {
2984 TailCallBBs.push_back(Pred);
2985 CallInsts.push_back(CI);
2986 }
2987 }
2988 }
2989 }
2990 }
2991
2992 bool Changed = false;
2993 for (auto const &TailCallBB : TailCallBBs) {
2994 // Make sure the call instruction is followed by an unconditional branch to
2995 // the return block.
2996 UncondBrInst *BI = dyn_cast<UncondBrInst>(TailCallBB->getTerminator());
2997 if (!BI || BI->getSuccessor() != BB)
2998 continue;
2999
3000 // Duplicate the return into TailCallBB.
3001 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB, DTU);
3002 assert(!Opts.cgp_verify_bfi_updates ||
3003 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3004 BFI->setBlockFreq(BB,
3005 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)));
3006 ModifiedDT = ModifyDT::ModifyBBDT;
3007 Changed = true;
3008 ++NumRetsDup;
3009 }
3010
3011 // If we eliminated all predecessors of the block, delete the block now.
3012 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3013 // Copy the fake uses found in the original return block to all blocks
3014 // that contain tail calls.
3015 for (auto *CI : CallInsts) {
3016 for (auto const *FakeUse : FakeUses) {
3017 auto *ClonedInst = FakeUse->clone();
3018 ClonedInst->insertBefore(CI->getIterator());
3019 }
3020 }
3021 DTU->deleteBB(BB);
3022 }
3023
3024 return Changed;
3025}
3026
3027//===----------------------------------------------------------------------===//
3028// Memory Optimization
3029//===----------------------------------------------------------------------===//
3030
3031namespace {
3032
3033/// This is an extended version of TargetLowering::AddrMode
3034/// which holds actual Value*'s for register values.
3035struct ExtAddrMode : public TargetLowering::AddrMode {
3036 Value *BaseReg = nullptr;
3037 Value *ScaledReg = nullptr;
3038 Value *OriginalValue = nullptr;
3039 bool InBounds = true;
3040
3041 enum FieldName {
3042 NoField = 0x00,
3043 BaseRegField = 0x01,
3044 BaseGVField = 0x02,
3045 BaseOffsField = 0x04,
3046 ScaledRegField = 0x08,
3047 ScaleField = 0x10,
3048 MultipleFields = 0xff
3049 };
3050
3051 ExtAddrMode() = default;
3052
3053 void print(raw_ostream &OS) const;
3054 void dump() const;
3055
3056 // Replace From in ExtAddrMode with To.
3057 // E.g., SExt insts may be promoted and deleted. We should replace them with
3058 // the promoted values.
3059 void replaceWith(Value *From, Value *To) {
3060 if (ScaledReg == From)
3061 ScaledReg = To;
3062 }
3063
3064 FieldName compare(const ExtAddrMode &other) {
3065 // First check that the types are the same on each field, as differing types
3066 // is something we can't cope with later on.
3067 if (BaseReg && other.BaseReg &&
3068 BaseReg->getType() != other.BaseReg->getType())
3069 return MultipleFields;
3070 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3071 return MultipleFields;
3072 if (ScaledReg && other.ScaledReg &&
3073 ScaledReg->getType() != other.ScaledReg->getType())
3074 return MultipleFields;
3075
3076 // Conservatively reject 'inbounds' mismatches.
3077 if (InBounds != other.InBounds)
3078 return MultipleFields;
3079
3080 // Check each field to see if it differs.
3081 unsigned Result = NoField;
3082 if (BaseReg != other.BaseReg)
3083 Result |= BaseRegField;
3084 if (BaseGV != other.BaseGV)
3085 Result |= BaseGVField;
3086 if (BaseOffs != other.BaseOffs)
3087 Result |= BaseOffsField;
3088 if (ScaledReg != other.ScaledReg)
3089 Result |= ScaledRegField;
3090 // Don't count 0 as being a different scale, because that actually means
3091 // unscaled (which will already be counted by having no ScaledReg).
3092 if (Scale && other.Scale && Scale != other.Scale)
3093 Result |= ScaleField;
3094
3095 if (llvm::popcount(Result) > 1)
3096 return MultipleFields;
3097 else
3098 return static_cast<FieldName>(Result);
3099 }
3100
3101 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3102 // with no offset.
3103 bool isTrivial() {
3104 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3105 // trivial if at most one of these terms is nonzero, except that BaseGV and
3106 // BaseReg both being zero actually means a null pointer value, which we
3107 // consider to be 'non-zero' here.
3108 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3109 }
3110
3111 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3112 switch (Field) {
3113 default:
3114 return nullptr;
3115 case BaseRegField:
3116 return BaseReg;
3117 case BaseGVField:
3118 return BaseGV;
3119 case ScaledRegField:
3120 return ScaledReg;
3121 case BaseOffsField:
3122 return ConstantInt::getSigned(IntPtrTy, BaseOffs);
3123 }
3124 }
3125
3126 void SetCombinedField(FieldName Field, Value *V,
3127 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3128 switch (Field) {
3129 default:
3130 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3131 break;
3132 case ExtAddrMode::BaseRegField:
3133 BaseReg = V;
3134 break;
3135 case ExtAddrMode::BaseGVField:
3136 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3137 // in the BaseReg field.
3138 assert(BaseReg == nullptr);
3139 BaseReg = V;
3140 BaseGV = nullptr;
3141 break;
3142 case ExtAddrMode::ScaledRegField:
3143 ScaledReg = V;
3144 // If we have a mix of scaled and unscaled addrmodes then we want scale
3145 // to be the scale and not zero.
3146 if (!Scale)
3147 for (const ExtAddrMode &AM : AddrModes)
3148 if (AM.Scale) {
3149 Scale = AM.Scale;
3150 break;
3151 }
3152 break;
3153 case ExtAddrMode::BaseOffsField:
3154 // The offset is no longer a constant, so it goes in ScaledReg with a
3155 // scale of 1.
3156 assert(ScaledReg == nullptr);
3157 ScaledReg = V;
3158 Scale = 1;
3159 BaseOffs = 0;
3160 break;
3161 }
3162 }
3163};
3164
3165#ifndef NDEBUG
3166static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3167 AM.print(OS);
3168 return OS;
3169}
3170#endif
3171
3172#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3173void ExtAddrMode::print(raw_ostream &OS) const {
3174 bool NeedPlus = false;
3175 OS << "[";
3176 if (InBounds)
3177 OS << "inbounds ";
3178 if (BaseGV) {
3179 OS << "GV:";
3180 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3181 NeedPlus = true;
3182 }
3183
3184 if (BaseOffs) {
3185 OS << (NeedPlus ? " + " : "") << BaseOffs;
3186 NeedPlus = true;
3187 }
3188
3189 if (BaseReg) {
3190 OS << (NeedPlus ? " + " : "") << "Base:";
3191 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3192 NeedPlus = true;
3193 }
3194 if (Scale) {
3195 OS << (NeedPlus ? " + " : "") << Scale << "*";
3196 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3197 }
3198
3199 OS << ']';
3200}
3201
3202LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3203 print(dbgs());
3204 dbgs() << '\n';
3205}
3206#endif
3207
3208} // end anonymous namespace
3209
3210namespace {
3211
3212/// This class provides transaction based operation on the IR.
3213/// Every change made through this class is recorded in the internal state and
3214/// can be undone (rollback) until commit is called.
3215/// CGP does not check if instructions could be speculatively executed when
3216/// moved. Preserving the original location would pessimize the debugging
3217/// experience, as well as negatively impact the quality of sample PGO.
3218class TypePromotionTransaction {
3219 /// This represents the common interface of the individual transaction.
3220 /// Each class implements the logic for doing one specific modification on
3221 /// the IR via the TypePromotionTransaction.
3222 class TypePromotionAction {
3223 protected:
3224 /// The Instruction modified.
3225 Instruction *Inst;
3226
3227 public:
3228 /// Constructor of the action.
3229 /// The constructor performs the related action on the IR.
3230 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3231
3232 virtual ~TypePromotionAction() = default;
3233
3234 /// Undo the modification done by this action.
3235 /// When this method is called, the IR must be in the same state as it was
3236 /// before this action was applied.
3237 /// \pre Undoing the action works if and only if the IR is in the exact same
3238 /// state as it was directly after this action was applied.
3239 virtual void undo() = 0;
3240
3241 /// Advocate every change made by this action.
3242 /// When the results on the IR of the action are to be kept, it is important
3243 /// to call this function, otherwise hidden information may be kept forever.
3244 virtual void commit() {
3245 // Nothing to be done, this action is not doing anything.
3246 }
3247 };
3248
3249 /// Utility to remember the position of an instruction.
3250 class InsertionHandler {
3251 /// Position of an instruction.
3252 /// Either an instruction:
3253 /// - Is the first in a basic block: BB is used.
3254 /// - Has a previous instruction: PrevInst is used.
3255 struct {
3256 BasicBlock::iterator PrevInst;
3257 BasicBlock *BB;
3258 } Point;
3259 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3260
3261 /// Remember whether or not the instruction had a previous instruction.
3262 bool HasPrevInstruction;
3263
3264 public:
3265 /// Record the position of \p Inst.
3266 InsertionHandler(Instruction *Inst) {
3267 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3268 BasicBlock *BB = Inst->getParent();
3269
3270 // Record where we would have to re-insert the instruction in the sequence
3271 // of DbgRecords, if we ended up reinserting.
3272 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3273
3274 if (HasPrevInstruction) {
3275 Point.PrevInst = std::prev(Inst->getIterator());
3276 } else {
3277 Point.BB = BB;
3278 }
3279 }
3280
3281 /// Insert \p Inst at the recorded position.
3282 void insert(Instruction *Inst) {
3283 if (HasPrevInstruction) {
3284 if (Inst->getParent())
3285 Inst->removeFromParent();
3286 Inst->insertAfter(Point.PrevInst);
3287 } else {
3288 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3289 if (Inst->getParent())
3290 Inst->moveBefore(*Point.BB, Position);
3291 else
3292 Inst->insertBefore(*Point.BB, Position);
3293 }
3294
3295 Inst->getParent()->reinsertInstInDbgRecords(Inst, BeforeDbgRecord);
3296 }
3297 };
3298
3299 /// Set the operand of an instruction with a new value.
3300 class OperandSetter : public TypePromotionAction {
3301 /// Original operand of the instruction.
3302 Value *Origin;
3303
3304 /// Index of the modified instruction.
3305 unsigned Idx;
3306
3307 public:
3308 /// Set \p Idx operand of \p Inst with \p NewVal.
3309 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3310 : TypePromotionAction(Inst), Idx(Idx) {
3311 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3312 << "for:" << *Inst << "\n"
3313 << "with:" << *NewVal << "\n");
3314 Origin = Inst->getOperand(Idx);
3315 Inst->setOperand(Idx, NewVal);
3316 }
3317
3318 /// Restore the original value of the instruction.
3319 void undo() override {
3320 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3321 << "for: " << *Inst << "\n"
3322 << "with: " << *Origin << "\n");
3323 Inst->setOperand(Idx, Origin);
3324 }
3325 };
3326
3327 /// Hide the operands of an instruction.
3328 /// Do as if this instruction was not using any of its operands.
3329 class OperandsHider : public TypePromotionAction {
3330 /// The list of original operands.
3331 SmallVector<Value *, 4> OriginalValues;
3332
3333 public:
3334 /// Remove \p Inst from the uses of the operands of \p Inst.
3335 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3336 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3337 unsigned NumOpnds = Inst->getNumOperands();
3338 OriginalValues.reserve(NumOpnds);
3339 for (unsigned It = 0; It < NumOpnds; ++It) {
3340 // Save the current operand.
3341 Value *Val = Inst->getOperand(It);
3342 OriginalValues.push_back(Val);
3343 // Set a dummy one.
3344 // We could use OperandSetter here, but that would imply an overhead
3345 // that we are not willing to pay.
3346 Inst->setOperand(It, PoisonValue::get(Val->getType()));
3347 }
3348 }
3349
3350 /// Restore the original list of uses.
3351 void undo() override {
3352 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3353 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3354 Inst->setOperand(It, OriginalValues[It]);
3355 }
3356 };
3357
3358 /// Build a truncate instruction.
3359 class TruncBuilder : public TypePromotionAction {
3360 Value *Val;
3361
3362 public:
3363 /// Build a truncate instruction of \p Opnd producing a \p Ty
3364 /// result.
3365 /// trunc Opnd to Ty.
3366 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3367 IRBuilder<> Builder(Opnd);
3368 Builder.SetCurrentDebugLocation(DebugLoc());
3369 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
3370 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3371 }
3372
3373 /// Get the built value.
3374 Value *getBuiltValue() { return Val; }
3375
3376 /// Remove the built instruction.
3377 void undo() override {
3378 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3379 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3380 IVal->eraseFromParent();
3381 }
3382 };
3383
3384 /// Build a sign extension instruction.
3385 class SExtBuilder : public TypePromotionAction {
3386 Value *Val;
3387
3388 public:
3389 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3390 /// result.
3391 /// sext Opnd to Ty.
3392 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3393 : TypePromotionAction(InsertPt) {
3394 IRBuilder<> Builder(InsertPt);
3395 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
3396 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3397 }
3398
3399 /// Get the built value.
3400 Value *getBuiltValue() { return Val; }
3401
3402 /// Remove the built instruction.
3403 void undo() override {
3404 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3405 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3406 IVal->eraseFromParent();
3407 }
3408 };
3409
3410 /// Build a zero extension instruction.
3411 class ZExtBuilder : public TypePromotionAction {
3412 Value *Val;
3413
3414 public:
3415 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3416 /// result.
3417 /// zext Opnd to Ty.
3418 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3419 : TypePromotionAction(InsertPt) {
3420 IRBuilder<> Builder(InsertPt);
3421 Builder.SetCurrentDebugLocation(DebugLoc());
3422 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
3423 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3424 }
3425
3426 /// Get the built value.
3427 Value *getBuiltValue() { return Val; }
3428
3429 /// Remove the built instruction.
3430 void undo() override {
3431 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3432 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3433 IVal->eraseFromParent();
3434 }
3435 };
3436
3437 /// Mutate an instruction to another type.
3438 class TypeMutator : public TypePromotionAction {
3439 /// Record the original type.
3440 Type *OrigTy;
3441
3442 public:
3443 /// Mutate the type of \p Inst into \p NewTy.
3444 TypeMutator(Instruction *Inst, Type *NewTy)
3445 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3446 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3447 << "\n");
3448 Inst->mutateType(NewTy);
3449 }
3450
3451 /// Mutate the instruction back to its original type.
3452 void undo() override {
3453 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3454 << "\n");
3455 Inst->mutateType(OrigTy);
3456 }
3457 };
3458
3459 /// Replace the uses of an instruction by another instruction.
3460 class UsesReplacer : public TypePromotionAction {
3461 /// Helper structure to keep track of the replaced uses.
3462 struct InstructionAndIdx {
3463 /// The instruction using the instruction.
3464 Instruction *Inst;
3465
3466 /// The index where this instruction is used for Inst.
3467 unsigned Idx;
3468
3469 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3470 : Inst(Inst), Idx(Idx) {}
3471 };
3472
3473 /// Keep track of the original uses (pair Instruction, Index).
3475 /// Keep track of the debug users.
3476 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3477
3478 /// Keep track of the new value so that we can undo it by replacing
3479 /// instances of the new value with the original value.
3480 Value *New;
3481
3482 public:
3483 /// Replace all the use of \p Inst by \p New.
3484 UsesReplacer(Instruction *Inst, Value *New)
3485 : TypePromotionAction(Inst), New(New) {
3486 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3487 << "\n");
3488 // Record the original uses.
3489 for (Use &U : Inst->uses()) {
3490 Instruction *UserI = cast<Instruction>(U.getUser());
3491 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
3492 }
3493 // Record the debug uses separately. They are not in the instruction's
3494 // use list, but they are replaced by RAUW.
3495 findDbgValues(Inst, DbgVariableRecords);
3496
3497 // Now, we can replace the uses.
3498 Inst->replaceAllUsesWith(New);
3499 }
3500
3501 /// Reassign the original uses of Inst to Inst.
3502 void undo() override {
3503 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3504 for (InstructionAndIdx &Use : OriginalUses)
3505 Use.Inst->setOperand(Use.Idx, Inst);
3506 // RAUW has replaced all original uses with references to the new value,
3507 // including the debug uses. Since we are undoing the replacements,
3508 // the original debug uses must also be reinstated to maintain the
3509 // correctness and utility of debug value records.
3510 for (DbgVariableRecord *DVR : DbgVariableRecords)
3511 DVR->replaceVariableLocationOp(New, Inst);
3512 }
3513 };
3514
3515 /// Remove an instruction from the IR.
3516 class InstructionRemover : public TypePromotionAction {
3517 /// Original position of the instruction.
3518 InsertionHandler Inserter;
3519
3520 /// Helper structure to hide all the link to the instruction. In other
3521 /// words, this helps to do as if the instruction was removed.
3522 OperandsHider Hider;
3523
3524 /// Keep track of the uses replaced, if any.
3525 UsesReplacer *Replacer = nullptr;
3526
3527 /// Keep track of instructions removed.
3528 SetOfInstrs &RemovedInsts;
3529
3530 public:
3531 /// Remove all reference of \p Inst and optionally replace all its
3532 /// uses with New.
3533 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3534 /// \pre If !Inst->use_empty(), then New != nullptr
3535 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3536 Value *New = nullptr)
3537 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3538 RemovedInsts(RemovedInsts) {
3539 if (New)
3540 Replacer = new UsesReplacer(Inst, New);
3541 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3542 RemovedInsts.insert(Inst);
3543 /// The instructions removed here will be freed after completing
3544 /// optimizeBlock() for all blocks as we need to keep track of the
3545 /// removed instructions during promotion.
3546 Inst->removeFromParent();
3547 }
3548
3549 ~InstructionRemover() override { delete Replacer; }
3550
3551 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3552 InstructionRemover(const InstructionRemover &other) = delete;
3553
3554 /// Resurrect the instruction and reassign it to the proper uses if
3555 /// new value was provided when build this action.
3556 void undo() override {
3557 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3558 Inserter.insert(Inst);
3559 if (Replacer)
3560 Replacer->undo();
3561 Hider.undo();
3562 RemovedInsts.erase(Inst);
3563 }
3564 };
3565
3566public:
3567 /// Restoration point.
3568 /// The restoration point is a pointer to an action instead of an iterator
3569 /// because the iterator may be invalidated but not the pointer.
3570 using ConstRestorationPt = const TypePromotionAction *;
3571
3572 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3573 : RemovedInsts(RemovedInsts) {}
3574
3575 /// Advocate every changes made in that transaction. Return true if any change
3576 /// happen.
3577 bool commit();
3578
3579 /// Undo all the changes made after the given point.
3580 void rollback(ConstRestorationPt Point);
3581
3582 /// Get the current restoration point.
3583 ConstRestorationPt getRestorationPoint() const;
3584
3585 /// \name API for IR modification with state keeping to support rollback.
3586 /// @{
3587 /// Same as Instruction::setOperand.
3588 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3589
3590 /// Same as Instruction::eraseFromParent.
3591 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3592
3593 /// Same as Value::replaceAllUsesWith.
3594 void replaceAllUsesWith(Instruction *Inst, Value *New);
3595
3596 /// Same as Value::mutateType.
3597 void mutateType(Instruction *Inst, Type *NewTy);
3598
3599 /// Same as IRBuilder::createTrunc.
3600 Value *createTrunc(Instruction *Opnd, Type *Ty);
3601
3602 /// Same as IRBuilder::createSExt.
3603 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3604
3605 /// Same as IRBuilder::createZExt.
3606 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3607
3608private:
3609 /// The ordered list of actions made so far.
3611
3612 SetOfInstrs &RemovedInsts;
3613};
3614
3615} // end anonymous namespace
3616
3617void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3618 Value *NewVal) {
3619 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3620 Inst, Idx, NewVal));
3621}
3622
3623void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3624 Value *NewVal) {
3625 Actions.push_back(
3626 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3627 Inst, RemovedInsts, NewVal));
3628}
3629
3630void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3631 Value *New) {
3632 Actions.push_back(
3633 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3634}
3635
3636void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3637 Actions.push_back(
3638 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3639}
3640
3641Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3642 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3643 Value *Val = Ptr->getBuiltValue();
3644 Actions.push_back(std::move(Ptr));
3645 return Val;
3646}
3647
3648Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3649 Type *Ty) {
3650 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3651 Value *Val = Ptr->getBuiltValue();
3652 Actions.push_back(std::move(Ptr));
3653 return Val;
3654}
3655
3656Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3657 Type *Ty) {
3658 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3659 Value *Val = Ptr->getBuiltValue();
3660 Actions.push_back(std::move(Ptr));
3661 return Val;
3662}
3663
3664TypePromotionTransaction::ConstRestorationPt
3665TypePromotionTransaction::getRestorationPoint() const {
3666 return !Actions.empty() ? Actions.back().get() : nullptr;
3667}
3668
3669bool TypePromotionTransaction::commit() {
3670 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3671 Action->commit();
3672 bool Modified = !Actions.empty();
3673 Actions.clear();
3674 return Modified;
3675}
3676
3677void TypePromotionTransaction::rollback(
3678 TypePromotionTransaction::ConstRestorationPt Point) {
3679 while (!Actions.empty() && Point != Actions.back().get()) {
3680 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3681 Curr->undo();
3682 }
3683}
3684
3685namespace {
3686
3687/// A helper class for matching addressing modes.
3688///
3689/// This encapsulates the logic for matching the target-legal addressing modes.
3690class AddressingModeMatcher {
3691 SmallVectorImpl<Instruction *> &AddrModeInsts;
3692 const TargetLowering &TLI;
3693 const TargetRegisterInfo &TRI;
3694 const DataLayout &DL;
3695 const LoopInfo &LI;
3696 const std::function<const DominatorTree &()> getDTFn;
3697
3698 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3699 /// the memory instruction that we're computing this address for.
3700 Type *AccessTy;
3701 unsigned AddrSpace;
3702 Instruction *MemoryInst;
3703
3704 /// This is the addressing mode that we're building up. This is
3705 /// part of the return value of this addressing mode matching stuff.
3706 ExtAddrMode &AddrMode;
3707
3708 /// The instructions inserted by other CodeGenPrepare optimizations.
3709 const SetOfInstrs &InsertedInsts;
3710
3711 /// A map from the instructions to their type before promotion.
3712 InstrToOrigTy &PromotedInsts;
3713
3714 /// The ongoing transaction where every action should be registered.
3715 TypePromotionTransaction &TPT;
3716
3717 // A GEP which has too large offset to be folded into the addressing mode.
3718 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3719
3720 /// This is set to true when we should not do profitability checks.
3721 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3722 bool IgnoreProfitability;
3723
3724 /// True if we are optimizing for size.
3725 bool OptSize = false;
3726
3727 ProfileSummaryInfo *PSI;
3728 BlockFrequencyInfo *BFI;
3729 const CodeGenOptions &Opts;
3730
3731 AddressingModeMatcher(
3732 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3733 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3734 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3735 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3736 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3737 TypePromotionTransaction &TPT,
3738 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3739 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3740 const CodeGenOptions &Opts)
3741 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), DL(MI->getDataLayout()), LI(LI),
3742 getDTFn(getDTFn), AccessTy(AT), AddrSpace(AS), MemoryInst(MI),
3743 AddrMode(AM), InsertedInsts(InsertedInsts),
3744 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP),
3745 OptSize(OptSize), PSI(PSI), BFI(BFI), Opts(Opts) {
3746 IgnoreProfitability = false;
3747 }
3748
3749public:
3750 /// Find the maximal addressing mode that a load/store of V can fold,
3751 /// give an access type of AccessTy. This returns a list of involved
3752 /// instructions in AddrModeInsts.
3753 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3754 /// optimizations.
3755 /// \p PromotedInsts maps the instructions to their type before promotion.
3756 /// \p The ongoing transaction where every action should be registered.
3757 static ExtAddrMode
3758 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3759 SmallVectorImpl<Instruction *> &AddrModeInsts,
3760 const TargetLowering &TLI, const LoopInfo &LI,
3761 const std::function<const DominatorTree &()> getDTFn,
3762 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3763 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3764 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3765 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI,
3766 const CodeGenOptions &Opts) {
3767 ExtAddrMode Result;
3768
3769 bool Success = AddressingModeMatcher(
3770 AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS,
3771 MemoryInst, Result, InsertedInsts, PromotedInsts, TPT,
3772 LargeOffsetGEP, OptSize, PSI, BFI, Opts)
3773 .matchAddr(V, 0);
3774 (void)Success;
3775 assert(Success && "Couldn't select *anything*?");
3776 return Result;
3777 }
3778
3779private:
3780 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3781 bool matchAddr(Value *Addr, unsigned Depth);
3782 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3783 bool *MovedAway = nullptr);
3784 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3785 ExtAddrMode &AMBefore,
3786 ExtAddrMode &AMAfter);
3787 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3788 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3789 Value *PromotedOperand) const;
3790};
3791
3792class PhiNodeSet;
3793
3794/// An iterator for PhiNodeSet.
3795class PhiNodeSetIterator {
3796 PhiNodeSet *const Set;
3797 size_t CurrentIndex = 0;
3798
3799public:
3800 /// The constructor. Start should point to either a valid element, or be equal
3801 /// to the size of the underlying SmallVector of the PhiNodeSet.
3802 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3803 PHINode *operator*() const;
3804 PhiNodeSetIterator &operator++();
3805 bool operator==(const PhiNodeSetIterator &RHS) const;
3806 bool operator!=(const PhiNodeSetIterator &RHS) const;
3807};
3808
3809/// Keeps a set of PHINodes.
3810///
3811/// This is a minimal set implementation for a specific use case:
3812/// It is very fast when there are very few elements, but also provides good
3813/// performance when there are many. It is similar to SmallPtrSet, but also
3814/// provides iteration by insertion order, which is deterministic and stable
3815/// across runs. It is also similar to SmallSetVector, but provides removing
3816/// elements in O(1) time. This is achieved by not actually removing the element
3817/// from the underlying vector, so comes at the cost of using more memory, but
3818/// that is fine, since PhiNodeSets are used as short lived objects.
3819class PhiNodeSet {
3820 friend class PhiNodeSetIterator;
3821
3822 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3823 using iterator = PhiNodeSetIterator;
3824
3825 /// Keeps the elements in the order of their insertion in the underlying
3826 /// vector. To achieve constant time removal, it never deletes any element.
3828
3829 /// Keeps the elements in the underlying set implementation. This (and not the
3830 /// NodeList defined above) is the source of truth on whether an element
3831 /// is actually in the collection.
3832 MapType NodeMap;
3833
3834 /// Points to the first valid (not deleted) element when the set is not empty
3835 /// and the value is not zero. Equals to the size of the underlying vector
3836 /// when the set is empty. When the value is 0, as in the beginning, the
3837 /// first element may or may not be valid.
3838 size_t FirstValidElement = 0;
3839
3840public:
3841 /// Inserts a new element to the collection.
3842 /// \returns true if the element is actually added, i.e. was not in the
3843 /// collection before the operation.
3844 bool insert(PHINode *Ptr) {
3845 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3846 NodeList.push_back(Ptr);
3847 return true;
3848 }
3849 return false;
3850 }
3851
3852 /// Removes the element from the collection.
3853 /// \returns whether the element is actually removed, i.e. was in the
3854 /// collection before the operation.
3855 bool erase(PHINode *Ptr) {
3856 if (NodeMap.erase(Ptr)) {
3857 SkipRemovedElements(FirstValidElement);
3858 return true;
3859 }
3860 return false;
3861 }
3862
3863 /// Removes all elements and clears the collection.
3864 void clear() {
3865 NodeMap.clear();
3866 NodeList.clear();
3867 FirstValidElement = 0;
3868 }
3869
3870 /// \returns an iterator that will iterate the elements in the order of
3871 /// insertion.
3872 iterator begin() {
3873 if (FirstValidElement == 0)
3874 SkipRemovedElements(FirstValidElement);
3875 return PhiNodeSetIterator(this, FirstValidElement);
3876 }
3877
3878 /// \returns an iterator that points to the end of the collection.
3879 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3880
3881 /// Returns the number of elements in the collection.
3882 size_t size() const { return NodeMap.size(); }
3883
3884 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3885 size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
3886
3887private:
3888 /// Updates the CurrentIndex so that it will point to a valid element.
3889 ///
3890 /// If the element of NodeList at CurrentIndex is valid, it does not
3891 /// change it. If there are no more valid elements, it updates CurrentIndex
3892 /// to point to the end of the NodeList.
3893 void SkipRemovedElements(size_t &CurrentIndex) {
3894 while (CurrentIndex < NodeList.size()) {
3895 auto it = NodeMap.find(NodeList[CurrentIndex]);
3896 // If the element has been deleted and added again later, NodeMap will
3897 // point to a different index, so CurrentIndex will still be invalid.
3898 if (it != NodeMap.end() && it->second == CurrentIndex)
3899 break;
3900 ++CurrentIndex;
3901 }
3902 }
3903};
3904
3905PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3906 : Set(Set), CurrentIndex(Start) {}
3907
3908PHINode *PhiNodeSetIterator::operator*() const {
3909 assert(CurrentIndex < Set->NodeList.size() &&
3910 "PhiNodeSet access out of range");
3911 return Set->NodeList[CurrentIndex];
3912}
3913
3914PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
3915 assert(CurrentIndex < Set->NodeList.size() &&
3916 "PhiNodeSet access out of range");
3917 ++CurrentIndex;
3918 Set->SkipRemovedElements(CurrentIndex);
3919 return *this;
3920}
3921
3922bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3923 return CurrentIndex == RHS.CurrentIndex;
3924}
3925
3926bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3927 return !((*this) == RHS);
3928}
3929
3930/// Keep track of simplification of Phi nodes.
3931/// Accept the set of all phi nodes and erase phi node from this set
3932/// if it is simplified.
3933class SimplificationTracker {
3934 DenseMap<Value *, Value *> Storage;
3935 // Tracks newly created Phi nodes. The elements are iterated by insertion
3936 // order.
3937 PhiNodeSet AllPhiNodes;
3938 // Tracks newly created Select nodes.
3939 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3940
3941public:
3942 Value *Get(Value *V) {
3943 do {
3944 auto SV = Storage.find(V);
3945 if (SV == Storage.end())
3946 return V;
3947 V = SV->second;
3948 } while (true);
3949 }
3950
3951 void Put(Value *From, Value *To) { Storage.insert({From, To}); }
3952
3953 void ReplacePhi(PHINode *From, PHINode *To) {
3954 Value *OldReplacement = Get(From);
3955 while (OldReplacement != From) {
3956 From = To;
3957 To = dyn_cast<PHINode>(OldReplacement);
3958 OldReplacement = Get(From);
3959 }
3960 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
3961 Put(From, To);
3962 From->replaceAllUsesWith(To);
3963 AllPhiNodes.erase(From);
3964 From->eraseFromParent();
3965 }
3966
3967 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
3968
3969 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3970
3971 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3972
3973 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3974
3975 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3976
3977 void destroyNewNodes(Type *CommonType) {
3978 // For safe erasing, replace the uses with dummy value first.
3979 auto *Dummy = PoisonValue::get(CommonType);
3980 for (auto *I : AllPhiNodes) {
3981 I->replaceAllUsesWith(Dummy);
3982 I->eraseFromParent();
3983 }
3984 AllPhiNodes.clear();
3985 for (auto *I : AllSelectNodes) {
3986 I->replaceAllUsesWith(Dummy);
3987 I->eraseFromParent();
3988 }
3989 AllSelectNodes.clear();
3990 }
3991};
3992
3993/// A helper class for combining addressing modes.
3994class AddressingModeCombiner {
3995 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3996 typedef std::pair<PHINode *, PHINode *> PHIPair;
3997
3998private:
3999 /// The addressing modes we've collected.
4001
4002 /// The field in which the AddrModes differ, when we have more than one.
4003 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4004
4005 /// Are the AddrModes that we have all just equal to their original values?
4006 bool AllAddrModesTrivial = true;
4007
4008 /// Common Type for all different fields in addressing modes.
4009 Type *CommonType = nullptr;
4010
4011 const DataLayout &DL;
4012 const CodeGenOptions &Opts;
4013
4014 /// Original Address.
4015 Value *Original;
4016
4017 /// Common value among addresses
4018 Value *CommonValue = nullptr;
4019
4020public:
4021 AddressingModeCombiner(const DataLayout &DL, const CodeGenOptions &Opts,
4022 Value *OriginalValue)
4023 : DL(DL), Opts(Opts), Original(OriginalValue) {}
4024
4025 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4026
4027 /// Get the combined AddrMode
4028 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4029
4030 /// Add a new AddrMode if it's compatible with the AddrModes we already
4031 /// have.
4032 /// \return True iff we succeeded in doing so.
4033 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4034 // Take note of if we have any non-trivial AddrModes, as we need to detect
4035 // when all AddrModes are trivial as then we would introduce a phi or select
4036 // which just duplicates what's already there.
4037 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4038
4039 // If this is the first addrmode then everything is fine.
4040 if (AddrModes.empty()) {
4041 AddrModes.emplace_back(NewAddrMode);
4042 return true;
4043 }
4044
4045 // Figure out how different this is from the other address modes, which we
4046 // can do just by comparing against the first one given that we only care
4047 // about the cumulative difference.
4048 ExtAddrMode::FieldName ThisDifferentField =
4049 AddrModes[0].compare(NewAddrMode);
4050 if (DifferentField == ExtAddrMode::NoField)
4051 DifferentField = ThisDifferentField;
4052 else if (DifferentField != ThisDifferentField)
4053 DifferentField = ExtAddrMode::MultipleFields;
4054
4055 // If NewAddrMode differs in more than one dimension we cannot handle it.
4056 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4057
4058 // If Scale Field is different then we reject.
4059 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4060
4061 // We also must reject the case when base offset is different and
4062 // scale reg is not null, we cannot handle this case due to merge of
4063 // different offsets will be used as ScaleReg.
4064 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4065 !NewAddrMode.ScaledReg);
4066
4067 // We also must reject the case when GV is different and BaseReg installed
4068 // due to we want to use base reg as a merge of GV values.
4069 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4070 !NewAddrMode.HasBaseReg);
4071
4072 // Even if NewAddMode is the same we still need to collect it due to
4073 // original value is different. And later we will need all original values
4074 // as anchors during finding the common Phi node.
4075 if (CanHandle)
4076 AddrModes.emplace_back(NewAddrMode);
4077 else
4078 AddrModes.clear();
4079
4080 return CanHandle;
4081 }
4082
4083 /// Combine the addressing modes we've collected into a single
4084 /// addressing mode.
4085 /// \return True iff we successfully combined them or we only had one so
4086 /// didn't need to combine them anyway.
4087 bool combineAddrModes() {
4088 // If we have no AddrModes then they can't be combined.
4089 if (AddrModes.size() == 0)
4090 return false;
4091
4092 // A single AddrMode can trivially be combined.
4093 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4094 return true;
4095
4096 // If the AddrModes we collected are all just equal to the value they are
4097 // derived from then combining them wouldn't do anything useful.
4098 if (AllAddrModesTrivial)
4099 return false;
4100
4101 if (!addrModeCombiningAllowed())
4102 return false;
4103
4104 // Build a map between <original value, basic block where we saw it> to
4105 // value of base register.
4106 // Bail out if there is no common type.
4107 FoldAddrToValueMapping Map;
4108 if (!initializeMap(Map))
4109 return false;
4110
4111 CommonValue = findCommon(Map);
4112 if (CommonValue)
4113 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
4114 return CommonValue != nullptr;
4115 }
4116
4117private:
4118 /// `CommonValue` may be a placeholder inserted by us.
4119 /// If the placeholder is not used, we should remove this dead instruction.
4120 void eraseCommonValueIfDead() {
4121 if (CommonValue && CommonValue->use_empty())
4122 if (Instruction *CommonInst = dyn_cast<Instruction>(CommonValue))
4123 CommonInst->eraseFromParent();
4124 }
4125
4126 /// Initialize Map with anchor values. For address seen
4127 /// we set the value of different field saw in this address.
4128 /// At the same time we find a common type for different field we will
4129 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4130 /// Return false if there is no common type found.
4131 bool initializeMap(FoldAddrToValueMapping &Map) {
4132 // Keep track of keys where the value is null. We will need to replace it
4133 // with constant null when we know the common type.
4134 SmallVector<Value *, 2> NullValue;
4135 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4136 for (auto &AM : AddrModes) {
4137 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
4138 if (DV) {
4139 auto *Type = DV->getType();
4140 if (CommonType && CommonType != Type)
4141 return false;
4142 CommonType = Type;
4143 Map[AM.OriginalValue] = DV;
4144 } else {
4145 NullValue.push_back(AM.OriginalValue);
4146 }
4147 }
4148 assert(CommonType && "At least one non-null value must be!");
4149 for (auto *V : NullValue)
4150 Map[V] = Constant::getNullValue(CommonType);
4151 return true;
4152 }
4153
4154 /// We have mapping between value A and other value B where B was a field in
4155 /// addressing mode represented by A. Also we have an original value C
4156 /// representing an address we start with. Traversing from C through phi and
4157 /// selects we ended up with A's in a map. This utility function tries to find
4158 /// a value V which is a field in addressing mode C and traversing through phi
4159 /// nodes and selects we will end up in corresponded values B in a map.
4160 /// The utility will create a new Phi/Selects if needed.
4161 // The simple example looks as follows:
4162 // BB1:
4163 // p1 = b1 + 40
4164 // br cond BB2, BB3
4165 // BB2:
4166 // p2 = b2 + 40
4167 // br BB3
4168 // BB3:
4169 // p = phi [p1, BB1], [p2, BB2]
4170 // v = load p
4171 // Map is
4172 // p1 -> b1
4173 // p2 -> b2
4174 // Request is
4175 // p -> ?
4176 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4177 Value *findCommon(FoldAddrToValueMapping &Map) {
4178 // Tracks the simplification of newly created phi nodes. The reason we use
4179 // this mapping is because we will add new created Phi nodes in AddrToBase.
4180 // Simplification of Phi nodes is recursive, so some Phi node may
4181 // be simplified after we added it to AddrToBase. In reality this
4182 // simplification is possible only if original phi/selects were not
4183 // simplified yet.
4184 // Using this mapping we can find the current value in AddrToBase.
4185 SimplificationTracker ST;
4186
4187 // First step, DFS to create PHI nodes for all intermediate blocks.
4188 // Also fill traverse order for the second step.
4189 SmallVector<Value *, 32> TraverseOrder;
4190 InsertPlaceholders(Map, TraverseOrder, ST);
4191
4192 // Second Step, fill new nodes by merged values and simplify if possible.
4193 FillPlaceholders(Map, TraverseOrder, ST);
4194
4195 if (!Opts.cgp_addr_sink_new_select && ST.countNewSelectNodes() > 0) {
4196 ST.destroyNewNodes(CommonType);
4197 return nullptr;
4198 }
4199
4200 // Now we'd like to match New Phi nodes to existed ones.
4201 unsigned PhiNotMatchedCount = 0;
4202 if (!MatchPhiSet(ST, Opts.cgp_addr_sink_new_phis, PhiNotMatchedCount)) {
4203 ST.destroyNewNodes(CommonType);
4204 return nullptr;
4205 }
4206
4207 auto *Result = ST.Get(Map.find(Original)->second);
4208 if (Result) {
4209 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4210 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4211 }
4212 return Result;
4213 }
4214
4215 /// Try to match PHI node to Candidate.
4216 /// Matcher tracks the matched Phi nodes.
4217 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4218 SmallSetVector<PHIPair, 8> &Matcher,
4219 PhiNodeSet &PhiNodesToMatch) {
4220 SmallVector<PHIPair, 8> WorkList;
4221 Matcher.insert({PHI, Candidate});
4222 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4223 MatchedPHIs.insert(PHI);
4224 WorkList.push_back({PHI, Candidate});
4225 SmallSet<PHIPair, 8> Visited;
4226 while (!WorkList.empty()) {
4227 auto Item = WorkList.pop_back_val();
4228 if (!Visited.insert(Item).second)
4229 continue;
4230 // We iterate over all incoming values to Phi to compare them.
4231 // If values are different and both of them Phi and the first one is a
4232 // Phi we added (subject to match) and both of them is in the same basic
4233 // block then we can match our pair if values match. So we state that
4234 // these values match and add it to work list to verify that.
4235 for (auto *B : Item.first->blocks()) {
4236 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
4237 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
4238 if (FirstValue == SecondValue)
4239 continue;
4240
4241 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
4242 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
4243
4244 // One of them is not Phi or
4245 // The first one is not Phi node from the set we'd like to match or
4246 // Phi nodes from different basic blocks then
4247 // we will not be able to match.
4248 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
4249 FirstPhi->getParent() != SecondPhi->getParent())
4250 return false;
4251
4252 // If we already matched them then continue.
4253 if (Matcher.count({FirstPhi, SecondPhi}))
4254 continue;
4255 // So the values are different and does not match. So we need them to
4256 // match. (But we register no more than one match per PHI node, so that
4257 // we won't later try to replace them twice.)
4258 if (MatchedPHIs.insert(FirstPhi).second)
4259 Matcher.insert({FirstPhi, SecondPhi});
4260 // But me must check it.
4261 WorkList.push_back({FirstPhi, SecondPhi});
4262 }
4263 }
4264 return true;
4265 }
4266
4267 /// For the given set of PHI nodes (in the SimplificationTracker) try
4268 /// to find their equivalents.
4269 /// Returns false if this matching fails and creation of new Phi is disabled.
4270 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4271 unsigned &PhiNotMatchedCount) {
4272 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4273 // order, so the replacements (ReplacePhi) are also done in a deterministic
4274 // order.
4275 SmallSetVector<PHIPair, 8> Matched;
4276 SmallPtrSet<PHINode *, 8> WillNotMatch;
4277 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4278 while (PhiNodesToMatch.size()) {
4279 PHINode *PHI = *PhiNodesToMatch.begin();
4280
4281 // Add us, if no Phi nodes in the basic block we do not match.
4282 WillNotMatch.clear();
4283 WillNotMatch.insert(PHI);
4284
4285 // Traverse all Phis until we found equivalent or fail to do that.
4286 bool IsMatched = false;
4287 for (auto &P : PHI->getParent()->phis()) {
4288 // Skip new Phi nodes.
4289 if (PhiNodesToMatch.count(&P))
4290 continue;
4291 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
4292 break;
4293 // If it does not match, collect all Phi nodes from matcher.
4294 // if we end up with no match, them all these Phi nodes will not match
4295 // later.
4296 WillNotMatch.insert_range(llvm::make_first_range(Matched));
4297 Matched.clear();
4298 }
4299 if (IsMatched) {
4300 // Replace all matched values and erase them.
4301 for (auto MV : Matched)
4302 ST.ReplacePhi(MV.first, MV.second);
4303 Matched.clear();
4304 continue;
4305 }
4306 // If we are not allowed to create new nodes then bail out.
4307 if (!AllowNewPhiNodes)
4308 return false;
4309 // Just remove all seen values in matcher. They will not match anything.
4310 PhiNotMatchedCount += WillNotMatch.size();
4311 for (auto *P : WillNotMatch)
4312 PhiNodesToMatch.erase(P);
4313 }
4314 return true;
4315 }
4316 /// Fill the placeholders with values from predecessors and simplify them.
4317 void FillPlaceholders(FoldAddrToValueMapping &Map,
4318 SmallVectorImpl<Value *> &TraverseOrder,
4319 SimplificationTracker &ST) {
4320 while (!TraverseOrder.empty()) {
4321 Value *Current = TraverseOrder.pop_back_val();
4322 assert(Map.contains(Current) && "No node to fill!!!");
4323 Value *V = Map[Current];
4324
4325 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
4326 // CurrentValue also must be Select.
4327 auto *CurrentSelect = cast<SelectInst>(Current);
4328 auto *TrueValue = CurrentSelect->getTrueValue();
4329 assert(Map.contains(TrueValue) && "No True Value!");
4330 Select->setTrueValue(ST.Get(Map[TrueValue]));
4331 auto *FalseValue = CurrentSelect->getFalseValue();
4332 assert(Map.contains(FalseValue) && "No False Value!");
4333 Select->setFalseValue(ST.Get(Map[FalseValue]));
4334 } else {
4335 // Must be a Phi node then.
4336 auto *PHI = cast<PHINode>(V);
4337 // Fill the Phi node with values from predecessors.
4338 for (auto *B : predecessors(PHI->getParent())) {
4339 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
4340 assert(Map.contains(PV) && "No predecessor Value!");
4341 PHI->addIncoming(ST.Get(Map[PV]), B);
4342 }
4343 }
4344 }
4345 }
4346
4347 /// Starting from original value recursively iterates over def-use chain up to
4348 /// known ending values represented in a map. For each traversed phi/select
4349 /// inserts a placeholder Phi or Select.
4350 /// Reports all new created Phi/Select nodes by adding them to set.
4351 /// Also reports and order in what values have been traversed.
4352 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4353 SmallVectorImpl<Value *> &TraverseOrder,
4354 SimplificationTracker &ST) {
4355 SmallVector<Value *, 32> Worklist;
4356 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4357 "Address must be a Phi or Select node");
4358 auto *Dummy = PoisonValue::get(CommonType);
4359 Worklist.push_back(Original);
4360 while (!Worklist.empty()) {
4361 Value *Current = Worklist.pop_back_val();
4362 // if it is already visited or it is an ending value then skip it.
4363 if (Map.contains(Current))
4364 continue;
4365 TraverseOrder.push_back(Current);
4366
4367 // CurrentValue must be a Phi node or select. All others must be covered
4368 // by anchors.
4369 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
4370 // Is it OK to get metadata from OrigSelect?!
4371 // Create a Select placeholder with dummy value.
4372 SelectInst *Select =
4373 SelectInst::Create(CurrentSelect->getCondition(), Dummy, Dummy,
4374 CurrentSelect->getName(),
4375 CurrentSelect->getIterator(), CurrentSelect);
4376 Map[Current] = Select;
4377 ST.insertNewSelect(Select);
4378 // We are interested in True and False values.
4379 Worklist.push_back(CurrentSelect->getTrueValue());
4380 Worklist.push_back(CurrentSelect->getFalseValue());
4381 } else {
4382 // It must be a Phi node then.
4383 PHINode *CurrentPhi = cast<PHINode>(Current);
4384 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4385 PHINode *PHI =
4386 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi->getIterator());
4387 Map[Current] = PHI;
4388 ST.insertNewPhi(PHI);
4389 append_range(Worklist, CurrentPhi->incoming_values());
4390 }
4391 }
4392 }
4393
4394 bool addrModeCombiningAllowed() {
4395 if (!Opts.cgp_complex_addr_modes)
4396 return false;
4397 switch (DifferentField) {
4398 default:
4399 return false;
4400 case ExtAddrMode::BaseRegField:
4401 return Opts.cgp_addr_sink_combine_base_reg;
4402 case ExtAddrMode::BaseGVField:
4403 return Opts.cgp_addr_sink_combine_base_gv;
4404 case ExtAddrMode::BaseOffsField:
4405 return Opts.cgp_addr_sink_combine_base_offs;
4406 case ExtAddrMode::ScaledRegField:
4407 return Opts.cgp_addr_sink_combine_scaled_reg;
4408 }
4409 }
4410};
4411} // end anonymous namespace
4412
4413/// Try adding ScaleReg*Scale to the current addressing mode.
4414/// Return true and update AddrMode if this addr mode is legal for the target,
4415/// false if not.
4416bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4417 unsigned Depth) {
4418 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4419 // mode. Just process that directly.
4420 if (Scale == 1)
4421 return matchAddr(ScaleReg, Depth);
4422
4423 // If the scale is 0, it takes nothing to add this.
4424 if (Scale == 0)
4425 return true;
4426
4427 // If we already have a scale of this value, we can add to it, otherwise, we
4428 // need an available scale field.
4429 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4430 return false;
4431
4432 ExtAddrMode TestAddrMode = AddrMode;
4433
4434 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4435 // [A+B + A*7] -> [B+A*8].
4436 TestAddrMode.Scale += Scale;
4437 TestAddrMode.ScaledReg = ScaleReg;
4438
4439 // If the new address isn't legal, bail out.
4440 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
4441 return false;
4442
4443 // It was legal, so commit it.
4444 AddrMode = TestAddrMode;
4445
4446 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4447 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4448 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4449 // go any further: we can reuse it and cannot eliminate it.
4450 ConstantInt *CI = nullptr;
4451 Value *AddLHS = nullptr;
4452 if (isa<Instruction>(ScaleReg) && // not a constant expr.
4453 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
4454 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
4455 TestAddrMode.InBounds = false;
4456 TestAddrMode.ScaledReg = AddLHS;
4457 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4458
4459 // If this addressing mode is legal, commit it and remember that we folded
4460 // this instruction.
4461 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
4462 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
4463 AddrMode = TestAddrMode;
4464 return true;
4465 }
4466 // Restore status quo.
4467 TestAddrMode = AddrMode;
4468 }
4469
4470 // If this is an add recurrence with a constant step, return the increment
4471 // instruction and the canonicalized step.
4472 auto GetConstantStep =
4473 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4474 auto *PN = dyn_cast<PHINode>(V);
4475 if (!PN)
4476 return std::nullopt;
4477 auto IVInc = getIVIncrement(PN, &LI);
4478 if (!IVInc)
4479 return std::nullopt;
4480 // TODO: The result of the intrinsics above is two-complement. However when
4481 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4482 // If it has nuw or nsw flags, we need to make sure that these flags are
4483 // inferrable at the point of memory instruction. Otherwise we are replacing
4484 // well-defined two-complement computation with poison. Currently, to avoid
4485 // potentially complex analysis needed to prove this, we reject such cases.
4486 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
4487 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4488 return std::nullopt;
4489 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
4490 return std::make_pair(IVInc->first, ConstantStep->getValue());
4491 return std::nullopt;
4492 };
4493
4494 // Try to account for the following special case:
4495 // 1. ScaleReg is an inductive variable;
4496 // 2. We use it with non-zero offset;
4497 // 3. IV's increment is available at the point of memory instruction.
4498 //
4499 // In this case, we may reuse the IV increment instead of the IV Phi to
4500 // achieve the following advantages:
4501 // 1. If IV step matches the offset, we will have no need in the offset;
4502 // 2. Even if they don't match, we will reduce the overlap of living IV
4503 // and IV increment, that will potentially lead to better register
4504 // assignment.
4505 if (AddrMode.BaseOffs) {
4506 if (auto IVStep = GetConstantStep(ScaleReg)) {
4507 Instruction *IVInc = IVStep->first;
4508 // The following assert is important to ensure a lack of infinite loops.
4509 // This transforms is (intentionally) the inverse of the one just above.
4510 // If they don't agree on the definition of an increment, we'd alternate
4511 // back and forth indefinitely.
4512 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4513 APInt Step = IVStep->second;
4514 APInt Offset = Step * AddrMode.Scale;
4515 if (Offset.isSignedIntN(64)) {
4516 TestAddrMode.InBounds = false;
4517 TestAddrMode.ScaledReg = IVInc;
4518 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4519 // If this addressing mode is legal, commit it..
4520 // (Note that we defer the (expensive) domtree base legality check
4521 // to the very last possible point.)
4522 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
4523 getDTFn().dominates(IVInc, MemoryInst)) {
4524 AddrModeInsts.push_back(cast<Instruction>(IVInc));
4525 AddrMode = TestAddrMode;
4526 return true;
4527 }
4528 // Restore status quo.
4529 TestAddrMode = AddrMode;
4530 }
4531 }
4532 }
4533
4534 // Otherwise, just return what we have.
4535 return true;
4536}
4537
4538/// This is a little filter, which returns true if an addressing computation
4539/// involving I might be folded into a load/store accessing it.
4540/// This doesn't need to be perfect, but needs to accept at least
4541/// the set of instructions that MatchOperationAddr can.
4543 switch (I->getOpcode()) {
4544 case Instruction::BitCast:
4545 case Instruction::AddrSpaceCast:
4546 // Don't touch identity bitcasts.
4547 if (I->getType() == I->getOperand(0)->getType())
4548 return false;
4549 return I->getType()->isIntOrPtrTy();
4550 case Instruction::PtrToInt:
4551 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4552 return true;
4553 case Instruction::IntToPtr:
4554 // We know the input is intptr_t, so this is foldable.
4555 return true;
4556 case Instruction::Add:
4557 return true;
4558 case Instruction::Or:
4559 return cast<PossiblyDisjointInst>(I)->isDisjoint();
4560 case Instruction::Mul:
4561 case Instruction::Shl:
4562 // Can only handle X*C and X << C.
4563 return isa<ConstantInt>(I->getOperand(1));
4564 case Instruction::GetElementPtr:
4565 return true;
4566 default:
4567 return false;
4568 }
4569}
4570
4571/// Check whether or not \p Val is a legal instruction for \p TLI.
4572/// \note \p Val is assumed to be the product of some type promotion.
4573/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4574/// to be legal, as the non-promoted value would have had the same state.
4576 const DataLayout &DL, Value *Val) {
4577 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4578 if (!PromotedInst)
4579 return false;
4580 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4581 // If the ISDOpcode is undefined, it was undefined before the promotion.
4582 if (!ISDOpcode)
4583 return true;
4584 // Otherwise, check if the promoted instruction is legal or not.
4585 return TLI.isOperationLegalOrCustom(
4586 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4587}
4588
4589namespace {
4590
4591/// Hepler class to perform type promotion.
4592class TypePromotionHelper {
4593 /// Utility function to add a promoted instruction \p ExtOpnd to
4594 /// \p PromotedInsts and record the type of extension we have seen.
4595 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4596 Instruction *ExtOpnd, bool IsSExt) {
4597 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4598 auto [It, Inserted] = PromotedInsts.try_emplace(ExtOpnd);
4599 if (!Inserted) {
4600 // If the new extension is same as original, the information in
4601 // PromotedInsts[ExtOpnd] is still correct.
4602 if (It->second.getInt() == ExtTy)
4603 return;
4604
4605 // Now the new extension is different from old extension, we make
4606 // the type information invalid by setting extension type to
4607 // BothExtension.
4608 ExtTy = BothExtension;
4609 }
4610 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4611 }
4612
4613 /// Utility function to query the original type of instruction \p Opnd
4614 /// with a matched extension type. If the extension doesn't match, we
4615 /// cannot use the information we had on the original type.
4616 /// BothExtension doesn't match any extension type.
4617 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4618 Instruction *Opnd, bool IsSExt) {
4619 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4620 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4621 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4622 return It->second.getPointer();
4623 return nullptr;
4624 }
4625
4626 /// Utility function to check whether or not a sign or zero extension
4627 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4628 /// either using the operands of \p Inst or promoting \p Inst.
4629 /// The type of the extension is defined by \p IsSExt.
4630 /// In other words, check if:
4631 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4632 /// #1 Promotion applies:
4633 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4634 /// #2 Operand reuses:
4635 /// ext opnd1 to ConsideredExtType.
4636 /// \p PromotedInsts maps the instructions to their type before promotion.
4637 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4638 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4639
4640 /// Utility function to determine if \p OpIdx should be promoted when
4641 /// promoting \p Inst.
4642 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4643 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4644 }
4645
4646 /// Utility function to promote the operand of \p Ext when this
4647 /// operand is a promotable trunc or sext or zext.
4648 /// \p PromotedInsts maps the instructions to their type before promotion.
4649 /// \p CreatedInstsCost[out] contains the cost of all instructions
4650 /// created to promote the operand of Ext.
4651 /// Newly added extensions are inserted in \p Exts.
4652 /// Newly added truncates are inserted in \p Truncs.
4653 /// Should never be called directly.
4654 /// \return The promoted value which is used instead of Ext.
4655 static Value *promoteOperandForTruncAndAnyExt(
4656 Instruction *Ext, TypePromotionTransaction &TPT,
4657 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4658 SmallVectorImpl<Instruction *> *Exts,
4659 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4660
4661 /// Utility function to promote the operand of \p Ext when this
4662 /// operand is promotable and is not a supported trunc or sext.
4663 /// \p PromotedInsts maps the instructions to their type before promotion.
4664 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4665 /// created to promote the operand of Ext.
4666 /// Newly added extensions are inserted in \p Exts.
4667 /// Newly added truncates are inserted in \p Truncs.
4668 /// Should never be called directly.
4669 /// \return The promoted value which is used instead of Ext.
4670 static Value *promoteOperandForOther(Instruction *Ext,
4671 TypePromotionTransaction &TPT,
4672 InstrToOrigTy &PromotedInsts,
4673 unsigned &CreatedInstsCost,
4674 SmallVectorImpl<Instruction *> *Exts,
4675 SmallVectorImpl<Instruction *> *Truncs,
4676 const TargetLowering &TLI, bool IsSExt);
4677
4678 /// \see promoteOperandForOther.
4679 static Value *signExtendOperandForOther(
4680 Instruction *Ext, TypePromotionTransaction &TPT,
4681 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4682 SmallVectorImpl<Instruction *> *Exts,
4683 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4684 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4685 Exts, Truncs, TLI, true);
4686 }
4687
4688 /// \see promoteOperandForOther.
4689 static Value *zeroExtendOperandForOther(
4690 Instruction *Ext, TypePromotionTransaction &TPT,
4691 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4692 SmallVectorImpl<Instruction *> *Exts,
4693 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4694 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4695 Exts, Truncs, TLI, false);
4696 }
4697
4698public:
4699 /// Type for the utility function that promotes the operand of Ext.
4700 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4701 InstrToOrigTy &PromotedInsts,
4702 unsigned &CreatedInstsCost,
4703 SmallVectorImpl<Instruction *> *Exts,
4704 SmallVectorImpl<Instruction *> *Truncs,
4705 const TargetLowering &TLI);
4706
4707 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4708 /// action to promote the operand of \p Ext instead of using Ext.
4709 /// \return NULL if no promotable action is possible with the current
4710 /// sign extension.
4711 /// \p InsertedInsts keeps track of all the instructions inserted by the
4712 /// other CodeGenPrepare optimizations. This information is important
4713 /// because we do not want to promote these instructions as CodeGenPrepare
4714 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4715 /// \p PromotedInsts maps the instructions to their type before promotion.
4716 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4717 const TargetLowering &TLI,
4718 const InstrToOrigTy &PromotedInsts);
4719};
4720
4721} // end anonymous namespace
4722
4723bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4724 Type *ConsideredExtType,
4725 const InstrToOrigTy &PromotedInsts,
4726 bool IsSExt) {
4727 // The promotion helper does not know how to deal with vector types yet.
4728 // To be able to fix that, we would need to fix the places where we
4729 // statically extend, e.g., constants and such.
4730 if (Inst->getType()->isVectorTy())
4731 return false;
4732
4733 // We can always get through zext.
4734 if (isa<ZExtInst>(Inst))
4735 return true;
4736
4737 // sext(sext) is ok too.
4738 if (IsSExt && isa<SExtInst>(Inst))
4739 return true;
4740
4741 // We can get through binary operator, if it is legal. In other words, the
4742 // binary operator must have a nuw or nsw flag.
4743 if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
4744 if (isa<OverflowingBinaryOperator>(BinOp) &&
4745 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4746 (IsSExt && BinOp->hasNoSignedWrap())))
4747 return true;
4748
4749 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4750 if ((Inst->getOpcode() == Instruction::And ||
4751 Inst->getOpcode() == Instruction::Or))
4752 return true;
4753
4754 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4755 if (Inst->getOpcode() == Instruction::Xor) {
4756 // Make sure it is not a NOT.
4757 if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
4758 if (!Cst->getValue().isAllOnes())
4759 return true;
4760 }
4761
4762 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4763 // It may change a poisoned value into a regular value, like
4764 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4765 // poisoned value regular value
4766 // It should be OK since undef covers valid value.
4767 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4768 return true;
4769
4770 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4771 // It may change a poisoned value into a regular value, like
4772 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4773 // poisoned value regular value
4774 // It should be OK since undef covers valid value.
4775 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4776 const auto *ExtInst = *Inst->user_begin();
4777 if (ExtInst->hasOneUse()) {
4778 const auto *AndInst = *ExtInst->user_begin();
4779 if (AndInst->getOpcode() == Instruction::And) {
4780 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4781 if (Cst &&
4782 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4783 return true;
4784 }
4785 }
4786 }
4787
4788 // Check if we can do the following simplification.
4789 // ext(trunc(opnd)) --> ext(opnd)
4790 if (!isa<TruncInst>(Inst))
4791 return false;
4792
4793 Value *OpndVal = Inst->getOperand(0);
4794 // Check if we can use this operand in the extension.
4795 // If the type is larger than the result type of the extension, we cannot.
4796 if (!OpndVal->getType()->isIntegerTy() ||
4797 OpndVal->getType()->getIntegerBitWidth() >
4798 ConsideredExtType->getIntegerBitWidth())
4799 return false;
4800
4801 // If the operand of the truncate is not an instruction, we will not have
4802 // any information on the dropped bits.
4803 // (Actually we could for constant but it is not worth the extra logic).
4804 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4805 if (!Opnd)
4806 return false;
4807
4808 // Check if the source of the type is narrow enough.
4809 // I.e., check that trunc just drops extended bits of the same kind of
4810 // the extension.
4811 // #1 get the type of the operand and check the kind of the extended bits.
4812 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4813 if (OpndType)
4814 ;
4815 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4816 OpndType = Opnd->getOperand(0)->getType();
4817 else
4818 return false;
4819
4820 // #2 check that the truncate just drops extended bits.
4821 return Inst->getType()->getIntegerBitWidth() >=
4822 OpndType->getIntegerBitWidth();
4823}
4824
4825TypePromotionHelper::Action TypePromotionHelper::getAction(
4826 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4827 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4828 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4829 "Unexpected instruction type");
4830 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4831 Type *ExtTy = Ext->getType();
4832 bool IsSExt = isa<SExtInst>(Ext);
4833 // If the operand of the extension is not an instruction, we cannot
4834 // get through.
4835 // If it, check we can get through.
4836 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4837 return nullptr;
4838
4839 // Do not promote if the operand has been added by codegenprepare.
4840 // Otherwise, it means we are undoing an optimization that is likely to be
4841 // redone, thus causing potential infinite loop.
4842 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4843 return nullptr;
4844
4845 // SExt or Trunc instructions.
4846 // Return the related handler.
4847 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4848 isa<ZExtInst>(ExtOpnd))
4849 return promoteOperandForTruncAndAnyExt;
4850
4851 // Regular instruction.
4852 // Abort early if we will have to insert non-free instructions.
4853 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4854 return nullptr;
4855 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4856}
4857
4858Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4859 Instruction *SExt, TypePromotionTransaction &TPT,
4860 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4861 SmallVectorImpl<Instruction *> *Exts,
4862 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4863 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4864 // get through it and this method should not be called.
4865 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4866 Value *ExtVal = SExt;
4867 bool HasMergedNonFreeExt = false;
4868 if (isa<ZExtInst>(SExtOpnd)) {
4869 // Replace s|zext(zext(opnd))
4870 // => zext(opnd).
4871 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4872 Value *ZExt =
4873 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4874 TPT.replaceAllUsesWith(SExt, ZExt);
4875 TPT.eraseInstruction(SExt);
4876 ExtVal = ZExt;
4877 } else {
4878 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4879 // => z|sext(opnd).
4880 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4881 }
4882 CreatedInstsCost = 0;
4883
4884 // Remove dead code.
4885 if (SExtOpnd->use_empty())
4886 TPT.eraseInstruction(SExtOpnd);
4887
4888 // Check if the extension is still needed.
4889 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4890 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4891 if (ExtInst) {
4892 if (Exts)
4893 Exts->push_back(ExtInst);
4894 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4895 }
4896 return ExtVal;
4897 }
4898
4899 // At this point we have: ext ty opnd to ty.
4900 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4901 Value *NextVal = ExtInst->getOperand(0);
4902 TPT.eraseInstruction(ExtInst, NextVal);
4903 return NextVal;
4904}
4905
4906Value *TypePromotionHelper::promoteOperandForOther(
4907 Instruction *Ext, TypePromotionTransaction &TPT,
4908 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4909 SmallVectorImpl<Instruction *> *Exts,
4910 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4911 bool IsSExt) {
4912 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4913 // get through it and this method should not be called.
4914 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4915 CreatedInstsCost = 0;
4916 if (!ExtOpnd->hasOneUse()) {
4917 // ExtOpnd will be promoted.
4918 // All its uses, but Ext, will need to use a truncated value of the
4919 // promoted version.
4920 // Create the truncate now.
4921 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4922 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4923 // Insert it just after the definition.
4924 ITrunc->moveAfter(ExtOpnd);
4925 if (Truncs)
4926 Truncs->push_back(ITrunc);
4927 }
4928
4929 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4930 // Restore the operand of Ext (which has been replaced by the previous call
4931 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4932 TPT.setOperand(Ext, 0, ExtOpnd);
4933 }
4934
4935 // Get through the Instruction:
4936 // 1. Update its type.
4937 // 2. Replace the uses of Ext by Inst.
4938 // 3. Extend each operand that needs to be extended.
4939
4940 // Remember the original type of the instruction before promotion.
4941 // This is useful to know that the high bits are sign extended bits.
4942 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4943 // Step #1.
4944 TPT.mutateType(ExtOpnd, Ext->getType());
4945 // Step #2.
4946 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4947 // Step #3.
4948 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
4949 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4950 ++OpIdx) {
4951 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
4952 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4953 !shouldExtOperand(ExtOpnd, OpIdx)) {
4954 LLVM_DEBUG(dbgs() << "No need to propagate\n");
4955 continue;
4956 }
4957 // Check if we can statically extend the operand.
4958 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4959 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4960 LLVM_DEBUG(dbgs() << "Statically extend\n");
4961 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4962 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4963 : Cst->getValue().zext(BitWidth);
4964 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4965 continue;
4966 }
4967 // UndefValue are typed, so we have to statically sign extend them.
4968 if (isa<UndefValue>(Opnd)) {
4969 LLVM_DEBUG(dbgs() << "Statically extend\n");
4970 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4971 continue;
4972 }
4973
4974 // Otherwise we have to explicitly sign extend the operand.
4975 Value *ValForExtOpnd = IsSExt
4976 ? TPT.createSExt(ExtOpnd, Opnd, Ext->getType())
4977 : TPT.createZExt(ExtOpnd, Opnd, Ext->getType());
4978 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4979 Instruction *InstForExtOpnd = dyn_cast<Instruction>(ValForExtOpnd);
4980 if (!InstForExtOpnd)
4981 continue;
4982
4983 if (Exts)
4984 Exts->push_back(InstForExtOpnd);
4985
4986 CreatedInstsCost += !TLI.isExtFree(InstForExtOpnd);
4987 }
4988 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
4989 TPT.eraseInstruction(Ext);
4990 return ExtOpnd;
4991}
4992
4993/// Check whether or not promoting an instruction to a wider type is profitable.
4994/// \p NewCost gives the cost of extension instructions created by the
4995/// promotion.
4996/// \p OldCost gives the cost of extension instructions before the promotion
4997/// plus the number of instructions that have been
4998/// matched in the addressing mode the promotion.
4999/// \p PromotedOperand is the value that has been promoted.
5000/// \return True if the promotion is profitable, false otherwise.
5001bool AddressingModeMatcher::isPromotionProfitable(
5002 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5003 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5004 << '\n');
5005 // The cost of the new extensions is greater than the cost of the
5006 // old extension plus what we folded.
5007 // This is not profitable.
5008 if (NewCost > OldCost)
5009 return false;
5010 if (NewCost < OldCost)
5011 return true;
5012 // The promotion is neutral but it may help folding the sign extension in
5013 // loads for instance.
5014 // Check that we did not create an illegal instruction.
5015 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
5016}
5017
5018/// Given an instruction or constant expr, see if we can fold the operation
5019/// into the addressing mode. If so, update the addressing mode and return
5020/// true, otherwise return false without modifying AddrMode.
5021/// If \p MovedAway is not NULL, it contains the information of whether or
5022/// not AddrInst has to be folded into the addressing mode on success.
5023/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5024/// because it has been moved away.
5025/// Thus AddrInst must not be added in the matched instructions.
5026/// This state can happen when AddrInst is a sext, since it may be moved away.
5027/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5028/// not be referenced anymore.
5029bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5030 unsigned Depth,
5031 bool *MovedAway) {
5032 // Avoid exponential behavior on extremely deep expression trees.
5033 if (Depth >= 5)
5034 return false;
5035
5036 // By default, all matched instructions stay in place.
5037 if (MovedAway)
5038 *MovedAway = false;
5039
5040 switch (Opcode) {
5041 case Instruction::PtrToInt:
5042 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5043 return matchAddr(AddrInst->getOperand(0), Depth);
5044 case Instruction::IntToPtr: {
5045 auto AS = AddrInst->getType()->getPointerAddressSpace();
5046 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
5047 // This inttoptr is a no-op if the integer type is pointer sized.
5048 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
5049 return matchAddr(AddrInst->getOperand(0), Depth);
5050 return false;
5051 }
5052 case Instruction::BitCast:
5053 // BitCast is always a noop, and we can handle it as long as it is
5054 // int->int or pointer->pointer (we don't want int<->fp or something).
5055 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
5056 // Don't touch identity bitcasts. These were probably put here by LSR,
5057 // and we don't want to mess around with them. Assume it knows what it
5058 // is doing.
5059 AddrInst->getOperand(0)->getType() != AddrInst->getType())
5060 return matchAddr(AddrInst->getOperand(0), Depth);
5061 return false;
5062 case Instruction::AddrSpaceCast: {
5063 unsigned SrcAS =
5064 AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
5065 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5066 if (TLI.getTargetMachine().isNoopAddrSpaceCast(DL, SrcAS, DestAS))
5067 return matchAddr(AddrInst->getOperand(0), Depth);
5068 return false;
5069 }
5070 case Instruction::Or:
5071 if (!cast<PossiblyDisjointInst>(AddrInst)->isDisjoint())
5072 return false;
5073 [[fallthrough]];
5074 case Instruction::Add: {
5075 // Check to see if we can merge in one operand, then the other. If so, we
5076 // win.
5077 ExtAddrMode BackupAddrMode = AddrMode;
5078 unsigned OldSize = AddrModeInsts.size();
5079 // Start a transaction at this point.
5080 // The LHS may match but not the RHS.
5081 // Therefore, we need a higher level restoration point to undo partially
5082 // matched operation.
5083 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5084 TPT.getRestorationPoint();
5085
5086 // Try to match an integer constant second to increase its chance of ending
5087 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5088 int First = 0, Second = 1;
5089 if (isa<ConstantInt>(AddrInst->getOperand(First))
5090 && !isa<ConstantInt>(AddrInst->getOperand(Second)))
5091 std::swap(First, Second);
5092 AddrMode.InBounds = false;
5093 if (matchAddr(AddrInst->getOperand(First), Depth + 1) &&
5094 matchAddr(AddrInst->getOperand(Second), Depth + 1))
5095 return true;
5096
5097 // Restore the old addr mode info.
5098 AddrMode = BackupAddrMode;
5099 AddrModeInsts.resize(OldSize);
5100 TPT.rollback(LastKnownGood);
5101
5102 // Otherwise this was over-aggressive. Try merging operands in the opposite
5103 // order.
5104 if (matchAddr(AddrInst->getOperand(Second), Depth + 1) &&
5105 matchAddr(AddrInst->getOperand(First), Depth + 1))
5106 return true;
5107
5108 // Otherwise we definitely can't merge the ADD in.
5109 AddrMode = BackupAddrMode;
5110 AddrModeInsts.resize(OldSize);
5111 TPT.rollback(LastKnownGood);
5112 break;
5113 }
5114 case Instruction::Mul:
5115 case Instruction::Shl: {
5116 // Can only handle X*C and X << C.
5117 AddrMode.InBounds = false;
5118 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
5119 if (!RHS || RHS->getBitWidth() > 64)
5120 return false;
5121 int64_t Scale = Opcode == Instruction::Shl
5122 ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
5123 : RHS->getSExtValue();
5124
5125 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
5126 }
5127 case Instruction::GetElementPtr: {
5128 // Scan the GEP. We check it if it contains constant offsets and at most
5129 // one variable offset.
5130 int VariableOperand = -1;
5131 unsigned VariableScale = 0;
5132
5133 int64_t ConstantOffset = 0;
5134 gep_type_iterator GTI = gep_type_begin(AddrInst);
5135 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5136 if (StructType *STy = GTI.getStructTypeOrNull()) {
5137 const StructLayout *SL = DL.getStructLayout(STy);
5138 unsigned Idx =
5139 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
5140 ConstantOffset += SL->getElementOffset(Idx);
5141 } else {
5142 TypeSize TS = GTI.getSequentialElementStride(DL);
5143 if (TS.isNonZero()) {
5144 // The optimisations below currently only work for fixed offsets.
5145 if (TS.isScalable())
5146 return false;
5147 int64_t TypeSize = TS.getFixedValue();
5148 if (ConstantInt *CI =
5149 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
5150 const APInt &CVal = CI->getValue();
5151 if (CVal.getSignificantBits() <= 64) {
5152 ConstantOffset += CVal.getSExtValue() * TypeSize;
5153 continue;
5154 }
5155 }
5156 // We only allow one variable index at the moment.
5157 if (VariableOperand != -1)
5158 return false;
5159
5160 // Remember the variable index.
5161 VariableOperand = i;
5162 VariableScale = TypeSize;
5163 }
5164 }
5165 }
5166
5167 // A common case is for the GEP to only do a constant offset. In this case,
5168 // just add it to the disp field and check validity.
5169 if (VariableOperand == -1) {
5170 AddrMode.BaseOffs += ConstantOffset;
5171 if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5172 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5173 AddrMode.InBounds = false;
5174 return true;
5175 }
5176 AddrMode.BaseOffs -= ConstantOffset;
5177
5178 if (Opts.cgp_split_large_offset_gep && isa<GetElementPtrInst>(AddrInst) &&
5180 ConstantOffset != 0) {
5181 // Record GEPs with non-zero offsets as candidates for splitting in
5182 // the event that the offset cannot fit into the r+i addressing mode.
5183 // Simple and common case that only one GEP is used in calculating the
5184 // address for the memory access.
5185 Value *Base = AddrInst->getOperand(0);
5186 auto *BaseI = dyn_cast<Instruction>(Base);
5187 auto *GEP = cast<GetElementPtrInst>(AddrInst);
5189 (BaseI && !isa<CastInst>(BaseI) &&
5190 !isa<GetElementPtrInst>(BaseI))) {
5191 // Make sure the parent block allows inserting non-PHI instructions
5192 // before the terminator.
5193 BasicBlock *Parent =
5194 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
5195 if (!Parent->getTerminator()->isEHPad())
5196 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
5197 }
5198 }
5199
5200 return false;
5201 }
5202
5203 // Save the valid addressing mode in case we can't match.
5204 ExtAddrMode BackupAddrMode = AddrMode;
5205 unsigned OldSize = AddrModeInsts.size();
5206
5207 // See if the scale and offset amount is valid for this target.
5208 AddrMode.BaseOffs += ConstantOffset;
5209 if (!cast<GEPOperator>(AddrInst)->isInBounds())
5210 AddrMode.InBounds = false;
5211
5212 // Match the base operand of the GEP.
5213 if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
5214 // If it couldn't be matched, just stuff the value in a register.
5215 if (AddrMode.HasBaseReg) {
5216 AddrMode = BackupAddrMode;
5217 AddrModeInsts.resize(OldSize);
5218 return false;
5219 }
5220 AddrMode.HasBaseReg = true;
5221 AddrMode.BaseReg = AddrInst->getOperand(0);
5222 }
5223
5224 // Match the remaining variable portion of the GEP.
5225 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
5226 Depth)) {
5227 // If it couldn't be matched, try stuffing the base into a register
5228 // instead of matching it, and retrying the match of the scale.
5229 AddrMode = BackupAddrMode;
5230 AddrModeInsts.resize(OldSize);
5231 if (AddrMode.HasBaseReg)
5232 return false;
5233 AddrMode.HasBaseReg = true;
5234 AddrMode.BaseReg = AddrInst->getOperand(0);
5235 AddrMode.BaseOffs += ConstantOffset;
5236 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
5237 VariableScale, Depth)) {
5238 // If even that didn't work, bail.
5239 AddrMode = BackupAddrMode;
5240 AddrModeInsts.resize(OldSize);
5241 return false;
5242 }
5243 }
5244
5245 return true;
5246 }
5247 case Instruction::SExt:
5248 case Instruction::ZExt: {
5249 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
5250 if (!Ext)
5251 return false;
5252
5253 // Try to move this ext out of the way of the addressing mode.
5254 // Ask for a method for doing so.
5255 TypePromotionHelper::Action TPH =
5256 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5257 if (!TPH)
5258 return false;
5259
5260 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5261 TPT.getRestorationPoint();
5262 unsigned CreatedInstsCost = 0;
5263 unsigned ExtCost = !TLI.isExtFree(Ext);
5264 Value *PromotedOperand =
5265 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5266 // SExt has been moved away.
5267 // Thus either it will be rematched later in the recursive calls or it is
5268 // gone. Anyway, we must not fold it into the addressing mode at this point.
5269 // E.g.,
5270 // op = add opnd, 1
5271 // idx = ext op
5272 // addr = gep base, idx
5273 // is now:
5274 // promotedOpnd = ext opnd <- no match here
5275 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5276 // addr = gep base, op <- match
5277 if (MovedAway)
5278 *MovedAway = true;
5279
5280 assert(PromotedOperand &&
5281 "TypePromotionHelper should have filtered out those cases");
5282
5283 ExtAddrMode BackupAddrMode = AddrMode;
5284 unsigned OldSize = AddrModeInsts.size();
5285
5286 if (!matchAddr(PromotedOperand, Depth) ||
5287 // The total of the new cost is equal to the cost of the created
5288 // instructions.
5289 // The total of the old cost is equal to the cost of the extension plus
5290 // what we have saved in the addressing mode.
5291 !isPromotionProfitable(CreatedInstsCost,
5292 ExtCost + (AddrModeInsts.size() - OldSize),
5293 PromotedOperand)) {
5294 AddrMode = BackupAddrMode;
5295 AddrModeInsts.resize(OldSize);
5296 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5297 TPT.rollback(LastKnownGood);
5298 return false;
5299 }
5300
5301 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5302 AddrMode.replaceWith(Ext, PromotedOperand);
5303 return true;
5304 }
5305 case Instruction::Call:
5306 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(AddrInst)) {
5307 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5308 GlobalValue &GV = cast<GlobalValue>(*II->getArgOperand(0));
5310 return matchAddr(AddrInst->getOperand(0), Depth);
5311 }
5312 }
5313 break;
5314 }
5315 return false;
5316}
5317
5318/// If we can, try to add the value of 'Addr' into the current addressing mode.
5319/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5320/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5321/// for the target.
5322///
5323bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5324 // Start a transaction at this point that we will rollback if the matching
5325 // fails.
5326 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5327 TPT.getRestorationPoint();
5328 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
5329 if (CI->getValue().isSignedIntN(64)) {
5330 // Check if the addition would result in a signed overflow.
5331 int64_t Result;
5332 bool Overflow =
5333 AddOverflow(AddrMode.BaseOffs, CI->getSExtValue(), Result);
5334 if (!Overflow) {
5335 // Fold in immediates if legal for the target.
5336 AddrMode.BaseOffs = Result;
5337 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5338 return true;
5339 AddrMode.BaseOffs -= CI->getSExtValue();
5340 }
5341 }
5342 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
5343 // If this is a global variable, try to fold it into the addressing mode.
5344 if (!AddrMode.BaseGV) {
5345 AddrMode.BaseGV = GV;
5346 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5347 return true;
5348 AddrMode.BaseGV = nullptr;
5349 }
5350 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
5351 ExtAddrMode BackupAddrMode = AddrMode;
5352 unsigned OldSize = AddrModeInsts.size();
5353
5354 // Check to see if it is possible to fold this operation.
5355 bool MovedAway = false;
5356 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
5357 // This instruction may have been moved away. If so, there is nothing
5358 // to check here.
5359 if (MovedAway)
5360 return true;
5361 // Okay, it's possible to fold this. Check to see if it is actually
5362 // *profitable* to do so. We use a simple cost model to avoid increasing
5363 // register pressure too much.
5364 if (I->hasOneUse() ||
5365 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
5366 AddrModeInsts.push_back(I);
5367 return true;
5368 }
5369
5370 // It isn't profitable to do this, roll back.
5371 AddrMode = BackupAddrMode;
5372 AddrModeInsts.resize(OldSize);
5373 TPT.rollback(LastKnownGood);
5374 }
5375 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
5376 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
5377 return true;
5378 TPT.rollback(LastKnownGood);
5379 } else if (isa<ConstantPointerNull>(Addr)) {
5380 // Null pointer gets folded without affecting the addressing mode.
5381 return true;
5382 }
5383
5384 // Worse case, the target should support [reg] addressing modes. :)
5385 if (!AddrMode.HasBaseReg) {
5386 AddrMode.HasBaseReg = true;
5387 AddrMode.BaseReg = Addr;
5388 // Still check for legality in case the target supports [imm] but not [i+r].
5389 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5390 return true;
5391 AddrMode.HasBaseReg = false;
5392 AddrMode.BaseReg = nullptr;
5393 }
5394
5395 // If the base register is already taken, see if we can do [r+r].
5396 if (AddrMode.Scale == 0) {
5397 AddrMode.Scale = 1;
5398 AddrMode.ScaledReg = Addr;
5399 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
5400 return true;
5401 AddrMode.Scale = 0;
5402 AddrMode.ScaledReg = nullptr;
5403 }
5404 // Couldn't match.
5405 TPT.rollback(LastKnownGood);
5406 return false;
5407}
5408
5409/// Check to see if all uses of OpVal by the specified inline asm call are due
5410/// to memory operands. If so, return true, otherwise return false.
5412 const TargetLowering &TLI,
5413 const TargetRegisterInfo &TRI) {
5414 const Function *F = CI->getFunction();
5415 TargetLowering::AsmOperandInfoVector TargetConstraints =
5416 TLI.ParseConstraints(F->getDataLayout(), &TRI, *CI);
5417
5418 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5419 // Compute the constraint code and ConstraintType to use.
5420 TLI.ComputeConstraintToUse(OpInfo, SDValue());
5421
5422 // If this asm operand is our Value*, and if it isn't an indirect memory
5423 // operand, we can't fold it! TODO: Also handle C_Address?
5424 if (OpInfo.CallOperandVal == OpVal &&
5425 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5426 !OpInfo.isIndirect))
5427 return false;
5428 }
5429
5430 return true;
5431}
5432
5433/// Recursively walk all the uses of I until we find a memory use.
5434/// If we find an obviously non-foldable instruction, return true.
5435/// Add accessed addresses and types to MemoryUses.
5437 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5438 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5439 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5440 BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan) {
5441 // If we already considered this instruction, we're done.
5442 if (!ConsideredInsts.insert(I).second)
5443 return false;
5444
5445 // If this is an obviously unfoldable instruction, bail out.
5446 if (!MightBeFoldableInst(I))
5447 return true;
5448
5449 // Loop over all the uses, recursively processing them.
5450 for (Use &U : I->uses()) {
5451 // Conservatively return true if we're seeing a large number or a deep chain
5452 // of users. This avoids excessive compilation times in pathological cases.
5453 if (SeenInsts++ >= MaxUsersToScan)
5454 return true;
5455
5456 Instruction *UserI = cast<Instruction>(U.getUser());
5457 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
5458 MemoryUses.push_back({&U, LI->getType()});
5459 continue;
5460 }
5461
5462 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
5463 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5464 return true; // Storing addr, not into addr.
5465 MemoryUses.push_back({&U, SI->getValueOperand()->getType()});
5466 continue;
5467 }
5468
5469 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
5470 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5471 return true; // Storing addr, not into addr.
5472 MemoryUses.push_back({&U, RMW->getValOperand()->getType()});
5473 continue;
5474 }
5475
5477 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5478 return true; // Storing addr, not into addr.
5479 MemoryUses.push_back({&U, CmpX->getCompareOperand()->getType()});
5480 continue;
5481 }
5482
5485 Type *AccessTy;
5486 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5487 return true;
5488
5489 if (!find(PtrOps, U.get()))
5490 return true;
5491
5492 MemoryUses.push_back({&U, AccessTy});
5493 continue;
5494 }
5495
5496 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
5497 if (CI->hasFnAttr(Attribute::Cold)) {
5498 // If this is a cold call, we can sink the addressing calculation into
5499 // the cold path. See optimizeCallInst
5500 if (!llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI))
5501 continue;
5502 }
5503
5504 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
5505 if (!IA)
5506 return true;
5507
5508 // If this is a memory operand, we're cool, otherwise bail out.
5509 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
5510 return true;
5511 continue;
5512 }
5513
5514 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5515 PSI, BFI, SeenInsts, MaxUsersToScan))
5516 return true;
5517 }
5518
5519 return false;
5520}
5521
5523 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5524 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5525 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned MaxUsersToScan) {
5526 unsigned SeenInsts = 0;
5527 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5528 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5529 PSI, BFI, SeenInsts, MaxUsersToScan);
5530}
5531
5532/// Return true if Val is already known to be live at the use site that we're
5533/// folding it into. If so, there is no cost to include it in the addressing
5534/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5535/// instruction already.
5536bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5537 Value *KnownLive1,
5538 Value *KnownLive2) {
5539 // If Val is either of the known-live values, we know it is live!
5540 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5541 return true;
5542
5543 // All values other than instructions and arguments (e.g. constants) are live.
5544 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5545 return true;
5546
5547 // If Val is a constant sized alloca in the entry block, it is live, this is
5548 // true because it is just a reference to the stack/frame pointer, which is
5549 // live for the whole function.
5550 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5551 if (AI->isStaticAlloca())
5552 return true;
5553
5554 // Check to see if this value is already used in the memory instruction's
5555 // block. If so, it's already live into the block at the very least, so we
5556 // can reasonably fold it.
5557 return Val->isUsedInBasicBlock(MemoryInst->getParent());
5558}
5559
5560/// It is possible for the addressing mode of the machine to fold the specified
5561/// instruction into a load or store that ultimately uses it.
5562/// However, the specified instruction has multiple uses.
5563/// Given this, it may actually increase register pressure to fold it
5564/// into the load. For example, consider this code:
5565///
5566/// X = ...
5567/// Y = X+1
5568/// use(Y) -> nonload/store
5569/// Z = Y+1
5570/// load Z
5571///
5572/// In this case, Y has multiple uses, and can be folded into the load of Z
5573/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5574/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5575/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5576/// number of computations either.
5577///
5578/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5579/// X was live across 'load Z' for other reasons, we actually *would* want to
5580/// fold the addressing mode in the Z case. This would make Y die earlier.
5581bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5582 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5583 if (IgnoreProfitability)
5584 return true;
5585
5586 // AMBefore is the addressing mode before this instruction was folded into it,
5587 // and AMAfter is the addressing mode after the instruction was folded. Get
5588 // the set of registers referenced by AMAfter and subtract out those
5589 // referenced by AMBefore: this is the set of values which folding in this
5590 // address extends the lifetime of.
5591 //
5592 // Note that there are only two potential values being referenced here,
5593 // BaseReg and ScaleReg (global addresses are always available, as are any
5594 // folded immediates).
5595 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5596
5597 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5598 // lifetime wasn't extended by adding this instruction.
5599 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5600 BaseReg = nullptr;
5601 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5602 ScaledReg = nullptr;
5603
5604 // If folding this instruction (and it's subexprs) didn't extend any live
5605 // ranges, we're ok with it.
5606 if (!BaseReg && !ScaledReg)
5607 return true;
5608
5609 // If all uses of this instruction can have the address mode sunk into them,
5610 // we can remove the addressing mode and effectively trade one live register
5611 // for another (at worst.) In this context, folding an addressing mode into
5612 // the use is just a particularly nice way of sinking it.
5614 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI,
5615 Opts.cgp_max_address_users_to_scan))
5616 return false; // Has a non-memory, non-foldable use!
5617
5618 // Now that we know that all uses of this instruction are part of a chain of
5619 // computation involving only operations that could theoretically be folded
5620 // into a memory use, loop over each of these memory operation uses and see
5621 // if they could *actually* fold the instruction. The assumption is that
5622 // addressing modes are cheap and that duplicating the computation involved
5623 // many times is worthwhile, even on a fastpath. For sinking candidates
5624 // (i.e. cold call sites), this serves as a way to prevent excessive code
5625 // growth since most architectures have some reasonable small and fast way to
5626 // compute an effective address. (i.e LEA on x86)
5627 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5628 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5629 Value *Address = Pair.first->get();
5630 Instruction *UserI = cast<Instruction>(Pair.first->getUser());
5631 Type *AddressAccessTy = Pair.second;
5632 unsigned AS = Address->getType()->getPointerAddressSpace();
5633
5634 // Do a match against the root of this address, ignoring profitability. This
5635 // will tell us if the addressing mode for the memory operation will
5636 // *actually* cover the shared instruction.
5637 ExtAddrMode Result;
5638 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5639 0);
5640 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5641 TPT.getRestorationPoint();
5642 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5643 AddressAccessTy, AS, UserI, Result,
5644 InsertedInsts, PromotedInsts, TPT,
5645 LargeOffsetGEP, OptSize, PSI, BFI, Opts);
5646 Matcher.IgnoreProfitability = true;
5647 bool Success = Matcher.matchAddr(Address, 0);
5648 (void)Success;
5649 assert(Success && "Couldn't select *anything*?");
5650
5651 // The match was to check the profitability, the changes made are not
5652 // part of the original matcher. Therefore, they should be dropped
5653 // otherwise the original matcher will not present the right state.
5654 TPT.rollback(LastKnownGood);
5655
5656 // If the match didn't cover I, then it won't be shared by it.
5657 if (!is_contained(MatchedAddrModeInsts, I))
5658 return false;
5659
5660 MatchedAddrModeInsts.clear();
5661 }
5662
5663 return true;
5664}
5665
5666/// Return true if the specified values are defined in a
5667/// different basic block than BB.
5668static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5670 return I->getParent() != BB;
5671 return false;
5672}
5673
5674// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5675// is the first instruction that will use Addr. So we need to find the first
5676// user of Addr in current BB.
5678 Value *SunkAddr) {
5679 if (Addr->hasOneUse())
5680 return MemoryInst->getIterator();
5681
5682 // We already have a SunkAddr in current BB, but we may need to insert cast
5683 // instruction after it.
5684 if (SunkAddr) {
5685 if (Instruction *AddrInst = dyn_cast<Instruction>(SunkAddr))
5686 return std::next(AddrInst->getIterator());
5687 }
5688
5689 // Find the first user of Addr in current BB.
5690 Instruction *Earliest = MemoryInst;
5691 for (User *U : Addr->users()) {
5692 Instruction *UserInst = dyn_cast<Instruction>(U);
5693 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5694 if (isa<PHINode>(UserInst))
5695 continue;
5696 if (UserInst->comesBefore(Earliest))
5697 Earliest = UserInst;
5698 }
5699 }
5700 return Earliest->getIterator();
5701}
5702
5703/// Sink addressing mode computation immediate before MemoryInst if doing so
5704/// can be done without increasing register pressure. The need for the
5705/// register pressure constraint means this can end up being an all or nothing
5706/// decision for all uses of the same addressing computation.
5707///
5708/// Load and Store Instructions often have addressing modes that can do
5709/// significant amounts of computation. As such, instruction selection will try
5710/// to get the load or store to do as much computation as possible for the
5711/// program. The problem is that isel can only see within a single block. As
5712/// such, we sink as much legal addressing mode work into the block as possible.
5713///
5714/// This method is used to optimize both load/store and inline asms with memory
5715/// operands. It's also used to sink addressing computations feeding into cold
5716/// call sites into their (cold) basic block.
5717///
5718/// The motivation for handling sinking into cold blocks is that doing so can
5719/// both enable other address mode sinking (by satisfying the register pressure
5720/// constraint above), and reduce register pressure globally (by removing the
5721/// addressing mode computation from the fast path entirely.).
5722bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5723 Type *AccessTy, unsigned AddrSpace) {
5724 Value *Repl = Addr;
5725
5726 // Try to collapse single-value PHI nodes. This is necessary to undo
5727 // unprofitable PRE transformations.
5728 SmallVector<Value *, 8> worklist;
5729 SmallPtrSet<Value *, 16> Visited;
5730 worklist.push_back(Addr);
5731
5732 // Use a worklist to iteratively look through PHI and select nodes, and
5733 // ensure that the addressing mode obtained from the non-PHI/select roots of
5734 // the graph are compatible.
5735 bool PhiOrSelectSeen = false;
5736 SmallVector<Instruction *, 16> AddrModeInsts;
5737 AddressingModeCombiner AddrModes(*DL, Opts, Addr);
5738 TypePromotionTransaction TPT(RemovedInsts);
5739 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5740 TPT.getRestorationPoint();
5741 while (!worklist.empty()) {
5742 Value *V = worklist.pop_back_val();
5743
5744 // We allow traversing cyclic Phi nodes.
5745 // In case of success after this loop we ensure that traversing through
5746 // Phi nodes ends up with all cases to compute address of the form
5747 // BaseGV + Base + Scale * Index + Offset
5748 // where Scale and Offset are constans and BaseGV, Base and Index
5749 // are exactly the same Values in all cases.
5750 // It means that BaseGV, Scale and Offset dominate our memory instruction
5751 // and have the same value as they had in address computation represented
5752 // as Phi. So we can safely sink address computation to memory instruction.
5753 if (!Visited.insert(V).second)
5754 continue;
5755
5756 // For a PHI node, push all of its incoming values.
5757 if (PHINode *P = dyn_cast<PHINode>(V)) {
5758 append_range(worklist, P->incoming_values());
5759 PhiOrSelectSeen = true;
5760 continue;
5761 }
5762 // Similar for select.
5763 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5764 worklist.push_back(SI->getFalseValue());
5765 worklist.push_back(SI->getTrueValue());
5766 PhiOrSelectSeen = true;
5767 continue;
5768 }
5769
5770 // For non-PHIs, determine the addressing mode being computed. Note that
5771 // the result may differ depending on what other uses our candidate
5772 // addressing instructions might have.
5773 AddrModeInsts.clear();
5774 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5775 0);
5776 // Defer the query (and possible computation of) the dom tree to point of
5777 // actual use. It's expected that most address matches don't actually need
5778 // the domtree.
5779 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5780 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5781 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5782 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5783 BFI, Opts);
5784
5785 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5786 if (GEP && !NewGEPBases.count(GEP)) {
5787 // If splitting the underlying data structure can reduce the offset of a
5788 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5789 // previously split data structures.
5790 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5791 LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
5792 }
5793
5794 NewAddrMode.OriginalValue = V;
5795 if (!AddrModes.addNewAddrMode(NewAddrMode))
5796 break;
5797 }
5798
5799 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5800 // or we have multiple but either couldn't combine them or combining them
5801 // wouldn't do anything useful, bail out now.
5802 if (!AddrModes.combineAddrModes()) {
5803 TPT.rollback(LastKnownGood);
5804 return false;
5805 }
5806 bool Modified = TPT.commit();
5807
5808 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5809 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5810
5811 // If all the instructions matched are already in this BB, don't do anything.
5812 // If we saw a Phi node then it is not local definitely, and if we saw a
5813 // select then we want to push the address calculation past it even if it's
5814 // already in this BB.
5815 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5816 return IsNonLocalValue(V, MemoryInst->getParent());
5817 })) {
5818 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5819 << "\n");
5820 return Modified;
5821 }
5822
5823 // Now that we determined the addressing expression we want to use and know
5824 // that we have to sink it into this block. Check to see if we have already
5825 // done this for some other load/store instr in this block. If so, reuse
5826 // the computation. Before attempting reuse, check if the address is valid
5827 // as it may have been erased.
5828
5829 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5830
5831 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5832 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5833 Type *IdxTy = DL->getIndexType(Addr->getType());
5834
5835 // The current BB may be optimized multiple times, we can't guarantee the
5836 // reuse of Addr happens later, call findInsertPos to find an appropriate
5837 // insert position.
5838 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5839
5840 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5841 if (!SunkAddr) {
5842 auto &DT = getDT();
5843 if ((AddrMode.BaseReg && !DT.dominates(AddrMode.BaseReg, &*InsertPos)) ||
5844 (AddrMode.ScaledReg && !DT.dominates(AddrMode.ScaledReg, &*InsertPos)))
5845 return Modified;
5846 }
5847
5848 IRBuilder<> Builder(InsertPos);
5849
5850 if (SunkAddr) {
5851 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5852 << " for " << *MemoryInst << "\n");
5853 if (SunkAddr->getType() != Addr->getType()) {
5854 if (SunkAddr->getType()->getPointerAddressSpace() !=
5855 Addr->getType()->getPointerAddressSpace() &&
5856 !DL->isNonIntegralPointerType(Addr->getType())) {
5857 // There are two reasons the address spaces might not match: a no-op
5858 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5859 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5860 // TODO: allow bitcast between different address space pointers with the
5861 // same size.
5862 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
5863 SunkAddr =
5864 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
5865 } else
5866 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5867 }
5868 } else {
5869 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
5870 << " for " << *MemoryInst << "\n");
5871 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5872
5873 // First, find the pointer.
5874 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5875 ResultPtr = AddrMode.BaseReg;
5876 AddrMode.BaseReg = nullptr;
5877 }
5878
5879 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5880 // We can't add more than one pointer together, nor can we scale a
5881 // pointer (both of which seem meaningless).
5882 if (ResultPtr || AddrMode.Scale != 1)
5883 return Modified;
5884
5885 ResultPtr = AddrMode.ScaledReg;
5886 AddrMode.Scale = 0;
5887 }
5888
5889 // It is only safe to sign extend the BaseReg if we know that the math
5890 // required to create it did not overflow before we extend it. Since
5891 // the original IR value was tossed in favor of a constant back when
5892 // the AddrMode was created we need to bail out gracefully if widths
5893 // do not match instead of extending it.
5894 //
5895 // (See below for code to add the scale.)
5896 if (AddrMode.Scale) {
5897 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5898 if (cast<IntegerType>(IdxTy)->getBitWidth() >
5899 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5900 return Modified;
5901 }
5902
5903 GlobalValue *BaseGV = AddrMode.BaseGV;
5904 if (BaseGV != nullptr) {
5905 if (ResultPtr)
5906 return Modified;
5907
5908 if (BaseGV->isThreadLocal()) {
5909 ResultPtr = Builder.CreateThreadLocalAddress(BaseGV);
5910 } else {
5911 ResultPtr = BaseGV;
5912 }
5913 }
5914
5915 // If the real base value actually came from an inttoptr, then the matcher
5916 // will look through it and provide only the integer value. In that case,
5917 // use it here.
5918 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5919 if (!ResultPtr && AddrMode.BaseReg) {
5920 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5921 "sunkaddr");
5922 AddrMode.BaseReg = nullptr;
5923 } else if (!ResultPtr && AddrMode.Scale == 1) {
5924 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5925 "sunkaddr");
5926 AddrMode.Scale = 0;
5927 }
5928 }
5929
5930 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
5931 !AddrMode.BaseOffs) {
5932 SunkAddr = Constant::getNullValue(Addr->getType());
5933 } else if (!ResultPtr) {
5934 return Modified;
5935 } else {
5936 Type *I8PtrTy =
5937 Builder.getPtrTy(Addr->getType()->getPointerAddressSpace());
5938
5939 // Start with the base register. Do this first so that subsequent address
5940 // matching finds it last, which will prevent it from trying to match it
5941 // as the scaled value in case it happens to be a mul. That would be
5942 // problematic if we've sunk a different mul for the scale, because then
5943 // we'd end up sinking both muls.
5944 if (AddrMode.BaseReg) {
5945 Value *V = AddrMode.BaseReg;
5946 if (V->getType() != IdxTy)
5947 V = Builder.CreateIntCast(V, IdxTy, /*isSigned=*/true, "sunkaddr");
5948
5949 ResultIndex = V;
5950 }
5951
5952 // Add the scale value.
5953 if (AddrMode.Scale) {
5954 Value *V = AddrMode.ScaledReg;
5955 if (V->getType() == IdxTy) {
5956 // done.
5957 } else {
5959 cast<IntegerType>(V->getType())->getBitWidth() &&
5960 "We can't transform if ScaledReg is too narrow");
5961 V = Builder.CreateTrunc(V, IdxTy, "sunkaddr");
5962 }
5963
5964 if (AddrMode.Scale != 1)
5965 V = Builder.CreateMul(
5966 V, ConstantInt::getSigned(IdxTy, AddrMode.Scale), "sunkaddr");
5967 if (ResultIndex)
5968 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5969 else
5970 ResultIndex = V;
5971 }
5972
5973 // Add in the Base Offset if present.
5974 if (AddrMode.BaseOffs) {
5975 Value *V = ConstantInt::getSigned(IdxTy, AddrMode.BaseOffs);
5976 if (ResultIndex) {
5977 // We need to add this separately from the scale above to help with
5978 // SDAG consecutive load/store merging.
5979 if (ResultPtr->getType() != I8PtrTy)
5980 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5981 ResultPtr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
5982 AddrMode.InBounds);
5983 }
5984
5985 ResultIndex = V;
5986 }
5987
5988 if (!ResultIndex) {
5989 auto PtrInst = dyn_cast<Instruction>(ResultPtr);
5990 // We know that we have a pointer without any offsets. If this pointer
5991 // originates from a different basic block than the current one, we
5992 // must be able to recreate it in the current basic block.
5993 // We do not support the recreation of any instructions yet.
5994 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
5995 return Modified;
5996 SunkAddr = ResultPtr;
5997 } else {
5998 if (ResultPtr->getType() != I8PtrTy)
5999 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
6000 SunkAddr = Builder.CreatePtrAdd(ResultPtr, ResultIndex, "sunkaddr",
6001 AddrMode.InBounds);
6002 }
6003
6004 if (SunkAddr->getType() != Addr->getType()) {
6005 if (SunkAddr->getType()->getPointerAddressSpace() !=
6006 Addr->getType()->getPointerAddressSpace() &&
6007 !DL->isNonIntegralPointerType(Addr->getType())) {
6008 // There are two reasons the address spaces might not match: a no-op
6009 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6010 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6011 // TODO: allow bitcast between different address space pointers with
6012 // the same size.
6013 SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
6014 SunkAddr =
6015 Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
6016 } else
6017 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
6018 }
6019 }
6020 }
6021
6022 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
6023 // Store the newly computed address into the cache. In the case we reused a
6024 // value, this should be idempotent.
6025 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6026
6027 // If we have no uses, recursively delete the value and all dead instructions
6028 // using it.
6029 if (Repl->use_empty()) {
6030 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
6031 RecursivelyDeleteTriviallyDeadInstructions(
6032 Repl, TLInfo, nullptr,
6033 [&](Value *V) { removeAllAssertingVHReferences(V); });
6034 });
6035 }
6036 ++NumMemoryInsts;
6037 return true;
6038}
6039
6040/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6041/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6042/// only handle a 2 operand GEP in the same basic block or a splat constant
6043/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6044/// index.
6045///
6046/// If the GEP is in another basic block, e.g. because LICM hoisted it out of a
6047/// loop, sink it next to the gather/scatter and reuse it for the other
6048/// gathers/scatters of the same GEP in the block.
6049///
6050/// If the existing GEP has a vector base pointer that is splat, we can look
6051/// through the splat to find the scalar pointer. If the vector base pointer is
6052/// a GEP with a scalar or splat base pointer, and the existing GEP only adds a
6053/// uniform offset to it, we can add that offset to the scalar pointer instead.
6054/// If we can't find a scalar pointer there's nothing we can do.
6055///
6056/// If we have a GEP with more than 2 indices where the middle indices are all
6057/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6058///
6059/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6060/// followed by a GEP with an all zeroes vector index. This will enable
6061/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6062/// zero index.
6063bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6064 Value *Ptr) {
6065 BasicBlock *BB = MemoryInst->getParent();
6066 Value *NewAddr;
6067
6068 // Reuse the address sunk into this block for an earlier gather/scatter, if
6069 // any. The block may be visited again, so it can also be after this one.
6070 auto *SunkAddr = dyn_cast_or_null<Instruction>(SunkAddrs.lookup(Ptr));
6071 if (SunkAddr && SunkAddr->getParent() == BB &&
6072 SunkAddr->comesBefore(MemoryInst)) {
6073 NewAddr = SunkAddr;
6074 } else if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
6075 // Don't optimize GEPs that don't have indices.
6076 if (!GEP->hasIndices())
6077 return false;
6078
6079 bool SinkGEP = GEP->getParent() != BB;
6080
6081 SmallVector<Value *, 2> Ops(GEP->operands());
6082 Type *SourceTy = GEP->getSourceElementType();
6083
6084 Type *OffsetTy = nullptr;
6085 SmallVector<Value *, 1> OffsetIdxs;
6086
6087 bool RewriteGEP = SinkGEP;
6088
6089 if (Ops[0]->getType()->isVectorTy()) {
6090 if (Value *Splat = getSplatValue(Ops[0])) {
6091 Ops[0] = Splat;
6092 } else {
6093 auto *BaseGEP = dyn_cast<GetElementPtrInst>(Ops[0]);
6094 if (!BaseGEP || !BaseGEP->hasIndices())
6095 return false;
6096 Value *Base = BaseGEP->getPointerOperand();
6097 if (Base->getType()->isVectorTy())
6099 if (!Base)
6100 return false;
6101 for (Value *Idx : drop_begin(Ops)) {
6102 if (Idx->getType()->isVectorTy())
6103 Idx = getSplatValue(Idx);
6104 if (!Idx)
6105 return false;
6106 OffsetIdxs.push_back(Idx);
6107 }
6108 OffsetTy = SourceTy;
6109 SourceTy = BaseGEP->getSourceElementType();
6110 Ops.assign(BaseGEP->op_begin(), BaseGEP->op_end());
6111 Ops[0] = Base;
6112 }
6113 RewriteGEP = true;
6114 }
6115
6116 unsigned FinalIndex = Ops.size() - 1;
6117
6118 // Ensure all but the last index is 0.
6119 // FIXME: This isn't strictly required. All that's required is that they are
6120 // all scalars or splats.
6121 for (unsigned i = 1; i < FinalIndex; ++i) {
6122 auto *C = dyn_cast<Constant>(Ops[i]);
6123 if (!C)
6124 return false;
6125 if (isa<VectorType>(C->getType()))
6126 C = C->getSplatValue();
6127 auto *CI = dyn_cast_or_null<ConstantInt>(C);
6128 if (!CI || !CI->isZero())
6129 return false;
6130 // Scalarize the index if needed.
6131 Ops[i] = CI;
6132 }
6133
6134 // Try to scalarize the final index.
6135 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6136 if (Value *V = getSplatValue(Ops[FinalIndex])) {
6137 auto *C = dyn_cast<ConstantInt>(V);
6138 // Don't scalarize all zeros vector.
6139 if (!C || !C->isZero()) {
6140 Ops[FinalIndex] = V;
6141 RewriteGEP = true;
6142 }
6143 }
6144 }
6145
6146 // If we made any changes or the we have extra operands, we need to generate
6147 // new instructions.
6148 if (!RewriteGEP && Ops.size() == 2)
6149 return false;
6150
6151 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6152
6153 IRBuilder<> Builder(MemoryInst);
6154 Builder.disableGEPCanonicalization();
6155
6156 if (OffsetTy)
6157 Ops[0] = Builder.CreateGEP(OffsetTy, Ops[0], OffsetIdxs);
6158
6159 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
6160
6161 // If the final index isn't a vector, emit a scalar GEP containing all ops
6162 // and a vector GEP with all zeroes final index.
6163 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6164 NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
6165 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6166 auto *SecondTy = GetElementPtrInst::getIndexedType(
6167 SourceTy, ArrayRef(Ops).drop_front());
6168 NewAddr =
6169 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
6170 } else {
6171 Value *Base = Ops[0];
6172 Value *Index = Ops[FinalIndex];
6173
6174 // Create a scalar GEP if there are more than 2 operands.
6175 if (Ops.size() != 2) {
6176 // Replace the last index with 0.
6177 Ops[FinalIndex] =
6178 Constant::getNullValue(Ops[FinalIndex]->getType()->getScalarType());
6179 Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
6181 SourceTy, ArrayRef(Ops).drop_front());
6182 }
6183
6184 // Now create the GEP with scalar pointer and vector index.
6185 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
6186 }
6187
6188 if (SinkGEP)
6189 SunkAddrs[Ptr] = WeakTrackingVH(NewAddr);
6190 } else if (!isa<Constant>(Ptr)) {
6191 // Not a GEP, maybe its a splat and we can create a GEP to enable
6192 // SelectionDAGBuilder to use it as a uniform base.
6193 Value *V = getSplatValue(Ptr);
6194 if (!V)
6195 return false;
6196
6197 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
6198
6199 IRBuilder<> Builder(MemoryInst);
6200 Builder.disableGEPCanonicalization();
6201
6202 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6203 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
6204 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
6205 Type *ScalarTy;
6206 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6207 Intrinsic::masked_gather) {
6208 ScalarTy = MemoryInst->getType()->getScalarType();
6209 } else {
6210 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6211 Intrinsic::masked_scatter);
6212 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
6213 }
6214 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
6215 } else {
6216 // Constant, SelectionDAGBuilder knows to check if its a splat.
6217 return false;
6218 }
6219
6220 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
6221
6222 // If we have no uses, recursively delete the value and all dead instructions
6223 // using it.
6224 if (Ptr->use_empty())
6226 Ptr, TLInfo, nullptr,
6227 [&](Value *V) { removeAllAssertingVHReferences(V); });
6228
6229 return true;
6230}
6231
6232// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6233// Check the pattern we are interested in where there are maximum 2 uses
6234// of the intrinsic which are the extract instructions.
6236 ExtractValueInst *&OverflowExtract) {
6237 // Bail out if it's more than 2 users:
6238 if (I->hasNUsesOrMore(3))
6239 return false;
6240
6241 for (User *U : I->users()) {
6242 auto *Extract = dyn_cast<ExtractValueInst>(U);
6243 if (!Extract || Extract->getNumIndices() != 1)
6244 return false;
6245
6246 unsigned Index = Extract->getIndices()[0];
6247 if (Index == 0)
6248 MulExtract = Extract;
6249 else if (Index == 1)
6250 OverflowExtract = Extract;
6251 else
6252 return false;
6253 }
6254 return true;
6255}
6256
6257// Rewrite the mul_with_overflow intrinsic by checking if both of the
6258// operands' value ranges are within the legal type. If so, we can optimize the
6259// multiplication algorithm. This code is supposed to be written during the step
6260// of type legalization, but given that we need to reconstruct the IR which is
6261// not doable there, we do it here.
6262// The IR after the optimization will look like:
6263// entry:
6264// if signed:
6265// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6266// overflow_no
6267// else:
6268// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6269// overflow_no:
6270// overflow:
6271// overflow.res:
6272// \returns true if optimization was applied
6273// TODO: This optimization can be further improved to optimize branching on
6274// overflow where the 'overflow_no' BB can branch directly to the false
6275// successor of overflow, but that would add additional complexity so we leave
6276// it for future work.
6277bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6278 ModifyDT &ModifiedDT) {
6279 // Check if target supports this optimization.
6281 I->getContext(),
6282 TLI->getValueType(*DL, I->getType()->getContainedType(0))))
6283 return false;
6284
6285 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6286 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6287 return false;
6288
6289 // Keep track of the instruction to stop reoptimizing it again.
6290 InsertedInsts.insert(I);
6291
6292 Value *LHS = I->getOperand(0);
6293 Value *RHS = I->getOperand(1);
6294 Type *Ty = LHS->getType();
6295 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6296 Type *LegalTy = Ty->getWithNewBitWidth(VTHalfBitWidth);
6297
6298 // New BBs:
6299 BasicBlock *OverflowEntryBB =
6300 splitBlockBefore(I->getParent(), I, DTU, LI, nullptr, "");
6301 OverflowEntryBB->takeName(I->getParent());
6302 // Keep the 'br' instruction that is generated as a result of the split to be
6303 // erased/replaced later.
6304 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6305 BasicBlock *NoOverflowBB =
6306 BasicBlock::Create(I->getContext(), "overflow.no", I->getFunction());
6307 NoOverflowBB->moveAfter(OverflowEntryBB);
6308 BasicBlock *OverflowBB =
6309 BasicBlock::Create(I->getContext(), "overflow", I->getFunction());
6310 OverflowBB->moveAfter(NoOverflowBB);
6311
6312 // BB overflow.entry:
6313 IRBuilder<> Builder(OverflowEntryBB);
6314 // Extract low and high halves of LHS:
6315 Value *LoLHS = Builder.CreateTrunc(LHS, LegalTy, "lo.lhs");
6316 Value *HiLHS = Builder.CreateLShr(LHS, VTHalfBitWidth, "lhs.lsr");
6317 HiLHS = Builder.CreateTrunc(HiLHS, LegalTy, "hi.lhs");
6318
6319 // Extract low and high halves of RHS:
6320 Value *LoRHS = Builder.CreateTrunc(RHS, LegalTy, "lo.rhs");
6321 Value *HiRHS = Builder.CreateLShr(RHS, VTHalfBitWidth, "rhs.lsr");
6322 HiRHS = Builder.CreateTrunc(HiRHS, LegalTy, "hi.rhs");
6323
6324 Value *IsAnyBitTrue;
6325 if (IsSigned) {
6326 Value *SignLoLHS =
6327 Builder.CreateAShr(LoLHS, VTHalfBitWidth - 1, "sign.lo.lhs");
6328 Value *SignLoRHS =
6329 Builder.CreateAShr(LoRHS, VTHalfBitWidth - 1, "sign.lo.rhs");
6330 Value *XorLHS = Builder.CreateXor(HiLHS, SignLoLHS);
6331 Value *XorRHS = Builder.CreateXor(HiRHS, SignLoRHS);
6332 Value *Or = Builder.CreateOr(XorLHS, XorRHS, "or.lhs.rhs");
6333 IsAnyBitTrue = Builder.CreateCmp(ICmpInst::ICMP_NE, Or,
6334 ConstantInt::getNullValue(Or->getType()));
6335 } else {
6336 Value *CmpLHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiLHS,
6337 ConstantInt::getNullValue(LegalTy));
6338 Value *CmpRHS = Builder.CreateCmp(ICmpInst::ICMP_NE, HiRHS,
6339 ConstantInt::getNullValue(LegalTy));
6340 IsAnyBitTrue = Builder.CreateOr(CmpLHS, CmpRHS, "or.lhs.rhs");
6341 }
6342 Builder.CreateCondBr(IsAnyBitTrue, OverflowBB, NoOverflowBB);
6343
6344 // BB overflow.no:
6345 Builder.SetInsertPoint(NoOverflowBB);
6346 Value *ExtLoLHS, *ExtLoRHS;
6347 if (IsSigned) {
6348 ExtLoLHS = Builder.CreateSExt(LoLHS, Ty, "lo.lhs.ext");
6349 ExtLoRHS = Builder.CreateSExt(LoRHS, Ty, "lo.rhs.ext");
6350 } else {
6351 ExtLoLHS = Builder.CreateZExt(LoLHS, Ty, "lo.lhs.ext");
6352 ExtLoRHS = Builder.CreateZExt(LoRHS, Ty, "lo.rhs.ext");
6353 }
6354
6355 Value *Mul = Builder.CreateMul(ExtLoLHS, ExtLoRHS, "mul.overflow.no");
6356
6357 // Create the 'overflow.res' BB to merge the results of
6358 // the two paths:
6359 BasicBlock *OverflowResBB = I->getParent();
6360 OverflowResBB->setName("overflow.res");
6361
6362 // BB overflow.no: jump to overflow.res BB
6363 Builder.CreateBr(OverflowResBB);
6364 // No we don't need the old terminator in overflow.entry BB, erase it:
6365 OldTerminator->eraseFromParent();
6366
6367 // BB overflow.res:
6368 Builder.SetInsertPoint(OverflowResBB->getFirstInsertionPt());
6369 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6370 // replace the extract instructions.
6371 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, 2),
6372 *OverflowFlagPHI =
6373 Builder.CreatePHI(IntegerType::getInt1Ty(I->getContext()), 2);
6374
6375 // Add the incoming values from no.overflow BB and later from overflow BB.
6376 OverflowResPHI->addIncoming(Mul, NoOverflowBB);
6377 OverflowFlagPHI->addIncoming(ConstantInt::getFalse(I->getContext()),
6378 NoOverflowBB);
6379
6380 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6381 if (MulExtract) {
6382 MulExtract->replaceAllUsesWith(OverflowResPHI);
6383 MulExtract->eraseFromParent();
6384 }
6385 if (OverflowExtract) {
6386 OverflowExtract->replaceAllUsesWith(OverflowFlagPHI);
6387 OverflowExtract->eraseFromParent();
6388 }
6389
6390 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6391 // overflow BB
6392 I->removeFromParent();
6393 // BB overflow:
6394 I->insertInto(OverflowBB, OverflowBB->end());
6395 Builder.SetInsertPoint(OverflowBB->end());
6396 Value *MulOverflow = Builder.CreateExtractValue(I, {0}, "mul.overflow");
6397 Value *OverflowFlag = Builder.CreateExtractValue(I, {1}, "overflow.flag");
6398 Builder.CreateBr(OverflowResBB);
6399
6400 // Add The Extracted values to the PHINodes in the overflow.res BB.
6401 OverflowResPHI->addIncoming(MulOverflow, OverflowBB);
6402 OverflowFlagPHI->addIncoming(OverflowFlag, OverflowBB);
6403
6404 DTU->applyUpdates({{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6405 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6406 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6407 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6408 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6409
6410 ModifiedDT = ModifyDT::ModifyBBDT;
6411 return true;
6412}
6413
6414/// If there are any memory operands, use OptimizeMemoryInst to sink their
6415/// address computing into the block when possible / profitable.
6416bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6417 bool MadeChange = false;
6418
6419 const TargetRegisterInfo *TRI =
6421 TargetLowering::AsmOperandInfoVector TargetConstraints =
6422 TLI->ParseConstraints(*DL, TRI, *CS);
6423 unsigned ArgNo = 0;
6424 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6425 // Compute the constraint code and ConstraintType to use.
6427
6428 // TODO: Also handle C_Address?
6429 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6430 OpInfo.isIndirect) {
6431 Value *OpVal = CS->getArgOperand(ArgNo++);
6432 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
6433 } else if (OpInfo.Type == InlineAsm::isInput)
6434 ArgNo++;
6435 }
6436
6437 return MadeChange;
6438}
6439
6440/// Check if all the uses of \p Val are equivalent (or free) zero or
6441/// sign extensions.
6442static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6443 assert(!Val->use_empty() && "Input must have at least one use");
6444 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
6445 bool IsSExt = isa<SExtInst>(FirstUser);
6446 Type *ExtTy = FirstUser->getType();
6447 for (const User *U : Val->users()) {
6448 const Instruction *UI = cast<Instruction>(U);
6449 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
6450 return false;
6451 Type *CurTy = UI->getType();
6452 // Same input and output types: Same instruction after CSE.
6453 if (CurTy == ExtTy)
6454 continue;
6455
6456 // If IsSExt is true, we are in this situation:
6457 // a = Val
6458 // b = sext ty1 a to ty2
6459 // c = sext ty1 a to ty3
6460 // Assuming ty2 is shorter than ty3, this could be turned into:
6461 // a = Val
6462 // b = sext ty1 a to ty2
6463 // c = sext ty2 b to ty3
6464 // However, the last sext is not free.
6465 if (IsSExt)
6466 return false;
6467
6468 // This is a ZExt, maybe this is free to extend from one type to another.
6469 // In that case, we would not account for a different use.
6470 Type *NarrowTy;
6471 Type *LargeTy;
6472 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6473 CurTy->getScalarType()->getIntegerBitWidth()) {
6474 NarrowTy = CurTy;
6475 LargeTy = ExtTy;
6476 } else {
6477 NarrowTy = ExtTy;
6478 LargeTy = CurTy;
6479 }
6480
6481 if (!TLI.isZExtFree(NarrowTy, LargeTy))
6482 return false;
6483 }
6484 // All uses are the same or can be derived from one another for free.
6485 return true;
6486}
6487
6488/// Try to speculatively promote extensions in \p Exts and continue
6489/// promoting through newly promoted operands recursively as far as doing so is
6490/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6491/// When some promotion happened, \p TPT contains the proper state to revert
6492/// them.
6493///
6494/// \return true if some promotion happened, false otherwise.
6495bool CodeGenPrepare::tryToPromoteExts(
6496 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6497 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6498 unsigned CreatedInstsCost) {
6499 bool Promoted = false;
6500
6501 // Iterate over all the extensions to try to promote them.
6502 for (auto *I : Exts) {
6503 // Early check if we directly have ext(load).
6504 if (isa<LoadInst>(I->getOperand(0))) {
6505 ProfitablyMovedExts.push_back(I);
6506 continue;
6507 }
6508
6509 // Check whether or not we want to do any promotion. The reason we have
6510 // this check inside the for loop is to catch the case where an extension
6511 // is directly fed by a load because in such case the extension can be moved
6512 // up without any promotion on its operands.
6513 if (!TLI->enableExtLdPromotion() || !Opts.cgp_ext_ld_promotion)
6514 return false;
6515
6516 // Get the action to perform the promotion.
6517 TypePromotionHelper::Action TPH =
6518 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
6519 // Check if we can promote.
6520 if (!TPH) {
6521 // Save the current extension as we cannot move up through its operand.
6522 ProfitablyMovedExts.push_back(I);
6523 continue;
6524 }
6525
6526 // Save the current state.
6527 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6528 TPT.getRestorationPoint();
6529 SmallVector<Instruction *, 4> NewExts;
6530 unsigned NewCreatedInstsCost = 0;
6531 unsigned ExtCost = !TLI->isExtFree(I);
6532 // Promote.
6533 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6534 &NewExts, nullptr, *TLI);
6535 assert(PromotedVal &&
6536 "TypePromotionHelper should have filtered out those cases");
6537
6538 // We would be able to merge only one extension in a load.
6539 // Therefore, if we have more than 1 new extension we heuristically
6540 // cut this search path, because it means we degrade the code quality.
6541 // With exactly 2, the transformation is neutral, because we will merge
6542 // one extension but leave one. However, we optimistically keep going,
6543 // because the new extension may be removed too. Also avoid replacing a
6544 // single free extension with multiple extensions, as this increases the
6545 // number of IR instructions while not providing any savings.
6546 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6547 // FIXME: It would be possible to propagate a negative value instead of
6548 // conservatively ceiling it to 0.
6549 TotalCreatedInstsCost =
6550 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
6551 if (!Opts.cgp_stress_ext_ld_promotion &&
6552 (TotalCreatedInstsCost > 1 ||
6553 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal) ||
6554 (ExtCost == 0 && NewExts.size() > 1))) {
6555 // This promotion is not profitable, rollback to the previous state, and
6556 // save the current extension in ProfitablyMovedExts as the latest
6557 // speculative promotion turned out to be unprofitable.
6558 TPT.rollback(LastKnownGood);
6559 ProfitablyMovedExts.push_back(I);
6560 continue;
6561 }
6562 // Continue promoting NewExts as far as doing so is profitable.
6563 SmallVector<Instruction *, 2> NewlyMovedExts;
6564 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
6565 bool NewPromoted = false;
6566 for (auto *ExtInst : NewlyMovedExts) {
6567 Instruction *MovedExt = cast<Instruction>(ExtInst);
6568 Value *ExtOperand = MovedExt->getOperand(0);
6569 // If we have reached to a load, we need this extra profitability check
6570 // as it could potentially be merged into an ext(load).
6571 if (isa<LoadInst>(ExtOperand) &&
6572 !(Opts.cgp_stress_ext_ld_promotion ||
6573 NewCreatedInstsCost <= ExtCost ||
6574 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
6575 continue;
6576
6577 ProfitablyMovedExts.push_back(MovedExt);
6578 NewPromoted = true;
6579 }
6580
6581 // If none of speculative promotions for NewExts is profitable, rollback
6582 // and save the current extension (I) as the last profitable extension.
6583 if (!NewPromoted) {
6584 TPT.rollback(LastKnownGood);
6585 ProfitablyMovedExts.push_back(I);
6586 continue;
6587 }
6588 // The promotion is profitable.
6589 Promoted = true;
6590 }
6591 return Promoted;
6592}
6593
6594/// Merging redundant sexts when one is dominating the other.
6595bool CodeGenPrepare::mergeSExts(Function &F) {
6596 bool Changed = false;
6597 for (auto &Entry : ValToSExtendedUses) {
6598 SExts &Insts = Entry.second;
6599 SExts CurPts;
6600 for (Instruction *Inst : Insts) {
6601 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
6602 Inst->getOperand(0) != Entry.first)
6603 continue;
6604 bool inserted = false;
6605 for (auto &Pt : CurPts) {
6606 if (getDT().dominates(Inst, Pt)) {
6607 replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
6608 RemovedInsts.insert(Pt);
6609 Pt->removeFromParent();
6610 Pt = Inst;
6611 inserted = true;
6612 Changed = true;
6613 break;
6614 }
6615 if (!getDT().dominates(Pt, Inst))
6616 // Give up if we need to merge in a common dominator as the
6617 // experiments show it is not profitable.
6618 continue;
6619 replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
6620 RemovedInsts.insert(Inst);
6621 Inst->removeFromParent();
6622 inserted = true;
6623 Changed = true;
6624 break;
6625 }
6626 if (!inserted)
6627 CurPts.push_back(Inst);
6628 }
6629 }
6630 return Changed;
6631}
6632
6633// Splitting large data structures so that the GEPs accessing them can have
6634// smaller offsets so that they can be sunk to the same blocks as their users.
6635// For example, a large struct starting from %base is split into two parts
6636// where the second part starts from %new_base.
6637//
6638// Before:
6639// BB0:
6640// %base =
6641//
6642// BB1:
6643// %gep0 = gep %base, off0
6644// %gep1 = gep %base, off1
6645// %gep2 = gep %base, off2
6646//
6647// BB2:
6648// %load1 = load %gep0
6649// %load2 = load %gep1
6650// %load3 = load %gep2
6651//
6652// After:
6653// BB0:
6654// %base =
6655// %new_base = gep %base, off0
6656//
6657// BB1:
6658// %new_gep0 = %new_base
6659// %new_gep1 = gep %new_base, off1 - off0
6660// %new_gep2 = gep %new_base, off2 - off0
6661//
6662// BB2:
6663// %load1 = load i32, i32* %new_gep0
6664// %load2 = load i32, i32* %new_gep1
6665// %load3 = load i32, i32* %new_gep2
6666//
6667// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6668// their offsets are smaller enough to fit into the addressing mode.
6669bool CodeGenPrepare::splitLargeGEPOffsets() {
6670 bool Changed = false;
6671 for (auto &Entry : LargeOffsetGEPMap) {
6672 Value *OldBase = Entry.first;
6673 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6674 &LargeOffsetGEPs = Entry.second;
6675 auto compareGEPOffset =
6676 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6677 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6678 if (LHS.first == RHS.first)
6679 return false;
6680 if (LHS.second != RHS.second)
6681 return LHS.second < RHS.second;
6682 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6683 };
6684 // Sorting all the GEPs of the same data structures based on the offsets.
6685 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
6686 LargeOffsetGEPs.erase(llvm::unique(LargeOffsetGEPs), LargeOffsetGEPs.end());
6687 // Skip if all the GEPs have the same offsets.
6688 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6689 continue;
6690 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6691 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6692 Value *NewBaseGEP = nullptr;
6693
6694 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6695 GetElementPtrInst *GEP) {
6696 LLVMContext &Ctx = GEP->getContext();
6697 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6698 Type *I8PtrTy =
6699 PointerType::get(Ctx, GEP->getType()->getPointerAddressSpace());
6700
6701 BasicBlock::iterator NewBaseInsertPt;
6702 BasicBlock *NewBaseInsertBB;
6703 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
6704 // If the base of the struct is an instruction, the new base will be
6705 // inserted close to it.
6706 NewBaseInsertBB = BaseI->getParent();
6707 if (isa<PHINode>(BaseI))
6708 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6709 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
6710 NewBaseInsertBB =
6711 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest(), &getDT(), LI);
6712 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6713 } else
6714 NewBaseInsertPt = std::next(BaseI->getIterator());
6715 } else {
6716 // If the current base is an argument or global value, the new base
6717 // will be inserted to the entry block.
6718 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6719 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6720 }
6721 IRBuilder<> NewBaseBuilder(NewBaseInsertPt);
6722 // Create a new base.
6723 // TODO: Avoid implicit trunc?
6724 // See https://github.com/llvm/llvm-project/issues/112510.
6725 Value *BaseIndex =
6726 ConstantInt::getSigned(PtrIdxTy, BaseOffset, /*ImplicitTrunc=*/true);
6727 NewBaseGEP = OldBase;
6728 if (NewBaseGEP->getType() != I8PtrTy)
6729 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
6730 NewBaseGEP =
6731 NewBaseBuilder.CreatePtrAdd(NewBaseGEP, BaseIndex, "splitgep");
6732 NewGEPBases.insert(NewBaseGEP);
6733 return;
6734 };
6735
6736 // Check whether all the offsets can be encoded with prefered common base.
6737 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6738 LargeOffsetGEPs.front().second, LargeOffsetGEPs.back().second)) {
6739 BaseOffset = PreferBase;
6740 // Create a new base if the offset of the BaseGEP can be decoded with one
6741 // instruction.
6742 createNewBase(BaseOffset, OldBase, BaseGEP);
6743 }
6744
6745 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6746 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6747 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6748 int64_t Offset = LargeOffsetGEP->second;
6749 if (Offset != BaseOffset) {
6750 TargetLowering::AddrMode AddrMode;
6751 AddrMode.HasBaseReg = true;
6752 AddrMode.BaseOffs = Offset - BaseOffset;
6753 // The result type of the GEP might not be the type of the memory
6754 // access.
6756 GEP->getResultElementType(),
6757 GEP->getAddressSpace())) {
6758 // We need to create a new base if the offset to the current base is
6759 // too large to fit into the addressing mode. So, a very large struct
6760 // may be split into several parts.
6761 BaseGEP = GEP;
6762 BaseOffset = Offset;
6763 NewBaseGEP = nullptr;
6764 }
6765 }
6766
6767 // Generate a new GEP to replace the current one.
6768 Type *PtrIdxTy = DL->getIndexType(GEP->getType());
6769
6770 if (!NewBaseGEP) {
6771 // Create a new base if we don't have one yet. Find the insertion
6772 // pointer for the new base first.
6773 createNewBase(BaseOffset, OldBase, GEP);
6774 }
6775
6776 IRBuilder<> Builder(GEP);
6777 Value *NewGEP = NewBaseGEP;
6778 if (Offset != BaseOffset) {
6779 // Calculate the new offset for the new GEP.
6780 Value *Index = ConstantInt::get(PtrIdxTy, Offset - BaseOffset);
6781 NewGEP = Builder.CreatePtrAdd(NewBaseGEP, Index);
6782 }
6783 replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
6784 LargeOffsetGEPID.erase(GEP);
6785 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
6786 GEP->eraseFromParent();
6787 Changed = true;
6788 }
6789 }
6790 return Changed;
6791}
6792
6793bool CodeGenPrepare::optimizePhiType(
6794 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6795 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6796 // We are looking for a collection on interconnected phi nodes that together
6797 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6798 // are of the same type. Convert the whole set of nodes to the type of the
6799 // bitcast.
6800 Type *PhiTy = I->getType();
6801 Type *ConvertTy = nullptr;
6802 if (Visited.count(I) ||
6803 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6804 return false;
6805
6806 SmallVector<Instruction *, 4> Worklist;
6807 Worklist.push_back(cast<Instruction>(I));
6808 SmallPtrSet<PHINode *, 4> PhiNodes;
6809 SmallPtrSet<ConstantData *, 4> Constants;
6810 PhiNodes.insert(I);
6811 Visited.insert(I);
6812 SmallPtrSet<Instruction *, 4> Defs;
6813 SmallPtrSet<Instruction *, 4> Uses;
6814 // This works by adding extra bitcasts between load/stores and removing
6815 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
6816 // we can get in the situation where we remove a bitcast in one iteration
6817 // just to add it again in the next. We need to ensure that at least one
6818 // bitcast we remove are anchored to something that will not change back.
6819 bool AnyAnchored = false;
6820
6821 while (!Worklist.empty()) {
6822 Instruction *II = Worklist.pop_back_val();
6823
6824 if (auto *Phi = dyn_cast<PHINode>(II)) {
6825 // Handle Defs, which might also be PHI's
6826 for (Value *V : Phi->incoming_values()) {
6827 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6828 if (!PhiNodes.count(OpPhi)) {
6829 if (!Visited.insert(OpPhi).second)
6830 return false;
6831 PhiNodes.insert(OpPhi);
6832 Worklist.push_back(OpPhi);
6833 }
6834 } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
6835 if (!OpLoad->isSimple())
6836 return false;
6837 if (Defs.insert(OpLoad).second)
6838 Worklist.push_back(OpLoad);
6839 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
6840 if (Defs.insert(OpEx).second)
6841 Worklist.push_back(OpEx);
6842 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6843 if (!ConvertTy)
6844 ConvertTy = OpBC->getOperand(0)->getType();
6845 if (OpBC->getOperand(0)->getType() != ConvertTy)
6846 return false;
6847 if (Defs.insert(OpBC).second) {
6848 Worklist.push_back(OpBC);
6849 AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
6850 !isa<ExtractElementInst>(OpBC->getOperand(0));
6851 }
6852 } else if (auto *OpC = dyn_cast<ConstantData>(V))
6853 Constants.insert(OpC);
6854 else
6855 return false;
6856 }
6857 }
6858
6859 // Handle uses which might also be phi's
6860 for (User *V : II->users()) {
6861 if (auto *OpPhi = dyn_cast<PHINode>(V)) {
6862 if (!PhiNodes.count(OpPhi)) {
6863 if (Visited.count(OpPhi))
6864 return false;
6865 PhiNodes.insert(OpPhi);
6866 Visited.insert(OpPhi);
6867 Worklist.push_back(OpPhi);
6868 }
6869 } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
6870 if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
6871 return false;
6872 Uses.insert(OpStore);
6873 } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
6874 if (!ConvertTy)
6875 ConvertTy = OpBC->getType();
6876 if (OpBC->getType() != ConvertTy)
6877 return false;
6878 Uses.insert(OpBC);
6879 AnyAnchored |=
6880 any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
6881 } else {
6882 return false;
6883 }
6884 }
6885 }
6886
6887 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
6888 !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
6889 return false;
6890
6891 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
6892 << *ConvertTy << "\n");
6893
6894 // Create all the new phi nodes of the new type, and bitcast any loads to the
6895 // correct type.
6896 ValueToValueMap ValMap;
6897 for (ConstantData *C : Constants)
6898 ValMap[C] = ConstantExpr::getBitCast(C, ConvertTy);
6899 for (Instruction *D : Defs) {
6900 if (isa<BitCastInst>(D)) {
6901 ValMap[D] = D->getOperand(0);
6902 DeletedInstrs.insert(D);
6903 } else {
6904 BasicBlock::iterator insertPt = std::next(D->getIterator());
6905 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
6906 }
6907 }
6908 for (PHINode *Phi : PhiNodes)
6909 ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
6910 Phi->getName() + ".tc", Phi->getIterator());
6911 // Pipe together all the PhiNodes.
6912 for (PHINode *Phi : PhiNodes) {
6913 PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
6914 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
6915 NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
6916 Phi->getIncomingBlock(i));
6917 Visited.insert(NewPhi);
6918 }
6919 // And finally pipe up the stores and bitcasts
6920 for (Instruction *U : Uses) {
6921 if (isa<BitCastInst>(U)) {
6922 DeletedInstrs.insert(U);
6923 replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
6924 } else {
6925 U->setOperand(0, new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc",
6926 U->getIterator()));
6927 }
6928 }
6929
6930 // Save the removed phis to be deleted later.
6931 DeletedInstrs.insert_range(PhiNodes);
6932 return true;
6933}
6934
6935bool CodeGenPrepare::optimizePhiTypes(Function &F) {
6936 if (!Opts.cgp_optimize_phi_types)
6937 return false;
6938
6939 bool Changed = false;
6940 SmallPtrSet<PHINode *, 4> Visited;
6941 SmallPtrSet<Instruction *, 4> DeletedInstrs;
6942
6943 // Attempt to optimize all the phis in the functions to the correct type.
6944 for (auto &BB : F)
6945 for (auto &Phi : BB.phis())
6946 Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
6947
6948 // Remove any old phi's that have been converted.
6949 for (auto *I : DeletedInstrs) {
6950 replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
6951 I->eraseFromParent();
6952 }
6953
6954 return Changed;
6955}
6956
6957/// Return true, if an ext(load) can be formed from an extension in
6958/// \p MovedExts.
6959bool CodeGenPrepare::canFormExtLd(
6960 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
6961 Instruction *&Inst, bool HasPromoted) {
6962 for (auto *MovedExtInst : MovedExts) {
6963 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
6964 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
6965 Inst = MovedExtInst;
6966 break;
6967 }
6968 }
6969 if (!LI)
6970 return false;
6971
6972 // If they're already in the same block, there's nothing to do.
6973 // Make the cheap checks first if we did not promote.
6974 // If we promoted, we need to check if it is indeed profitable.
6975 if (!HasPromoted && LI->getParent() == Inst->getParent())
6976 return false;
6977
6978 return TLI->isExtLoad(LI, Inst, *DL);
6979}
6980
6981/// Move a zext or sext fed by a load into the same basic block as the load,
6982/// unless conditions are unfavorable. This allows SelectionDAG to fold the
6983/// extend into the load.
6984///
6985/// E.g.,
6986/// \code
6987/// %ld = load i32* %addr
6988/// %add = add nuw i32 %ld, 4
6989/// %zext = zext i32 %add to i64
6990// \endcode
6991/// =>
6992/// \code
6993/// %ld = load i32* %addr
6994/// %zext = zext i32 %ld to i64
6995/// %add = add nuw i64 %zext, 4
6996/// \encode
6997/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
6998/// allow us to match zext(load i32*) to i64.
6999///
7000/// Also, try to promote the computations used to obtain a sign extended
7001/// value used into memory accesses.
7002/// E.g.,
7003/// \code
7004/// a = add nsw i32 b, 3
7005/// d = sext i32 a to i64
7006/// e = getelementptr ..., i64 d
7007/// \endcode
7008/// =>
7009/// \code
7010/// f = sext i32 b to i64
7011/// a = add nsw i64 f, 3
7012/// e = getelementptr ..., i64 a
7013/// \endcode
7014///
7015/// \p Inst[in/out] the extension may be modified during the process if some
7016/// promotions apply.
7017bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7018 bool AllowPromotionWithoutCommonHeader = false;
7019 /// See if it is an interesting sext operations for the address type
7020 /// promotion before trying to promote it, e.g., the ones with the right
7021 /// type and used in memory accesses.
7022 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7023 *Inst, AllowPromotionWithoutCommonHeader);
7024 TypePromotionTransaction TPT(RemovedInsts);
7025 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7026 TPT.getRestorationPoint();
7028 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7029 Exts.push_back(Inst);
7030
7031 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
7032
7033 // Look for a load being extended.
7034 LoadInst *LI = nullptr;
7035 Instruction *ExtFedByLoad;
7036
7037 // Try to promote a chain of computation if it allows to form an extended
7038 // load.
7039 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
7040 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7041 TPT.commit();
7042 // Move the extend into the same block as the load.
7043 ExtFedByLoad->moveAfter(LI);
7044 ++NumExtsMoved;
7045 Inst = ExtFedByLoad;
7046 return true;
7047 }
7048
7049 // Continue promoting SExts if known as considerable depending on targets.
7050 if (ATPConsiderable &&
7051 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7052 HasPromoted, TPT, SpeculativelyMovedExts))
7053 return true;
7054
7055 TPT.rollback(LastKnownGood);
7056 return false;
7057}
7058
7059// Perform address type promotion if doing so is profitable.
7060// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7061// instructions that sign extended the same initial value. However, if
7062// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7063// extension is just profitable.
7064bool CodeGenPrepare::performAddressTypePromotion(
7065 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7066 bool HasPromoted, TypePromotionTransaction &TPT,
7067 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7068 bool Promoted = false;
7069 SmallPtrSet<Instruction *, 1> UnhandledExts;
7070 bool AllSeenFirst = true;
7071 for (auto *I : SpeculativelyMovedExts) {
7072 Value *HeadOfChain = I->getOperand(0);
7073 auto AlreadySeen = SeenChainsForSExt.find(HeadOfChain);
7074 // If there is an unhandled SExt which has the same header, try to promote
7075 // it as well.
7076 if (AlreadySeen != SeenChainsForSExt.end()) {
7077 if (AlreadySeen->second != nullptr)
7078 UnhandledExts.insert(AlreadySeen->second);
7079 AllSeenFirst = false;
7080 }
7081 }
7082
7083 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7084 SpeculativelyMovedExts.size() == 1)) {
7085 TPT.commit();
7086 if (HasPromoted)
7087 Promoted = true;
7088 for (auto *I : SpeculativelyMovedExts) {
7089 Value *HeadOfChain = I->getOperand(0);
7090 SeenChainsForSExt[HeadOfChain] = nullptr;
7091 ValToSExtendedUses[HeadOfChain].push_back(I);
7092 }
7093 // Update Inst as promotion happen.
7094 Inst = SpeculativelyMovedExts.pop_back_val();
7095 } else {
7096 // This is the first chain visited from the header, keep the current chain
7097 // as unhandled. Defer to promote this until we encounter another SExt
7098 // chain derived from the same header.
7099 for (auto *I : SpeculativelyMovedExts) {
7100 Value *HeadOfChain = I->getOperand(0);
7101 SeenChainsForSExt[HeadOfChain] = Inst;
7102 }
7103 return false;
7104 }
7105
7106 if (!AllSeenFirst && !UnhandledExts.empty())
7107 for (auto *VisitedSExt : UnhandledExts) {
7108 if (RemovedInsts.count(VisitedSExt))
7109 continue;
7110 TypePromotionTransaction TPT(RemovedInsts);
7112 SmallVector<Instruction *, 2> Chains;
7113 Exts.push_back(VisitedSExt);
7114 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
7115 TPT.commit();
7116 if (HasPromoted)
7117 Promoted = true;
7118 for (auto *I : Chains) {
7119 Value *HeadOfChain = I->getOperand(0);
7120 // Mark this as handled.
7121 SeenChainsForSExt[HeadOfChain] = nullptr;
7122 ValToSExtendedUses[HeadOfChain].push_back(I);
7123 }
7124 }
7125 return Promoted;
7126}
7127
7128bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7129 BasicBlock *DefBB = I->getParent();
7130
7131 // If the result of a {s|z}ext and its source are both live out, rewrite all
7132 // other uses of the source with result of extension.
7133 Value *Src = I->getOperand(0);
7134 if (Src->hasOneUse())
7135 return false;
7136
7137 // Only do this xform if truncating is free.
7138 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
7139 return false;
7140
7141 // Only safe to perform the optimization if the source is also defined in
7142 // this block.
7143 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
7144 return false;
7145
7146 bool DefIsLiveOut = false;
7147 for (Instruction *UI : I->users()) {
7148 // Figure out which BB this ext is used in.
7149 BasicBlock *UserBB = UI->getParent();
7150 if (UserBB == DefBB)
7151 continue;
7152 DefIsLiveOut = true;
7153 break;
7154 }
7155 if (!DefIsLiveOut)
7156 return false;
7157
7158 // Make sure none of the uses are PHI nodes.
7159 for (User *U : Src->users()) {
7161 BasicBlock *UserBB = UI->getParent();
7162 if (UserBB == DefBB)
7163 continue;
7164 // Be conservative. We don't want this xform to end up introducing
7165 // reloads just before load / store instructions.
7166 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
7167 return false;
7168 }
7169
7170 // InsertedTruncs - Only insert one trunc in each block once.
7171 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7172
7173 bool MadeChange = false;
7174 for (Use &U : make_early_inc_range(Src->uses())) {
7175 Instruction *User = cast<Instruction>(U.getUser());
7176
7177 // Figure out which BB this ext is used in.
7178 BasicBlock *UserBB = User->getParent();
7179 if (UserBB == DefBB)
7180 continue;
7181
7182 // Both src and def are live in this block. Rewrite the use.
7183 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7184
7185 if (!InsertedTrunc) {
7186 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7187 assert(InsertPt != UserBB->end());
7188 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7189 InsertedTrunc->insertBefore(*UserBB, InsertPt);
7190 InsertedInsts.insert(InsertedTrunc);
7191 }
7192
7193 // Replace a use of the {s|z}ext source with a use of the result.
7194 U = InsertedTrunc;
7195 ++NumExtUses;
7196 MadeChange = true;
7197 }
7198
7199 // The uses rewritten above read trunc(I), which equals Src only where I isn't
7200 // poison. A poison-generating flag such as zext nneg can only hold under a
7201 // guard, such as a sign check of Src, that itself is one of those uses.
7202 if (MadeChange)
7203 I->dropPoisonGeneratingFlags();
7204
7205 return MadeChange;
7206}
7207
7208// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7209// just after the load if the target can fold this into one extload instruction,
7210// with the hope of eliminating some of the other later "and" instructions using
7211// the loaded value. "and"s that are made trivially redundant by the insertion
7212// of the new "and" are removed by this function, while others (e.g. those whose
7213// path from the load goes through a phi) are left for isel to potentially
7214// remove.
7215//
7216// For example:
7217//
7218// b0:
7219// x = load i32
7220// ...
7221// b1:
7222// y = and x, 0xff
7223// z = use y
7224//
7225// becomes:
7226//
7227// b0:
7228// x = load i32
7229// x' = and x, 0xff
7230// ...
7231// b1:
7232// z = use x'
7233//
7234// whereas:
7235//
7236// b0:
7237// x1 = load i32
7238// ...
7239// b1:
7240// x2 = load i32
7241// ...
7242// b2:
7243// x = phi x1, x2
7244// y = and x, 0xff
7245//
7246// becomes (after a call to optimizeLoadExt for each load):
7247//
7248// b0:
7249// x1 = load i32
7250// x1' = and x1, 0xff
7251// ...
7252// b1:
7253// x2 = load i32
7254// x2' = and x2, 0xff
7255// ...
7256// b2:
7257// x = phi x1', x2'
7258// y = and x, 0xff
7259bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7260 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7261 return false;
7262
7263 // Skip loads we've already transformed.
7264 if (Load->hasOneUse() && InsertedInsts.count(*Load->user_begin()))
7265 return false;
7266
7267 // Look at all uses of Load, looking through phis, to determine how many bits
7268 // of the loaded value are needed.
7269 SmallVector<Instruction *, 8> WorkList;
7270 SmallPtrSet<Instruction *, 16> Visited;
7271 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7272 SmallVector<Instruction *, 8> DropFlags;
7273 for (Instruction *U : Load->users())
7274 WorkList.push_back(U);
7275
7276 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
7277 unsigned BitWidth = LoadResultVT.getSizeInBits();
7278 // If the BitWidth is 0, do not try to optimize the type
7279 if (BitWidth == 0)
7280 return false;
7281
7282 APInt DemandBits(BitWidth, 0);
7283 APInt WidestAndBits(BitWidth, 0);
7284
7285 while (!WorkList.empty()) {
7286 Instruction *I = WorkList.pop_back_val();
7287
7288 // Break use-def graph loops.
7289 if (!Visited.insert(I).second)
7290 continue;
7291
7292 // For a PHI node, push all of its users.
7293 if (auto *Phi = dyn_cast<PHINode>(I)) {
7294 for (Instruction *U : Phi->users())
7295 WorkList.push_back(U);
7296 continue;
7297 }
7298
7299 switch (I->getOpcode()) {
7300 case Instruction::And: {
7301 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
7302 if (!AndC)
7303 return false;
7304 APInt AndBits = AndC->getValue();
7305 DemandBits |= AndBits;
7306 // Keep track of the widest and mask we see.
7307 if (AndBits.ugt(WidestAndBits))
7308 WidestAndBits = AndBits;
7309 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
7310 AndsToMaybeRemove.push_back(I);
7311 break;
7312 }
7313
7314 case Instruction::Shl: {
7315 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
7316 if (!ShlC)
7317 return false;
7318 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
7319 DemandBits.setLowBits(BitWidth - ShiftAmt);
7320 DropFlags.push_back(I);
7321 break;
7322 }
7323
7324 case Instruction::Trunc: {
7325 EVT TruncVT = TLI->getValueType(*DL, I->getType());
7326 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7327 DemandBits.setLowBits(TruncBitWidth);
7328 DropFlags.push_back(I);
7329 break;
7330 }
7331
7332 default:
7333 return false;
7334 }
7335 }
7336
7337 uint32_t ActiveBits = DemandBits.getActiveBits();
7338 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7339 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7340 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7341 // true, but (and (load x) 1) is not matched as a single instruction, rather
7342 // as a LDR followed by an AND.
7343 // TODO: Look into removing this restriction by fixing backends to either
7344 // return false for isLoadLegal for i1 or have them select this pattern to
7345 // a single instruction.
7346 //
7347 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7348 // mask, since these are the only ands that will be removed by isel.
7349 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
7350 WidestAndBits != DemandBits)
7351 return false;
7352
7353 LLVMContext &Ctx = Load->getType()->getContext();
7354 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
7355 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
7356
7357 // Reject cases that won't be matched as extloads.
7358 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
7359 !TLI->isLoadLegal(LoadResultVT, TruncVT, Load->getAlign(),
7360 Load->getPointerAddressSpace(), ISD::ZEXTLOAD, false))
7361 return false;
7362
7363 IRBuilder<> Builder(Load->getNextNode());
7364 auto *NewAnd = cast<Instruction>(
7365 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
7366 // Mark this instruction as "inserted by CGP", so that other
7367 // optimizations don't touch it.
7368 InsertedInsts.insert(NewAnd);
7369
7370 // Replace all uses of load with new and (except for the use of load in the
7371 // new and itself).
7372 replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
7373 NewAnd->setOperand(0, Load);
7374
7375 // Remove any and instructions that are now redundant.
7376 for (auto *And : AndsToMaybeRemove)
7377 // Check that the and mask is the same as the one we decided to put on the
7378 // new and.
7379 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
7380 replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
7381 if (&*CurInstIterator == And)
7382 CurInstIterator = std::next(And->getIterator());
7383 And->eraseFromParent();
7384 ++NumAndUses;
7385 }
7386
7387 // NSW flags may not longer hold.
7388 for (auto *Inst : DropFlags)
7389 Inst->setHasNoSignedWrap(false);
7390
7391 ++NumAndsAdded;
7392 return true;
7393}
7394
7395/// Check if V (an operand of a select instruction) is an expensive instruction
7396/// that is only used once.
7398 auto *I = dyn_cast<Instruction>(V);
7399 // If it's safe to speculatively execute, then it should not have side
7400 // effects; therefore, it's safe to sink and possibly *not* execute.
7401 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7402 TTI->isExpensiveToSpeculativelyExecute(I);
7403}
7404
7405/// Returns true if a SelectInst should be turned into an explicit branch.
7407 const TargetLowering *TLI,
7408 SelectInst *SI) {
7409 // If even a predictable select is cheap, then a branch can't be cheaper.
7410 if (!TLI->isPredictableSelectExpensive())
7411 return false;
7412
7413 // FIXME: This should use the same heuristics as IfConversion to determine
7414 // whether a select is better represented as a branch.
7415
7416 // If metadata tells us that the select condition is obviously predictable,
7417 // then we want to replace the select with a branch.
7418 uint64_t TrueWeight, FalseWeight;
7419 if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
7420 uint64_t Max = std::max(TrueWeight, FalseWeight);
7421 uint64_t Sum = TrueWeight + FalseWeight;
7422 if (Sum != 0) {
7423 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
7424 if (Probability > TTI->getPredictableBranchThreshold())
7425 return true;
7426 }
7427 }
7428
7429 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
7430
7431 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7432 // comparison condition. If the compare has more than one use, there's
7433 // probably another cmov or setcc around, so it's not worth emitting a branch.
7434 if (!Cmp || !Cmp->hasOneUse())
7435 return false;
7436
7437 // If either operand of the select is expensive and only needed on one side
7438 // of the select, we should form a branch.
7439 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
7440 sinkSelectOperand(TTI, SI->getFalseValue()))
7441 return true;
7442
7443 return false;
7444}
7445
7446/// If \p isTrue is true, return the true value of \p SI, otherwise return
7447/// false value of \p SI. If the true/false value of \p SI is defined by any
7448/// select instructions in \p Selects, look through the defining select
7449/// instruction until the true/false value is not defined in \p Selects.
7450static Value *
7452 const SmallPtrSet<const Instruction *, 2> &Selects) {
7453 Value *V = nullptr;
7454
7455 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
7456 DefSI = dyn_cast<SelectInst>(V)) {
7457 assert(DefSI->getCondition() == SI->getCondition() &&
7458 "The condition of DefSI does not match with SI");
7459 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7460 }
7461
7462 assert(V && "Failed to get select true/false value");
7463 return V;
7464}
7465
7466bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7467 assert(Shift->isShift() && "Expected a shift");
7468
7469 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7470 // general vector shifts, and (3) the shift amount is a select-of-splatted
7471 // values, hoist the shifts before the select:
7472 // shift Op0, (select Cond, TVal, FVal) -->
7473 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7474 //
7475 // This is inverting a generic IR transform when we know that the cost of a
7476 // general vector shift is more than the cost of 2 shift-by-scalars.
7477 // We can't do this effectively in SDAG because we may not be able to
7478 // determine if the select operands are splats from within a basic block.
7479 Type *Ty = Shift->getType();
7480 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7481 return false;
7482 Value *Cond, *TVal, *FVal;
7483 if (!match(Shift->getOperand(1),
7484 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7485 return false;
7486 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7487 return false;
7488
7489 IRBuilder<> Builder(Shift);
7490 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7491 Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
7492 Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
7493 // The new select has the same condition, so it keeps the profile metadata.
7494 Value *NewSel = Builder.CreateSelect(
7495 Cond, NewTVal, NewFVal, "",
7497 : cast<Instruction>(Shift->getOperand(1)));
7498 replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
7499 Shift->eraseFromParent();
7500 return true;
7501}
7502
7503bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7504 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7505 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7506 "Expected a funnel shift");
7507
7508 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7509 // than general vector shifts, and (3) the shift amount is select-of-splatted
7510 // values, hoist the funnel shifts before the select:
7511 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7512 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7513 //
7514 // This is inverting a generic IR transform when we know that the cost of a
7515 // general vector shift is more than the cost of 2 shift-by-scalars.
7516 // We can't do this effectively in SDAG because we may not be able to
7517 // determine if the select operands are splats from within a basic block.
7518 Type *Ty = Fsh->getType();
7519 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7520 return false;
7521 Value *Cond, *TVal, *FVal;
7522 if (!match(Fsh->getOperand(2),
7523 m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
7524 return false;
7525 if (!isSplatValue(TVal) || !isSplatValue(FVal))
7526 return false;
7527
7528 IRBuilder<> Builder(Fsh);
7529 Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
7530 Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
7531 Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
7532 Value *NewSel = Builder.CreateSelect(
7533 Cond, NewTVal, NewFVal, "",
7535 : cast<Instruction>(Fsh->getOperand(2)));
7536 replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
7537 Fsh->eraseFromParent();
7538 return true;
7539}
7540
7541/// If we have a SelectInst that will likely profit from branch prediction,
7542/// turn it into a branch.
7543bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7544 if (!Opts.cgp_select2branch)
7545 return false;
7546
7547 // If the SelectOptimize pass is enabled, selects have already been optimized.
7548 if (!Opts.disable_select_optimize)
7549 return false;
7550
7551 // Find all consecutive select instructions that share the same condition.
7553 ASI.push_back(SI);
7555 It != SI->getParent()->end(); ++It) {
7556 SelectInst *I = dyn_cast<SelectInst>(&*It);
7557 if (I && SI->getCondition() == I->getCondition()) {
7558 ASI.push_back(I);
7559 } else {
7560 break;
7561 }
7562 }
7563
7564 SelectInst *LastSI = ASI.back();
7565 // Increment the current iterator to skip all the rest of select instructions
7566 // because they will be either "not lowered" or "all lowered" to branch.
7567 CurInstIterator = std::next(LastSI->getIterator());
7568 // Examine debug-info attached to the consecutive select instructions. They
7569 // won't be individually optimised by optimizeInst, so we need to perform
7570 // DbgVariableRecord maintenence here instead.
7571 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7572 fixupDbgVariableRecordsOnInst(*SI);
7573
7574 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
7575
7576 // Can we convert the 'select' to CF ?
7577 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
7578 return false;
7579
7580 TargetLowering::SelectSupportKind SelectKind;
7581 if (SI->getType()->isVectorTy())
7582 SelectKind = TargetLowering::ScalarCondVectorVal;
7583 else
7584 SelectKind = TargetLowering::ScalarValSelect;
7585
7586 if (TLI->isSelectSupported(SelectKind) &&
7588 llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI)))
7589 return false;
7590
7591 // Transform a sequence like this:
7592 // start:
7593 // %cmp = cmp uge i32 %a, %b
7594 // %sel = select i1 %cmp, i32 %c, i32 %d
7595 //
7596 // Into:
7597 // start:
7598 // %cmp = cmp uge i32 %a, %b
7599 // %cmp.frozen = freeze %cmp
7600 // br i1 %cmp.frozen, label %select.true, label %select.false
7601 // select.true:
7602 // br label %select.end
7603 // select.false:
7604 // br label %select.end
7605 // select.end:
7606 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7607 //
7608 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7609 // In addition, we may sink instructions that produce %c or %d from
7610 // the entry block into the destination(s) of the new branch.
7611 // If the true or false blocks do not contain a sunken instruction, that
7612 // block and its branch may be optimized away. In that case, one side of the
7613 // first branch will point directly to select.end, and the corresponding PHI
7614 // predecessor block will be the start block.
7615 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7616 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7617 // runOnFunction for each select optimized.
7618
7619 // Collect values that go on the true side and the values that go on the false
7620 // side.
7621 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7622 for (SelectInst *SI : ASI) {
7623 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7624 TrueInstrs.push_back(cast<Instruction>(V));
7625 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7626 FalseInstrs.push_back(cast<Instruction>(V));
7627 }
7628
7629 // Split the select block, according to how many (if any) values go on each
7630 // side.
7631 BasicBlock *StartBlock = SI->getParent();
7632 BasicBlock::iterator SplitPt = std::next(BasicBlock::iterator(LastSI));
7633 // We should split before any debug-info.
7634 SplitPt.setHeadBit(true);
7635
7636 IRBuilder<> IB(SI);
7637 auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
7638
7639 BasicBlock *TrueBlock = nullptr;
7640 BasicBlock *FalseBlock = nullptr;
7641 BasicBlock *EndBlock = nullptr;
7642 UncondBrInst *TrueBranch = nullptr;
7643 UncondBrInst *FalseBranch = nullptr;
7644 if (TrueInstrs.size() == 0) {
7645 FalseBranch = cast<UncondBrInst>(
7646 SplitBlockAndInsertIfElse(CondFr, SplitPt, false, nullptr, DTU, LI));
7647 FalseBlock = FalseBranch->getParent();
7648 EndBlock = cast<BasicBlock>(FalseBranch->getOperand(0));
7649 } else if (FalseInstrs.size() == 0) {
7650 TrueBranch = cast<UncondBrInst>(
7651 SplitBlockAndInsertIfThen(CondFr, SplitPt, false, nullptr, DTU, LI));
7652 TrueBlock = TrueBranch->getParent();
7653 EndBlock = TrueBranch->getSuccessor();
7654 } else {
7655 Instruction *ThenTerm = nullptr;
7656 Instruction *ElseTerm = nullptr;
7657 SplitBlockAndInsertIfThenElse(CondFr, SplitPt, &ThenTerm, &ElseTerm,
7658 nullptr, DTU, LI);
7659 TrueBranch = cast<UncondBrInst>(ThenTerm);
7660 FalseBranch = cast<UncondBrInst>(ElseTerm);
7661 TrueBlock = TrueBranch->getParent();
7662 FalseBlock = FalseBranch->getParent();
7663 EndBlock = TrueBranch->getSuccessor();
7664 }
7665
7666 EndBlock->setName("select.end");
7667 if (TrueBlock)
7668 TrueBlock->setName("select.true.sink");
7669 if (FalseBlock)
7670 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7671 : "select.false.sink");
7672
7673 if (IsHugeFunc) {
7674 if (TrueBlock)
7675 FreshBBs.insert(TrueBlock);
7676 if (FalseBlock)
7677 FreshBBs.insert(FalseBlock);
7678 FreshBBs.insert(EndBlock);
7679 }
7680
7681 BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock));
7682
7683 static const unsigned MD[] = {
7684 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7685 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7686 StartBlock->getTerminator()->copyMetadata(*SI, MD);
7687
7688 // Sink expensive instructions into the conditional blocks to avoid executing
7689 // them speculatively.
7690 for (Instruction *I : TrueInstrs)
7691 I->moveBefore(TrueBranch->getIterator());
7692 for (Instruction *I : FalseInstrs)
7693 I->moveBefore(FalseBranch->getIterator());
7694
7695 // If we did not create a new block for one of the 'true' or 'false' paths
7696 // of the condition, it means that side of the branch goes to the end block
7697 // directly and the path originates from the start block from the point of
7698 // view of the new PHI.
7699 if (TrueBlock == nullptr)
7700 TrueBlock = StartBlock;
7701 else if (FalseBlock == nullptr)
7702 FalseBlock = StartBlock;
7703
7704 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7705 // Use reverse iterator because later select may use the value of the
7706 // earlier select, and we need to propagate value through earlier select
7707 // to get the PHI operand.
7708 for (SelectInst *SI : llvm::reverse(ASI)) {
7709 // The select itself is replaced with a PHI Node.
7710 PHINode *PN = PHINode::Create(SI->getType(), 2, "");
7711 PN->insertBefore(EndBlock->begin());
7712 PN->takeName(SI);
7713 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
7714 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
7715 PN->setDebugLoc(SI->getDebugLoc());
7716
7717 replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
7718 SI->eraseFromParent();
7719 INS.erase(SI);
7720 ++NumSelectsExpanded;
7721 }
7722
7723 // Instruct OptimizeBlock to skip to the next block.
7724 CurInstIterator = StartBlock->end();
7725 return true;
7726}
7727
7728/// Some targets only accept certain types for splat inputs. For example a VDUP
7729/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7730/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7731bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7732 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7734 m_Undef(), m_ZeroMask())))
7735 return false;
7736 Type *NewType = TLI->shouldConvertSplatType(SVI);
7737 if (!NewType)
7738 return false;
7739
7740 auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
7741 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7742 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7743 "Expected a type of the same size!");
7744 auto *NewVecType =
7745 FixedVectorType::get(NewType, SVIVecType->getNumElements());
7746
7747 // Create a bitcast (shuffle (insert (bitcast(..))))
7748 IRBuilder<> Builder(SVI);
7749 Value *BC1 = Builder.CreateBitCast(
7750 cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
7751 Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
7752 Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
7753
7754 replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
7756 SVI, TLInfo, nullptr,
7757 [&](Value *V) { removeAllAssertingVHReferences(V); });
7758
7759 // Also hoist the bitcast up to its operand if it they are not in the same
7760 // block.
7761 if (auto *BCI = dyn_cast<Instruction>(BC1))
7762 if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
7763 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
7764 !Op->isTerminator() && !Op->isEHPad())
7765 BCI->moveAfter(Op);
7766
7767 return true;
7768}
7769
7770bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7771 // If the operands of I can be folded into a target instruction together with
7772 // I, duplicate and sink them.
7773 SmallVector<Use *, 4> OpsToSink;
7774 if (!TTI->isProfitableToSinkOperands(I, OpsToSink, LI))
7775 return false;
7776
7777 // OpsToSink can contain multiple uses in a use chain (e.g.
7778 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7779 // uses must come first, so we process the ops in reverse order so as to not
7780 // create invalid IR.
7781 BasicBlock *TargetBB = I->getParent();
7782 bool Changed = false;
7783 SmallVector<Use *, 4> ToReplace;
7784 Instruction *InsertPoint = I;
7785 for (Use *U : reverse(OpsToSink)) {
7786 auto *UI = cast<Instruction>(U->get());
7787 if (isa<PHINode>(UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7788 continue;
7789 if (UI->getParent() == TargetBB) {
7790 if (UI->comesBefore(InsertPoint))
7791 InsertPoint = UI;
7792 continue;
7793 }
7794 ToReplace.push_back(U);
7795 }
7796
7797 SetVector<Instruction *> MaybeDead;
7798 DenseMap<Instruction *, Instruction *> NewInstructions;
7799 for (Use *U : ToReplace) {
7800 auto *UI = cast<Instruction>(U->get());
7801 Instruction *NI = UI->clone();
7802
7803 if (IsHugeFunc) {
7804 // Now we clone an instruction, its operands' defs may sink to this BB
7805 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7806 for (Value *Op : NI->operands())
7807 if (auto *OpDef = dyn_cast<Instruction>(Op))
7808 FreshBBs.insert(OpDef->getParent());
7809 }
7810
7811 NewInstructions[UI] = NI;
7812 MaybeDead.insert(UI);
7813 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7814 NI->insertBefore(InsertPoint->getIterator());
7815 InsertPoint = NI;
7816 InsertedInsts.insert(NI);
7817
7818 // Update the use for the new instruction, making sure that we update the
7819 // sunk instruction uses, if it is part of a chain that has already been
7820 // sunk.
7821 Instruction *OldI = cast<Instruction>(U->getUser());
7822 if (auto It = NewInstructions.find(OldI); It != NewInstructions.end())
7823 It->second->setOperand(U->getOperandNo(), NI);
7824 else
7825 U->set(NI);
7826 Changed = true;
7827 }
7828
7829 // Remove instructions that are dead after sinking.
7830 for (auto *I : MaybeDead) {
7831 if (!I->hasNUsesOrMore(1)) {
7832 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
7833 I->eraseFromParent();
7834 }
7835 }
7836
7837 return Changed;
7838}
7839
7840bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
7841 Value *Cond = SI->getCondition();
7842 Type *OldType = Cond->getType();
7843 LLVMContext &Context = Cond->getContext();
7844 EVT OldVT = TLI->getValueType(*DL, OldType);
7846 unsigned RegWidth = RegType.getSizeInBits();
7847
7848 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
7849 return false;
7850
7851 // If the register width is greater than the type width, expand the condition
7852 // of the switch instruction and each case constant to the width of the
7853 // register. By widening the type of the switch condition, subsequent
7854 // comparisons (for case comparisons) will not need to be extended to the
7855 // preferred register width, so we will potentially eliminate N-1 extends,
7856 // where N is the number of cases in the switch.
7857 auto *NewType = Type::getIntNTy(Context, RegWidth);
7858
7859 // Extend the switch condition and case constants using the target preferred
7860 // extend unless the switch condition is a function argument with an extend
7861 // attribute. In that case, we can avoid an unnecessary mask/extension by
7862 // matching the argument extension instead.
7863 Instruction::CastOps ExtType = Instruction::ZExt;
7864 // Some targets prefer SExt over ZExt.
7865 if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
7866 ExtType = Instruction::SExt;
7867
7868 if (auto *Arg = dyn_cast<Argument>(Cond)) {
7869 if (Arg->hasSExtAttr())
7870 ExtType = Instruction::SExt;
7871 if (Arg->hasZExtAttr())
7872 ExtType = Instruction::ZExt;
7873 }
7874
7875 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
7876 ExtInst->insertBefore(SI->getIterator());
7877 ExtInst->setDebugLoc(SI->getDebugLoc());
7878 SI->setCondition(ExtInst);
7879 for (auto Case : SI->cases()) {
7880 const APInt &NarrowConst = Case.getCaseValue()->getValue();
7881 APInt WideConst = (ExtType == Instruction::ZExt)
7882 ? NarrowConst.zext(RegWidth)
7883 : NarrowConst.sext(RegWidth);
7884 Case.setValue(ConstantInt::get(Context, WideConst));
7885 }
7886
7887 return true;
7888}
7889
7890bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
7891 // The SCCP optimization tends to produce code like this:
7892 // switch(x) { case 42: phi(42, ...) }
7893 // Materializing the constant for the phi-argument needs instructions; So we
7894 // change the code to:
7895 // switch(x) { case 42: phi(x, ...) }
7896
7897 Value *Condition = SI->getCondition();
7898 // Avoid endless loop in degenerate case.
7899 if (isa<ConstantInt>(*Condition))
7900 return false;
7901
7902 bool Changed = false;
7903 BasicBlock *SwitchBB = SI->getParent();
7904 Type *ConditionType = Condition->getType();
7905
7906 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
7907 ConstantInt *CaseValue = Case.getCaseValue();
7908 BasicBlock *CaseBB = Case.getCaseSuccessor();
7909 // Set to true if we previously checked that `CaseBB` is only reached by
7910 // a single case from this switch.
7911 bool CheckedForSinglePred = false;
7912 for (PHINode &PHI : CaseBB->phis()) {
7913 Type *PHIType = PHI.getType();
7914 // If ZExt is free then we can also catch patterns like this:
7915 // switch((i32)x) { case 42: phi((i64)42, ...); }
7916 // and replace `(i64)42` with `zext i32 %x to i64`.
7917 bool TryZExt =
7918 PHIType->isIntegerTy() &&
7919 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
7920 TLI->isZExtFree(ConditionType, PHIType);
7921 if (PHIType == ConditionType || TryZExt) {
7922 // Set to true to skip this case because of multiple preds.
7923 bool SkipCase = false;
7924 Value *Replacement = nullptr;
7925 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
7926 Value *PHIValue = PHI.getIncomingValue(I);
7927 if (PHIValue != CaseValue) {
7928 if (!TryZExt)
7929 continue;
7930 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
7931 if (!PHIValueInt ||
7932 PHIValueInt->getValue() !=
7933 CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
7934 continue;
7935 }
7936 if (PHI.getIncomingBlock(I) != SwitchBB)
7937 continue;
7938 // We cannot optimize if there are multiple case labels jumping to
7939 // this block. This check may get expensive when there are many
7940 // case labels so we test for it last.
7941 if (!CheckedForSinglePred) {
7942 CheckedForSinglePred = true;
7943 if (SI->findCaseDest(CaseBB) == nullptr) {
7944 SkipCase = true;
7945 break;
7946 }
7947 }
7948
7949 if (Replacement == nullptr) {
7950 if (PHIValue == CaseValue) {
7951 Replacement = Condition;
7952 } else {
7953 IRBuilder<> Builder(SI);
7954 Replacement = Builder.CreateZExt(Condition, PHIType);
7955 }
7956 }
7957 PHI.setIncomingValue(I, Replacement);
7958 Changed = true;
7959 }
7960 if (SkipCase)
7961 break;
7962 }
7963 }
7964 }
7965 return Changed;
7966}
7967
7968bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
7969 bool Changed = optimizeSwitchType(SI);
7970 Changed |= optimizeSwitchPhiConstants(SI);
7971 return Changed;
7972}
7973
7974namespace {
7975
7976/// Helper class to promote a scalar operation to a vector one.
7977/// This class is used to move downward extractelement transition.
7978/// E.g.,
7979/// a = vector_op <2 x i32>
7980/// b = extractelement <2 x i32> a, i32 0
7981/// c = scalar_op b
7982/// store c
7983///
7984/// =>
7985/// a = vector_op <2 x i32>
7986/// c = vector_op a (equivalent to scalar_op on the related lane)
7987/// * d = extractelement <2 x i32> c, i32 0
7988/// * store d
7989/// Assuming both extractelement and store can be combine, we get rid of the
7990/// transition.
7991class VectorPromoteHelper {
7992 /// DataLayout associated with the current module.
7993 const DataLayout &DL;
7994
7995 /// Used to perform some checks on the legality of vector operations.
7996 const TargetLowering &TLI;
7997
7998 /// Used to estimated the cost of the promoted chain.
7999 const TargetTransformInfo &TTI;
8000
8001 /// The transition being moved downwards.
8002 Instruction *Transition;
8003
8004 /// The sequence of instructions to be promoted.
8005 SmallVector<Instruction *, 4> InstsToBePromoted;
8006
8007 /// Cost of combining a store and an extract.
8008 unsigned StoreExtractCombineCost;
8009
8010 bool StressStoreExtract;
8011
8012 /// Instruction that will be combined with the transition.
8013 Instruction *CombineInst = nullptr;
8014
8015 /// The instruction that represents the current end of the transition.
8016 /// Since we are faking the promotion until we reach the end of the chain
8017 /// of computation, we need a way to get the current end of the transition.
8018 Instruction *getEndOfTransition() const {
8019 if (InstsToBePromoted.empty())
8020 return Transition;
8021 return InstsToBePromoted.back();
8022 }
8023
8024 /// Return the index of the original value in the transition.
8025 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8026 /// c, is at index 0.
8027 unsigned getTransitionOriginalValueIdx() const {
8028 assert(isa<ExtractElementInst>(Transition) &&
8029 "Other kind of transitions are not supported yet");
8030 return 0;
8031 }
8032
8033 /// Return the index of the index in the transition.
8034 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8035 /// is at index 1.
8036 unsigned getTransitionIdx() const {
8037 assert(isa<ExtractElementInst>(Transition) &&
8038 "Other kind of transitions are not supported yet");
8039 return 1;
8040 }
8041
8042 /// Get the type of the transition.
8043 /// This is the type of the original value.
8044 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8045 /// transition is <2 x i32>.
8046 Type *getTransitionType() const {
8047 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
8048 }
8049
8050 /// Promote \p ToBePromoted by moving \p Def downward through.
8051 /// I.e., we have the following sequence:
8052 /// Def = Transition <ty1> a to <ty2>
8053 /// b = ToBePromoted <ty2> Def, ...
8054 /// =>
8055 /// b = ToBePromoted <ty1> a, ...
8056 /// Def = Transition <ty1> ToBePromoted to <ty2>
8057 void promoteImpl(Instruction *ToBePromoted);
8058
8059 /// Check whether or not it is profitable to promote all the
8060 /// instructions enqueued to be promoted.
8061 bool isProfitableToPromote() {
8062 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
8063 unsigned Index = isa<ConstantInt>(ValIdx)
8064 ? cast<ConstantInt>(ValIdx)->getZExtValue()
8065 : -1;
8066 Type *PromotedType = getTransitionType();
8067
8068 StoreInst *ST = cast<StoreInst>(CombineInst);
8069 unsigned AS = ST->getPointerAddressSpace();
8070 // Check if this store is supported.
8072 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
8073 ST->getAlign())) {
8074 // If this is not supported, there is no way we can combine
8075 // the extract with the store.
8076 return false;
8077 }
8078
8079 // The scalar chain of computation has to pay for the transition
8080 // scalar to vector.
8081 // The vector chain has to account for the combining cost.
8084 InstructionCost ScalarCost =
8085 TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
8086 InstructionCost VectorCost = StoreExtractCombineCost;
8087 for (const auto &Inst : InstsToBePromoted) {
8088 // Compute the cost.
8089 // By construction, all instructions being promoted are arithmetic ones.
8090 // Moreover, one argument is a constant that can be viewed as a splat
8091 // constant.
8092 Value *Arg0 = Inst->getOperand(0);
8093 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
8094 isa<ConstantFP>(Arg0);
8095 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8096 if (IsArg0Constant)
8098 else
8100
8101 ScalarCost += TTI.getArithmeticInstrCost(
8102 Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
8103 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
8104 CostKind, Arg0Info, Arg1Info);
8105 }
8106 LLVM_DEBUG(
8107 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8108 << ScalarCost << "\nVector: " << VectorCost << '\n');
8109 return ScalarCost > VectorCost;
8110 }
8111
8112 /// Generate a constant vector with \p Val with the same
8113 /// number of elements as the transition.
8114 /// \p UseSplat defines whether or not \p Val should be replicated
8115 /// across the whole vector.
8116 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8117 /// otherwise we generate a vector with as many poison as possible:
8118 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8119 /// used at the index of the extract.
8120 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8121 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8122 if (!UseSplat) {
8123 // If we cannot determine where the constant must be, we have to
8124 // use a splat constant.
8125 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
8126 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
8127 ExtractIdx = CstVal->getSExtValue();
8128 else
8129 UseSplat = true;
8130 }
8131
8132 ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
8133 if (UseSplat)
8134 return ConstantVector::getSplat(EC, Val);
8135
8136 if (!EC.isScalable()) {
8137 SmallVector<Constant *, 4> ConstVec;
8138 PoisonValue *PoisonVal = PoisonValue::get(Val->getType());
8139 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8140 if (Idx == ExtractIdx)
8141 ConstVec.push_back(Val);
8142 else
8143 ConstVec.push_back(PoisonVal);
8144 }
8145 return ConstantVector::get(ConstVec);
8146 } else
8148 "Generate scalable vector for non-splat is unimplemented");
8149 }
8150
8151 /// Check if promoting to a vector type an operand at \p OperandIdx
8152 /// in \p Use can trigger undefined behavior.
8153 static bool canCauseUndefinedBehavior(const Instruction *Use,
8154 unsigned OperandIdx) {
8155 // This is not safe to introduce undef when the operand is on
8156 // the right hand side of a division-like instruction.
8157 if (OperandIdx != 1)
8158 return false;
8159 switch (Use->getOpcode()) {
8160 default:
8161 return false;
8162 case Instruction::SDiv:
8163 case Instruction::UDiv:
8164 case Instruction::SRem:
8165 case Instruction::URem:
8166 return true;
8167 case Instruction::FDiv:
8168 case Instruction::FRem:
8169 return !Use->hasNoNaNs();
8170 }
8171 llvm_unreachable(nullptr);
8172 }
8173
8174public:
8175 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8176 const TargetTransformInfo &TTI, Instruction *Transition,
8177 unsigned CombineCost, bool StressStoreExtract)
8178 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8179 StoreExtractCombineCost(CombineCost),
8180 StressStoreExtract(StressStoreExtract) {
8181 assert(Transition && "Do not know how to promote null");
8182 }
8183
8184 /// Check if we can promote \p ToBePromoted to \p Type.
8185 bool canPromote(const Instruction *ToBePromoted) const {
8186 // We could support CastInst too.
8187 return isa<BinaryOperator>(ToBePromoted);
8188 }
8189
8190 /// Check if it is profitable to promote \p ToBePromoted
8191 /// by moving downward the transition through.
8192 bool shouldPromote(const Instruction *ToBePromoted) const {
8194 return false;
8195 // Promote only if all the operands can be statically expanded.
8196 // Indeed, we do not want to introduce any new kind of transitions.
8197 for (const Use &U : ToBePromoted->operands()) {
8198 const Value *Val = U.get();
8199 if (Val == getEndOfTransition()) {
8200 continue;
8201 }
8202 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8203 !isa<ConstantFP>(Val))
8204 return false;
8205 }
8206 // Check that the resulting operation is legal.
8207 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
8208 if (!ISDOpcode)
8209 return false;
8210 return StressStoreExtract ||
8212 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
8213 }
8214
8215 /// Check whether or not \p Use can be combined
8216 /// with the transition.
8217 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8218 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
8219
8220 /// Record \p ToBePromoted as part of the chain to be promoted.
8221 void enqueueForPromotion(Instruction *ToBePromoted) {
8222 InstsToBePromoted.push_back(ToBePromoted);
8223 }
8224
8225 /// Set the instruction that will be combined with the transition.
8226 void recordCombineInstruction(Instruction *ToBeCombined) {
8227 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8228 CombineInst = ToBeCombined;
8229 }
8230
8231 /// Promote all the instructions enqueued for promotion if it is
8232 /// is profitable.
8233 /// \return True if the promotion happened, false otherwise.
8234 bool promote() {
8235 // Check if there is something to promote.
8236 // Right now, if we do not have anything to combine with,
8237 // we assume the promotion is not profitable.
8238 if (InstsToBePromoted.empty() || !CombineInst)
8239 return false;
8240
8241 // Check cost.
8242 if (!StressStoreExtract && !isProfitableToPromote())
8243 return false;
8244
8245 // Promote.
8246 for (auto &ToBePromoted : InstsToBePromoted)
8247 promoteImpl(ToBePromoted);
8248 InstsToBePromoted.clear();
8249 return true;
8250 }
8251};
8252
8253} // end anonymous namespace
8254
8255void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8256 // At this point, we know that all the operands of ToBePromoted but Def
8257 // can be statically promoted.
8258 // For Def, we need to use its parameter in ToBePromoted:
8259 // b = ToBePromoted ty1 a
8260 // Def = Transition ty1 b to ty2
8261 // Move the transition down.
8262 // 1. Replace all uses of the promoted operation by the transition.
8263 // = ... b => = ... Def.
8264 assert(ToBePromoted->getType() == Transition->getType() &&
8265 "The type of the result of the transition does not match "
8266 "the final type");
8267 ToBePromoted->replaceAllUsesWith(Transition);
8268 // 2. Update the type of the uses.
8269 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8270 Type *TransitionTy = getTransitionType();
8271 ToBePromoted->mutateType(TransitionTy);
8272 // 3. Update all the operands of the promoted operation with promoted
8273 // operands.
8274 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8275 for (Use &U : ToBePromoted->operands()) {
8276 Value *Val = U.get();
8277 Value *NewVal = nullptr;
8278 if (Val == Transition)
8279 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
8280 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8281 isa<ConstantFP>(Val)) {
8282 // Use a splat constant if it is not safe to use undef.
8283 NewVal = getConstantVector(
8284 cast<Constant>(Val),
8285 isa<UndefValue>(Val) ||
8286 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
8287 } else
8288 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8289 "this?");
8290 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
8291 }
8292 Transition->moveAfter(ToBePromoted);
8293 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
8294}
8295
8296/// Some targets can do store(extractelement) with one instruction.
8297/// Try to push the extractelement towards the stores when the target
8298/// has this feature and this is profitable.
8299bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8300 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8301 if (!Opts.cgp_store_extract ||
8302 (!Opts.cgp_stress_store_extract &&
8304 Inst->getOperand(1), CombineCost)))
8305 return false;
8306
8307 // At this point we know that Inst is a vector to scalar transition.
8308 // Try to move it down the def-use chain, until:
8309 // - We can combine the transition with its single use
8310 // => we got rid of the transition.
8311 // - We escape the current basic block
8312 // => we would need to check that we are moving it at a cheaper place and
8313 // we do not do that for now.
8314 BasicBlock *Parent = Inst->getParent();
8315 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8316 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost,
8317 Opts.cgp_stress_store_extract);
8318 // If the transition has more than one use, assume this is not going to be
8319 // beneficial.
8320 while (Inst->hasOneUse()) {
8321 Instruction *ToBePromoted = *Inst->user_begin();
8322 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8323
8324 if (ToBePromoted->getParent() != Parent) {
8325 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8326 << ToBePromoted->getParent()->getName()
8327 << ") than the transition (" << Parent->getName()
8328 << ").\n");
8329 return false;
8330 }
8331
8332 if (VPH.canCombine(ToBePromoted)) {
8333 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8334 << "will be combined with: " << *ToBePromoted << '\n');
8335 VPH.recordCombineInstruction(ToBePromoted);
8336 bool Changed = VPH.promote();
8337 NumStoreExtractExposed += Changed;
8338 return Changed;
8339 }
8340
8341 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8342 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8343 return false;
8344
8345 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8346
8347 VPH.enqueueForPromotion(ToBePromoted);
8348 Inst = ToBePromoted;
8349 }
8350 return false;
8351}
8352
8353/// For the instruction sequence of store below, F and I values
8354/// are bundled together as an i64 value before being stored into memory.
8355/// Sometimes it is more efficient to generate separate stores for F and I,
8356/// which can remove the bitwise instructions or sink them to colder places.
8357///
8358/// (store (or (zext (bitcast F to i32) to i64),
8359/// (shl (zext I to i64), 32)), addr) -->
8360/// (store F, addr) and (store I, addr+4)
8361///
8362/// Similarly, splitting for other merged store can also be beneficial, like:
8363/// For pair of {i32, i32}, i64 store --> two i32 stores.
8364/// For pair of {i32, i16}, i64 store --> two i32 stores.
8365/// For pair of {i16, i16}, i32 store --> two i16 stores.
8366/// For pair of {i16, i8}, i32 store --> two i16 stores.
8367/// For pair of {i8, i8}, i16 store --> two i8 stores.
8368///
8369/// We allow each target to determine specifically which kind of splitting is
8370/// supported.
8371///
8372/// The store patterns are commonly seen from the simple code snippet below
8373/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8374/// void goo(const std::pair<int, float> &);
8375/// hoo() {
8376/// ...
8377/// goo(std::make_pair(tmp, ftmp));
8378/// ...
8379/// }
8380///
8381/// Although we already have similar splitting in DAG Combine, we duplicate
8382/// it in CodeGenPrepare to catch the case in which pattern is across
8383/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8384/// during code expansion.
8386 const TargetLowering &TLI,
8387 bool ForceSplitStore) {
8388 // Handle simple but common cases only.
8389 Type *StoreType = SI.getValueOperand()->getType();
8390
8391 // The code below assumes shifting a value by <number of bits>,
8392 // whereas scalable vectors would have to be shifted by
8393 // <2log(vscale) + number of bits> in order to store the
8394 // low/high parts. Bailing out for now.
8395 if (StoreType->isScalableTy())
8396 return false;
8397
8398 if (!DL.typeSizeEqualsStoreSize(StoreType) ||
8399 DL.getTypeSizeInBits(StoreType) == 0)
8400 return false;
8401
8402 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
8403 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
8404 if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
8405 return false;
8406
8407 // Don't split the store if it is volatile or atomic.
8408 if (!SI.isSimple())
8409 return false;
8410
8411 // Match the following patterns:
8412 // (store (or (zext LValue to i64),
8413 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8414 // or
8415 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8416 // (zext LValue to i64),
8417 // Expect both operands of OR and the first operand of SHL have only
8418 // one use.
8419 Value *LValue, *HValue;
8420 if (!match(SI.getValueOperand(),
8423 m_SpecificInt(HalfValBitSize))))))
8424 return false;
8425
8426 // Check LValue and HValue are int with size less or equal than 32.
8427 if (!LValue->getType()->isIntegerTy() ||
8428 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
8429 !HValue->getType()->isIntegerTy() ||
8430 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
8431 return false;
8432
8433 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8434 // as the input of target query.
8435 auto *LBC = dyn_cast<BitCastInst>(LValue);
8436 auto *HBC = dyn_cast<BitCastInst>(HValue);
8437 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
8438 : EVT::getEVT(LValue->getType());
8439 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
8440 : EVT::getEVT(HValue->getType());
8441 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
8442 return false;
8443
8444 // Start to split store.
8445 IRBuilder<> Builder(&SI);
8446 Builder.disableGEPCanonicalization();
8447
8448 // If LValue/HValue is a bitcast in another BB, create a new one in current
8449 // BB so it may be merged with the splitted stores by dag combiner.
8450 if (LBC && LBC->getParent() != SI.getParent())
8451 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
8452 if (HBC && HBC->getParent() != SI.getParent())
8453 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
8454
8455 bool IsLE = SI.getDataLayout().isLittleEndian();
8456 auto CreateSplitStore = [&](Value *V, bool Upper) {
8457 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
8458 Value *Addr = SI.getPointerOperand();
8459 Align Alignment = SI.getAlign();
8460 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8461 if (IsOffsetStore) {
8462 Addr = Builder.CreateGEP(
8463 SplitStoreType, Addr,
8464 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
8465
8466 // When splitting the store in half, naturally one half will retain the
8467 // alignment of the original wider store, regardless of whether it was
8468 // over-aligned or not, while the other will require adjustment.
8469 Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
8470 }
8471 Builder.CreateAlignedStore(V, Addr, Alignment);
8472 };
8473
8474 CreateSplitStore(LValue, false);
8475 CreateSplitStore(HValue, true);
8476
8477 // Delete the old store.
8478 SI.eraseFromParent();
8479 return true;
8480}
8481
8482// Try unmerging GEPs to reduce liveness interference (register pressure) across
8483// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8484// reducing liveness interference across those edges benefits global register
8485// allocation. Currently handles only certain cases.
8486//
8487// For example, unmerge %GEPI and %UGEPI as below.
8488//
8489// ---------- BEFORE ----------
8490// SrcBlock:
8491// ...
8492// %GEPIOp = ...
8493// ...
8494// %GEPI = gep %GEPIOp, Idx
8495// ...
8496// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8497// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8498// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8499// %UGEPI)
8500//
8501// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8502// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8503// ...
8504//
8505// DstBi:
8506// ...
8507// %UGEPI = gep %GEPIOp, UIdx
8508// ...
8509// ---------------------------
8510//
8511// ---------- AFTER ----------
8512// SrcBlock:
8513// ... (same as above)
8514// (* %GEPI is still alive on the indirectbr edges)
8515// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8516// unmerging)
8517// ...
8518//
8519// DstBi:
8520// ...
8521// %UGEPI = gep %GEPI, (UIdx-Idx)
8522// ...
8523// ---------------------------
8524//
8525// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8526// no longer alive on them.
8527//
8528// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8529// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8530// not to disable further simplications and optimizations as a result of GEP
8531// merging.
8532//
8533// Note this unmerging may increase the length of the data flow critical path
8534// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8535// between the register pressure and the length of data-flow critical
8536// path. Restricting this to the uncommon IndirectBr case would minimize the
8537// impact of potentially longer critical path, if any, and the impact on compile
8538// time.
8540 const TargetTransformInfo *TTI) {
8541 const DataLayout &DL = GEPI->getDataLayout();
8542 BasicBlock *SrcBlock = GEPI->getParent();
8543 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8544 // (non-IndirectBr) cases exit early here.
8545 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
8546 return false;
8547 // Check that GEPI is a constant ptradd with canonical index type.
8548 Instruction *GEPIOp;
8549 ConstantInt *GEPIIdx;
8550 if (!match(GEPI, m_PtrAdd(DL, m_Instruction(GEPIOp), m_ConstantInt(GEPIIdx))))
8551 return false;
8552 // Check that GEPI is a cheap one.
8553 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
8556 return false;
8557 // Check that GEPIOp is also defined in SrcBlock.
8558 if (GEPIOp->getParent() != SrcBlock)
8559 return false;
8560 // Check that GEP is used outside the block, meaning it's alive on the
8561 // IndirectBr edge(s).
8562 if (llvm::none_of(GEPI->users(), [&](User *Usr) {
8563 if (auto *I = dyn_cast<Instruction>(Usr)) {
8564 if (I->getParent() != SrcBlock) {
8565 return true;
8566 }
8567 }
8568 return false;
8569 }))
8570 return false;
8571 // The second elements of the GEP chains to be unmerged.
8572 std::vector<GetElementPtrInst *> UGEPIs;
8573 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8574 // on IndirectBr edges.
8575 for (Instruction *Usr : GEPIOp->users()) {
8576 if (Usr == GEPI)
8577 continue;
8578 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8579 if (Usr->getParent() == SrcBlock)
8580 continue;
8581 // Check if Usr is also a constant ptradd with GEPIOp as pointer operand.
8582 // If so, record it in the vector. If not, give up.
8583 ConstantInt *UGEPIIdx;
8584 if (!match(Usr, m_PtrAdd(DL, m_Specific(GEPIOp), m_ConstantInt(UGEPIIdx))))
8585 return false;
8586 if (GEPIIdx->getType() != UGEPIIdx->getType())
8587 return false;
8588 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
8591 return false;
8592 UGEPIs.push_back(cast<GetElementPtrInst>(Usr));
8593 }
8594 if (UGEPIs.size() == 0)
8595 return false;
8596 // Check the materializing cost of (Uidx-Idx).
8597 for (GetElementPtrInst *UGEPI : UGEPIs) {
8598 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8599 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8601 NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
8602 if (ImmCost > TargetTransformInfo::TCC_Basic)
8603 return false;
8604 }
8605 // Now unmerge between GEPI and UGEPIs.
8606 for (GetElementPtrInst *UGEPI : UGEPIs) {
8607 UGEPI->setOperand(0, GEPI);
8608 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
8609 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8610 Constant *NewUGEPIIdx = ConstantInt::get(GEPIIdx->getType(), NewIdx);
8611 UGEPI->setOperand(1, NewUGEPIIdx);
8612
8613 auto SourceFlags = GEPI->getNoWrapFlags();
8614 // Intersect flags to avoid UB in updated GEP.
8615 auto TargetFlags =
8616 UGEPI->getNoWrapFlags().intersectForOffsetAdd(SourceFlags);
8617 // If UGEPI now has a negative index, drop the nuw flag.
8618 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8619 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8620 UGEPI->setNoWrapFlags(TargetFlags);
8621 }
8622 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8623 // alive on IndirectBr edges).
8624 assert(llvm::none_of(GEPIOp->users(),
8625 [&](User *Usr) {
8626 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8627 }) &&
8628 "GEPIOp is used outside SrcBlock");
8629 return true;
8630}
8631
8632static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8634 bool IsHugeFunc) {
8635 // Try and convert
8636 // %c = icmp ult %x, 8
8637 // br %c, bla, blb
8638 // %tc = lshr %x, 3
8639 // to
8640 // %tc = lshr %x, 3
8641 // %c = icmp eq %tc, 0
8642 // br %c, bla, blb
8643 // Creating the cmp to zero can be better for the backend, especially if the
8644 // lshr produces flags that can be used automatically.
8645 if (!TLI.preferZeroCompareBranch())
8646 return false;
8647
8648 ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
8649 if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
8650 return false;
8651
8652 Value *X = Cmp->getOperand(0);
8653 if (!X->hasUseList())
8654 return false;
8655
8656 APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
8657
8658 for (auto *U : X->users()) {
8660 // A quick dominance check
8661 if (!UI ||
8662 (UI->getParent() != Branch->getParent() &&
8663 UI->getParent() != Branch->getSuccessor(0) &&
8664 UI->getParent() != Branch->getSuccessor(1)) ||
8665 (UI->getParent() != Branch->getParent() &&
8666 !UI->getParent()->getSinglePredecessor()))
8667 continue;
8668
8669 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8670 match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
8671 IRBuilder<> Builder(Branch);
8672 if (UI->getParent() != Branch->getParent())
8673 UI->moveBefore(Branch->getIterator());
8675 Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
8676 ConstantInt::get(UI->getType(), 0));
8677 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8678 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8679 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8680 return true;
8681 }
8682 if (Cmp->isEquality() &&
8683 (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
8684 match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))) ||
8685 match(UI, m_Xor(m_Specific(X), m_SpecificInt(CmpC))))) {
8686 IRBuilder<> Builder(Branch);
8687 if (UI->getParent() != Branch->getParent())
8688 UI->moveBefore(Branch->getIterator());
8690 Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
8691 ConstantInt::get(UI->getType(), 0));
8692 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8693 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8694 replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
8695 return true;
8696 }
8697 }
8698 return false;
8699}
8700
8701// Performs very basic loop strength reduction to vector values with a known
8702// evolution from one iteration to the next that are used as the value operand
8703// for a store.
8704// A simple example to illustrate:
8705//
8706// %vec.ind = phi <vscale x 2 x i64> [ %start, %vector.ph ],
8707// [ %vec.ind.next, %vector.body ]
8708// %data.gep = getelementptr inbounds nuw [72 x i8], ptr %datap,
8709// <vscale x 2 x i64> %vec.ind
8710// %addr.gep = getelementptr inbounds nuw [8 x i8], ptr %addrp, i64 %index
8711// store <vscale x 2 x ptr> %data.gep, ptr %addr.gep, align 8
8712// %vec.ind.next = add nuw nsw <vscale x 2 x i64> %vec.ind, %elt.cnt.splat
8713//
8714// We want to change this to:
8715// vector.ph:
8716// %base = gep i8, %datap, (<stepvector> * 72)
8717// %stride = splat(elementcount) * 72
8718//
8719// vector.body:
8720// %vec.lsr.phi = phi <vscale x 2 x ptr> [ %base, %vector.ph ],
8721// [ %vec.lsr.next, %vector.body ]
8722// %addr.gep = gep inbounds nuw [8 x i8], ptr %addrp, i64 %index
8723// store <vscale x 2 x ptr> %vec.lsr.phi, ptr %addr.gep, align 8
8724// %vec.lsr.next = gep i8, %vec.lsr.phi, %stride
8725//
8726// Doing so will remove a multiply from the loop, and leave the update as just
8727// an add.
8728//
8730 // We're only interested in header phis in innermost loops.
8731 // We want a loop with an identifiable preheader and single latch.
8732 Loop *L = LI->getLoopFor(Phi->getParent());
8733 if (!L || !L->isInnermost())
8734 return false;
8735
8736 BasicBlock *Header = L->getHeader();
8737 BasicBlock *PreHeader = L->getLoopPreheader();
8738 BasicBlock *Latch = L->getLoopLatch();
8739 if (!PreHeader || !Latch || Phi->getParent() != Header ||
8740 Phi->getNumIncomingValues() != 2)
8741 return false;
8742
8743 // Check the progression of the phi.
8744 Value *Start = Phi->getIncomingValueForBlock(PreHeader);
8745 Value *Step = Phi->getIncomingValueForBlock(Latch);
8746
8747 // Check that the elements are integers equal in size to pointers.
8748 DataLayout DL = Phi->getFunction()->getDataLayout();
8749 VectorType *VTy = dyn_cast<VectorType>(Start->getType());
8750 if (!VTy)
8751 return false;
8752 Type *ITy = VTy->getElementType();
8753 if (DL.getTypeStoreSize(ITy) != DL.getPointerSize())
8754 return false;
8755
8758 m_Splat(m_Value())))))
8759 return false;
8760
8761 Value *LoopStride = nullptr;
8762 if (!match(Step, m_OneUse(m_c_Add(m_Specific(Phi), m_Value(LoopStride)))))
8763 return false;
8764
8765 // Make sure the loop stride matches the pointer stride.
8766 auto EltCnt = cast<VectorType>(Phi->getType())->getElementCount();
8767 const APInt *ShiftAmt = nullptr;
8768 Value *PtrStride = nullptr;
8769 if (!match(
8770 LoopStride,
8771 m_Splat(m_Value(PtrStride, m_Shl(m_VScale(), m_APInt(ShiftAmt))))) ||
8772 (1ULL << ShiftAmt->getZExtValue()) != EltCnt.getKnownMinValue())
8773 return false;
8774
8775 // Make sure the stride isn't defined inside the loop, so we don't have to
8776 // worry about dominance.
8777 if (L->contains(cast<Instruction>(PtrStride)))
8778 return false;
8779
8780 // For the simplest case, we're only interested if the phi has two users;
8781 // The Step forming the incoming value for the backedge, and a GEP.
8782 GetElementPtrInst *GEP = nullptr;
8783 Value *Base = nullptr;
8784 for (User *U : Phi->users()) {
8785 // Skip over the step, handled above.
8786 if (Step == U)
8787 continue;
8788
8789 // If we've already found a GEP, bail out.
8790 // TODO: Support multiple GEPs.
8791 if (GEP)
8792 return false;
8793
8794 // We're only interested in single index GEPs
8796 if (!GEP || GEP->getNumOperands() != 2)
8797 return false;
8798
8799 // Reject if the base isn't loop invariant.
8800 Base = GEP->getOperand(0);
8801 if (!L->isLoopInvariant(Base))
8802 return false;
8803 }
8804
8805 // Make sure we found a GEP.
8806 if (!GEP)
8807 return false;
8808
8809 // Multiply the start by the size of the struct, and add the base pointer.
8810 unsigned Size = DL.getTypeAllocSize(GEP->getSourceElementType());
8811 IRBuilder<> Builder(PreHeader->getTerminator());
8812 Value *StructSize = ConstantInt::get(ITy, Size);
8813 Value *SizeSplat =
8814 Builder.CreateVectorSplat(VTy->getElementCount(), StructSize);
8815 Value *NewStart = Builder.CreateMul(Start, SizeSplat);
8816 NewStart = Builder.CreatePtrAdd(Base, NewStart);
8817
8818 // Create a new step based on the total size of all struct addresses per
8819 // iteration.
8820 Value *StructStride = Builder.CreateMul(PtrStride, StructSize);
8821 StructStride =
8822 Builder.CreateVectorSplat(VTy->getElementCount(), StructStride);
8823
8824 Builder.SetInsertPoint(Phi);
8825 PHINode *NewPhi = Builder.CreatePHI(GEP->getType(), 2, "vec.lsr.phi");
8826 Builder.SetInsertPoint(cast<Instruction>(Step));
8827 StructStride = Builder.CreatePtrAdd(NewPhi, StructStride);
8828
8829 // Set up the new PHI.
8830 NewPhi->addIncoming(NewStart, PreHeader);
8831 NewPhi->addIncoming(StructStride, Latch);
8832
8833 // Replace the GEP with the new phi.
8834 Builder.SetInsertPoint(GEP);
8835 GEP->replaceAllUsesWith(NewPhi);
8836
8837 // Remove old phi, gep, and step.
8838 Phi->replaceAllUsesWith(llvm::PoisonValue::get(Phi->getType()));
8840
8841 return true;
8842}
8843
8844bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8845 bool AnyChange = false;
8846 AnyChange = fixupDbgVariableRecordsOnInst(*I);
8847
8848 // Bail out if we inserted the instruction to prevent optimizations from
8849 // stepping on each other's toes.
8850 if (InsertedInsts.count(I))
8851 return AnyChange;
8852
8853 // TODO: Move into the switch on opcode below here.
8854 if (PHINode *P = dyn_cast<PHINode>(I)) {
8855 // It is possible for very late stage optimizations (such as SimplifyCFG)
8856 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8857 // trivial PHI, go ahead and zap it here.
8858 if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
8859 LargeOffsetGEPMap.erase(P);
8860 replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
8861 P->eraseFromParent();
8862 ++NumPHIsElim;
8863 return true;
8864 }
8865
8866 // Look for simple GEPs on scalable vectors used as data which may
8867 // introduce unnecessary multiplies in the loop.
8868 // TODO: Support fixed vectors too.
8869 if (P->getType()->isScalableTy())
8870 AnyChange |= strengthReduceVectorPhiUsers(P, LI);
8871 return AnyChange;
8872 }
8873
8874 if (CastInst *CI = dyn_cast<CastInst>(I)) {
8875 // If the source of the cast is a constant, then this should have
8876 // already been constant folded. The only reason NOT to constant fold
8877 // it is if something (e.g. LSR) was careful to place the constant
8878 // evaluation in a block other than then one that uses it (e.g. to hoist
8879 // the address of globals out of a loop). If this is the case, we don't
8880 // want to forward-subst the cast.
8881 if (auto *BCI = dyn_cast<BitCastInst>(CI)) {
8882 // Hoist bitcasts of illegal types to reduce cross-block register pressure
8883 // and prevent register splitting.
8884 if (optimizeBitCast(BCI, *TLI, *DL)) {
8885 return true;
8886 }
8887 }
8888
8889 if (isa<Constant>(CI->getOperand(0)))
8890 return AnyChange;
8891
8892 if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
8893 return true;
8894
8896 isa<TruncInst>(I)) &&
8898 I, LI->getLoopFor(I->getParent()), *TTI))
8899 return true;
8900
8901 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8902 /// Sink a zext or sext into its user blocks if the target type doesn't
8903 /// fit in one register
8904 if (TLI->getTypeAction(CI->getContext(),
8905 TLI->getValueType(*DL, CI->getType())) ==
8906 TargetLowering::TypeExpandInteger) {
8907 return SinkCast(CI);
8908 } else {
8910 I, LI->getLoopFor(I->getParent()), *TTI))
8911 return true;
8912
8913 bool MadeChange = optimizeExt(I);
8914 return MadeChange | optimizeExtUses(I);
8915 }
8916 }
8917 return AnyChange;
8918 }
8919
8920 if (auto *Cmp = dyn_cast<CmpInst>(I))
8921 if (optimizeCmp(Cmp, ModifiedDT))
8922 return true;
8923
8924 if (match(I, m_URem(m_Value(), m_Value())))
8925 if (optimizeURem(I))
8926 return true;
8927
8928 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8929 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8930 bool Modified = optimizeLoadExt(LI);
8931 unsigned AS = LI->getPointerAddressSpace();
8932 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
8933 return Modified;
8934 }
8935
8936 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
8937 if (splitMergedValStore(*SI, *DL, *TLI, Opts.cgp_force_split_store))
8938 return true;
8939 bool Modified = tryToSinkFreeOperands(I);
8940 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
8941 unsigned AS = SI->getPointerAddressSpace();
8942 Modified |= optimizeMemoryInst(I, SI->getOperand(1),
8943 SI->getOperand(0)->getType(), AS);
8944 return Modified;
8945 }
8946
8947 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
8948 unsigned AS = RMW->getPointerAddressSpace();
8949 return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
8950 }
8951
8952 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
8953 unsigned AS = CmpX->getPointerAddressSpace();
8954 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
8955 CmpX->getCompareOperand()->getType(), AS);
8956 }
8957
8958 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
8959
8960 if (BinOp && BinOp->getOpcode() == Instruction::And &&
8961 Opts.cgp_andcmp_sinking &&
8962 sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
8963 return true;
8964
8965 // TODO: Move this into the switch on opcode - it handles shifts already.
8966 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
8967 BinOp->getOpcode() == Instruction::LShr)) {
8968 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
8969 if (CI && TLI->hasExtractBitsInsn())
8970 if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
8971 return true;
8972 }
8973
8974 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
8975 if (GEPI->hasAllZeroIndices()) {
8976 /// The GEP operand must be a pointer, so must its result -> BitCast
8977 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
8978 GEPI->getName(), GEPI->getIterator());
8979 NC->setDebugLoc(GEPI->getDebugLoc());
8980 replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
8982 GEPI, TLInfo, nullptr,
8983 [&](Value *V) { removeAllAssertingVHReferences(V); });
8984 ++NumGEPsElim;
8985 optimizeInst(NC, ModifiedDT);
8986 return true;
8987 }
8989 return true;
8990 }
8991 }
8992
8993 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
8994 // freeze(icmp a, const)) -> icmp (freeze a), const
8995 // This helps generate efficient conditional jumps.
8996 CmpInst *CmpI = dyn_cast<CmpInst>(FI->getOperand(0));
8997 if (CmpI && CmpI->hasOneUse()) {
8998 auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
8999 bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
9001 bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
9003 if (Const0 || Const1) {
9004 if (!Const0 || !Const1) {
9005 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9006 F->takeName(FI);
9007 CmpI->setOperand(Const0 ? 1 : 0, F);
9008 }
9010 replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
9011 FI->eraseFromParent();
9012 return true;
9013 }
9014 }
9015 return AnyChange;
9016 }
9017
9018 // Try to fold some cross-lane vector operations if in a loop.
9019 if (I->getType()->isVectorTy() &&
9020 TLI->optimizeVectorCrossLaneOperation(I, LI->getLoopFor(I->getParent())))
9021 return true;
9022
9023 if (tryToSinkFreeOperands(I))
9024 return true;
9025
9026 switch (I->getOpcode()) {
9027 case Instruction::Shl:
9028 case Instruction::LShr:
9029 case Instruction::AShr:
9030 return optimizeShiftInst(cast<BinaryOperator>(I));
9031 case Instruction::Call:
9032 return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
9033 case Instruction::Select:
9034 return optimizeSelectInst(cast<SelectInst>(I));
9035 case Instruction::ShuffleVector:
9036 return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
9037 case Instruction::Switch:
9038 return optimizeSwitchInst(cast<SwitchInst>(I));
9039 case Instruction::ExtractElement:
9040 return optimizeExtractElementInst(cast<ExtractElementInst>(I));
9041 case Instruction::CondBr:
9042 return optimizeBranch(cast<CondBrInst>(I), *TLI, FreshBBs, IsHugeFunc);
9043 }
9044
9045 return AnyChange;
9046}
9047
9048/// Given an OR instruction, check to see if this is a bitreverse
9049/// idiom. If so, insert the new intrinsic and return true.
9050bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9051 if (!I.getType()->isIntegerTy() ||
9053 TLI->getValueType(*DL, I.getType(), true)))
9054 return false;
9055
9056 SmallVector<Instruction *, 4> Insts;
9057 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
9058 return false;
9059 Instruction *LastInst = Insts.back();
9060 replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
9062 &I, TLInfo, nullptr,
9063 [&](Value *V) { removeAllAssertingVHReferences(V); });
9064 return true;
9065}
9066
9067// In this pass we look for GEP and cast instructions that are used
9068// across basic blocks and rewrite them to improve basic-block-at-a-time
9069// selection.
9070bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9071 SunkAddrs.clear();
9072 bool MadeChange = false;
9073
9074 do {
9075 CurInstIterator = BB.begin();
9076 ModifiedDT = ModifyDT::NotModifyDT;
9077 while (CurInstIterator != BB.end()) {
9078 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
9079 if (ModifiedDT != ModifyDT::NotModifyDT) {
9080 // For huge function we tend to quickly go though the inner optmization
9081 // opportunities in the BB. So we go back to the BB head to re-optimize
9082 // each instruction instead of go back to the function head.
9083 if (IsHugeFunc)
9084 break;
9085 return true;
9086 }
9087 }
9088 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9089
9090 bool MadeBitReverse = true;
9091 while (MadeBitReverse) {
9092 MadeBitReverse = false;
9093 for (auto &I : reverse(BB)) {
9094 if (makeBitReverse(I)) {
9095 MadeBitReverse = MadeChange = true;
9096 break;
9097 }
9098 }
9099 }
9100 MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
9101
9102 return MadeChange;
9103}
9104
9105bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9106 bool AnyChange = false;
9107 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
9108 AnyChange |= fixupDbgVariableRecord(DVR);
9109 return AnyChange;
9110}
9111
9112// FIXME: should updating debug-info really cause the "changed" flag to fire,
9113// which can cause a function to be reprocessed?
9114bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9115 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9116 DVR.Type != DbgVariableRecord::LocationType::Assign)
9117 return false;
9118
9119 // Does this DbgVariableRecord refer to a sunk address calculation?
9120 bool AnyChange = false;
9121 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9122 DVR.location_ops().end());
9123 for (Value *Location : LocationOps) {
9124 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9125 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9126 if (SunkAddr) {
9127 // Point dbg.value at locally computed address, which should give the best
9128 // opportunity to be accurately lowered. This update may change the type
9129 // of pointer being referred to; however this makes no difference to
9130 // debugging information, and we can't generate bitcasts that may affect
9131 // codegen.
9132 DVR.replaceVariableLocationOp(Location, SunkAddr);
9133 AnyChange = true;
9134 }
9135 }
9136 return AnyChange;
9137}
9138
9140 DVR->removeFromParent();
9141 BasicBlock *VIBB = VI->getParent();
9142 if (isa<PHINode>(VI))
9143 VIBB->insertDbgRecordBefore(DVR, VIBB->getFirstInsertionPt());
9144 else
9145 VIBB->insertDbgRecordAfter(DVR, &*VI);
9146}
9147
9148// A llvm.dbg.value may be using a value before its definition, due to
9149// optimizations in this pass and others. Scan for such dbg.values, and rescue
9150// them by moving the dbg.value to immediately after the value definition.
9151// FIXME: Ideally this should never be necessary, and this has the potential
9152// to re-order dbg.value intrinsics.
9153bool CodeGenPrepare::placeDbgValues(Function &F) {
9154 bool MadeChange = false;
9155 DominatorTree &DT = getDT();
9156
9157 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9158 SmallVector<Instruction *, 4> VIs;
9159 for (Value *V : DbgItem->location_ops())
9160 if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
9161 VIs.push_back(VI);
9162
9163 // This item may depend on multiple instructions, complicating any
9164 // potential sink. This block takes the defensive approach, opting to
9165 // "undef" the item if it has more than one instruction and any of them do
9166 // not dominate iem.
9167 for (Instruction *VI : VIs) {
9168 if (VI->isTerminator())
9169 continue;
9170
9171 // If VI is a phi in a block with an EHPad terminator, we can't insert
9172 // after it.
9173 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
9174 continue;
9175
9176 // If the defining instruction dominates the dbg.value, we do not need
9177 // to move the dbg.value.
9178 if (DT.dominates(VI, Position))
9179 continue;
9180
9181 // If we depend on multiple instructions and any of them doesn't
9182 // dominate this DVI, we probably can't salvage it: moving it to
9183 // after any of the instructions could cause us to lose the others.
9184 if (VIs.size() > 1) {
9185 LLVM_DEBUG(
9186 dbgs()
9187 << "Unable to find valid location for Debug Value, undefing:\n"
9188 << *DbgItem);
9189 DbgItem->setKillLocation();
9190 break;
9191 }
9192
9193 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9194 << *DbgItem << ' ' << *VI);
9195 DbgInserterHelper(DbgItem, VI->getIterator());
9196 MadeChange = true;
9197 ++NumDbgValueMoved;
9198 }
9199 };
9200
9201 for (BasicBlock &BB : F) {
9202 for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
9203 // Process any DbgVariableRecord records attached to this
9204 // instruction.
9205 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9206 filterDbgVars(Insn.getDbgRecordRange()))) {
9207 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9208 continue;
9209 DbgProcessor(&DVR, &Insn);
9210 }
9211 }
9212 }
9213
9214 return MadeChange;
9215}
9216
9217// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9218// probes can be chained dependencies of other regular DAG nodes and block DAG
9219// combine optimizations.
9220bool CodeGenPrepare::placePseudoProbes(Function &F) {
9221 bool MadeChange = false;
9222 for (auto &Block : F) {
9223 // Move the rest probes to the beginning of the block.
9224 auto FirstInst = Block.getFirstInsertionPt();
9225 while (FirstInst != Block.end() && isa<PseudoProbeInst>(FirstInst))
9226 ++FirstInst;
9227 BasicBlock::iterator I(FirstInst);
9228 I++;
9229 while (I != Block.end()) {
9230 if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
9231 II->moveBefore(FirstInst);
9232 MadeChange = true;
9233 }
9234 }
9235 }
9236 return MadeChange;
9237}
9238
9239/// Some targets prefer to split a conditional branch like:
9240/// \code
9241/// %0 = icmp ne i32 %a, 0
9242/// %1 = icmp ne i32 %b, 0
9243/// %or.cond = or i1 %0, %1
9244/// br i1 %or.cond, label %TrueBB, label %FalseBB
9245/// \endcode
9246/// into multiple branch instructions like:
9247/// \code
9248/// bb1:
9249/// %0 = icmp ne i32 %a, 0
9250/// br i1 %0, label %TrueBB, label %bb2
9251/// bb2:
9252/// %1 = icmp ne i32 %b, 0
9253/// br i1 %1, label %TrueBB, label %FalseBB
9254/// \endcode
9255/// This usually allows instruction selection to do even further optimizations
9256/// and combine the compare with the branch instruction. Currently this is
9257/// applied for targets which have "cheap" jump instructions.
9258///
9259/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9260///
9261bool CodeGenPrepare::splitBranchCondition(Function &F) {
9263 return false;
9264
9265 bool MadeChange = false;
9266 for (auto &BB : F) {
9267 // Does this BB end with the following?
9268 // %cond1 = icmp|fcmp|binary instruction ...
9269 // %cond2 = icmp|fcmp|binary instruction ...
9270 // %cond.or = or|and i1 %cond1, cond2
9271 // br i1 %cond.or label %dest1, label %dest2"
9272 Instruction *LogicOp;
9273 BasicBlock *TBB, *FBB;
9274 if (!match(BB.getTerminator(),
9275 m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
9276 continue;
9277
9278 auto *Br1 = cast<CondBrInst>(BB.getTerminator());
9279 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
9280 continue;
9281
9282 // The merging of mostly empty BB can cause a degenerate branch.
9283 if (TBB == FBB)
9284 continue;
9285
9286 unsigned Opc;
9287 Value *Cond1, *Cond2;
9288 if (match(LogicOp,
9289 m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
9290 Opc = Instruction::And;
9291 else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
9292 m_OneUse(m_Value(Cond2)))))
9293 Opc = Instruction::Or;
9294 else
9295 continue;
9296
9297 auto IsGoodCond = [](Value *Cond) {
9298 return match(
9299 Cond,
9301 m_LogicalOr(m_Value(), m_Value()))));
9302 };
9303 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9304 continue;
9305
9306 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9307
9308 // Create a new BB.
9309 auto *TmpBB =
9310 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
9311 BB.getParent(), BB.getNextNode());
9312 if (IsHugeFunc)
9313 FreshBBs.insert(TmpBB);
9314
9315 // Update original basic block by using the first condition directly by the
9316 // branch instruction and removing the no longer needed and/or instruction.
9317 Br1->setCondition(Cond1);
9318 LogicOp->eraseFromParent();
9319
9320 // Depending on the condition we have to either replace the true or the
9321 // false successor of the original branch instruction.
9322 if (Opc == Instruction::And)
9323 Br1->setSuccessor(0, TmpBB);
9324 else
9325 Br1->setSuccessor(1, TmpBB);
9326
9327 // Fill in the new basic block.
9328 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
9329 if (auto *I = dyn_cast<Instruction>(Cond2)) {
9330 I->removeFromParent();
9331 I->insertBefore(Br2->getIterator());
9332 }
9333
9334 // Update PHI nodes in both successors. The original BB needs to be
9335 // replaced in one successor's PHI nodes, because the branch comes now from
9336 // the newly generated BB (NewBB). In the other successor we need to add one
9337 // incoming edge to the PHI nodes, because both branch instructions target
9338 // now the same successor. Depending on the original branch condition
9339 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9340 // we perform the correct update for the PHI nodes.
9341 // This doesn't change the successor order of the just created branch
9342 // instruction (or any other instruction).
9343 if (Opc == Instruction::Or)
9344 std::swap(TBB, FBB);
9345
9346 // Replace the old BB with the new BB.
9347 TBB->replacePhiUsesWith(&BB, TmpBB);
9348
9349 // Add another incoming edge from the new BB.
9350 for (PHINode &PN : FBB->phis()) {
9351 auto *Val = PN.getIncomingValueForBlock(&BB);
9352 PN.addIncoming(Val, TmpBB);
9353 }
9354
9355 if (Loop *L = LI->getLoopFor(&BB))
9356 L->addBasicBlockToLoop(TmpBB, *LI);
9357
9358 // The edge we need to delete starts at BB and ends at whatever TBB ends
9359 // up pointing to.
9360 DTU->applyUpdates({{DominatorTree::Insert, &BB, TmpBB},
9361 {DominatorTree::Insert, TmpBB, TBB},
9362 {DominatorTree::Insert, TmpBB, FBB},
9363 {DominatorTree::Delete, &BB, TBB}});
9364
9365 // Update the branch weights (from SelectionDAGBuilder::
9366 // FindMergedConditions).
9367 if (Opc == Instruction::Or) {
9368 // Codegen X | Y as:
9369 // BB1:
9370 // jmp_if_X TBB
9371 // jmp TmpBB
9372 // TmpBB:
9373 // jmp_if_Y TBB
9374 // jmp FBB
9375 //
9376
9377 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9378 // The requirement is that
9379 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9380 // = TrueProb for original BB.
9381 // Assuming the original weights are A and B, one choice is to set BB1's
9382 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9383 // assumes that
9384 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9385 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9386 // TmpBB, but the math is more complicated.
9387 uint64_t TrueWeight, FalseWeight;
9388 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9389 uint64_t NewTrueWeight = TrueWeight;
9390 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9391 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9392 hasBranchWeightOrigin(*Br1));
9393
9394 NewTrueWeight = TrueWeight;
9395 NewFalseWeight = 2 * FalseWeight;
9396 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9397 /*IsExpected=*/false);
9398 }
9399 } else {
9400 // Codegen X & Y as:
9401 // BB1:
9402 // jmp_if_X TmpBB
9403 // jmp FBB
9404 // TmpBB:
9405 // jmp_if_Y TBB
9406 // jmp FBB
9407 //
9408 // This requires creation of TmpBB after CurBB.
9409
9410 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9411 // The requirement is that
9412 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9413 // = FalseProb for original BB.
9414 // Assuming the original weights are A and B, one choice is to set BB1's
9415 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9416 // assumes that
9417 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9418 uint64_t TrueWeight, FalseWeight;
9419 if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
9420 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9421 uint64_t NewFalseWeight = FalseWeight;
9422 setFittedBranchWeights(*Br1, {NewTrueWeight, NewFalseWeight},
9423 /*IsExpected=*/false);
9424
9425 NewTrueWeight = 2 * TrueWeight;
9426 NewFalseWeight = FalseWeight;
9427 setFittedBranchWeights(*Br2, {NewTrueWeight, NewFalseWeight},
9428 /*IsExpected=*/false);
9429 }
9430 }
9431
9432 MadeChange = true;
9433
9434 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9435 TmpBB->dump());
9436 }
9437 return MadeChange;
9438}
#define Success
return SDValue()
static unsigned getIntrinsicID(const SDNode *N)
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI, SetOfInstrs &InsertedInsts)
Duplicate and sink the given 'and' instruction into user blocks where it is used in a compare to allo...
static bool SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, DenseMap< BasicBlock *, BinaryOperator * > &InsertedShifts, const TargetLowering &TLI, const DataLayout &DL)
Sink both shift and truncate instruction to the use of truncate's BB.
static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, SmallVectorImpl< Value * > &OffsetV)
static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V)
Check if V (an operand of a select instruction) is an expensive instruction that is only used once.
static bool isExtractBitsCandidateUse(Instruction *User)
Check if the candidates could be combined with a shift instruction, which includes:
static bool optimizeBitCast(BitCastInst *BCI, const TargetLowering &TLI, const DataLayout &DL)
Hoists bitcasts to the source block to reduce register pressure.
static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, const TargetLowering &TLI, const DataLayout &DL)
Sink the shift right instruction into user blocks if the uses could potentially be combined with this...
static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, const DataLayout &DL)
If the specified cast instruction is a noop copy (e.g.
static bool SinkCast(CastInst *CI)
Sink the specified cast instruction into its user blocks.
static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, const TargetLowering &TLI, bool ForceSplitStore)
For the instruction sequence of store below, F and I values are bundled together as an i64 value befo...
static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp)
Many architectures use the same instruction for both subtract and cmp.
static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, const TargetLowering *TLI, SelectInst *SI)
Returns true if a SelectInst should be turned into an explicit branch.
static bool FindAllMemoryUses(Instruction *I, SmallVectorImpl< std::pair< Use *, Type * > > &MemoryUses, SmallPtrSetImpl< Instruction * > &ConsideredInsts, const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI, unsigned &SeenInsts, unsigned MaxUsersToScan)
Recursively walk all the uses of I until we find a memory use.
static std::optional< std::pair< Instruction *, Constant * > > getIVIncrement(const PHINode *PN, const LoopInfo *LI)
If given PN is an inductive variable with value IVInc coming from the backedge, and on each iteration...
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool foldICmpWithDominatingICmp(CmpInst *Cmp, const TargetLowering &TLI, bool EnableICmpEqToICmpSt)
For pattern like:
static bool strengthReduceVectorPhiUsers(PHINode *Phi, LoopInfo *LI)
static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, const TargetTransformInfo *TTI)
static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, const TargetLowering &TLI, const TargetRegisterInfo &TRI)
Check to see if all uses of OpVal by the specified inline asm call are due to memory operands.
static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo, const CallInst *CI)
static void replaceAllUsesWith(Value *Old, Value *New, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
Replace all old uses with new ones, and push the updated BBs into FreshBBs.
static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract, ExtractValueInst *&OverflowExtract)
static void computeBaseDerivedRelocateMap(const SmallVectorImpl< GCRelocateInst * > &AllRelocateCalls, MapVector< GCRelocateInst *, SmallVector< GCRelocateInst *, 0 > > &RelocateInstMap)
static bool simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, const SmallVectorImpl< GCRelocateInst * > &Targets)
static bool MightBeFoldableInst(Instruction *I)
This is a little filter, which returns true if an addressing computation involving I might be folded ...
static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS, Constant *&Step)
static bool isIVIncrement(const Value *V, const LoopInfo *LI)
static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI)
static bool isPromotedInstructionLegal(const TargetLowering &TLI, const DataLayout &DL, Value *Val)
Check whether or not Val is a legal instruction for TLI.
static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst, Value *SunkAddr)
static bool isRemOfLoopIncrementWithLoopInvariant(Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut, Value *&AddOffsetOut, PHINode *&LoopIncrPNOut, Constant *&StepOut)
static bool IsNonLocalValue(Value *V, BasicBlock *BB)
Return true if the specified values are defined in a different basic block than BB.
static bool despeculateCountZeros(IntrinsicInst *CountZeros, DomTreeUpdater *DTU, LoopInfo *LI, const TargetLowering *TLI, const DataLayout *DL, ModifyDT &ModifiedDT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHugeFunc)
If counting leading or trailing zeros is an expensive operation and a zero input is defined,...
static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI, const DataLayout &DL)
Sink the given CmpInst into user blocks to reduce the number of virtual registers that must be create...
static bool hasSameExtUse(Value *Val, const TargetLowering &TLI)
Check if all the uses of Val are equivalent (or free) zero or sign extensions.
static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL, const LoopInfo *LI, DominatorTree &DT, SmallPtrSet< BasicBlock *, 32 > &FreshBBs, bool IsHuge)
static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp, BinaryOperator *&Add)
Match special-case patterns that check for unsigned add overflow.
Defines an IR pass for CodeGen Prepare.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:702
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file declares the LLVM IR specialization of the GenericCycle templates.
This file defines the DenseMap class.
static bool runOnFunction(Function &F, bool PostInlining)
#define DEBUG_TYPE
static Value * getCondition(Instruction *I)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
static constexpr Value * getValue(Ty &ValueOrUse)
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
Definition LICM.cpp:1183
static LVOptions Options
Definition LVOptions.cpp:25
SmallVector< MachineOperand, 4 > Cond
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register const TargetRegisterInfo * TRI
This file implements a map that provides insertion order iteration.
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
ppc ctr loops verify
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
This file defines the PointerIntPair class.
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > MachineBasicBlock * TBB
static DominatorTree getDomTree(Function &F)
static bool dominates(InstrPosIndexes &PosIndexes, const MachineInstr &A, const MachineInstr &B)
Remove Loads Into Fake Uses
This file contains some templates that are useful if you are working with the STL at all.
static bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
static bool optimizeCallInst(CallInst *CI, bool &ModifiedDT, const TargetTransformInfo &TTI, const DataLayout &DL, bool HasBranchDivergence, DomTreeUpdater *DTU)
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
This pass exposes codegen information to IR-level passes.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static Constant * getConstantVector(MVT VT, ArrayRef< APInt > Bits, const APInt &Undefs, LLVMContext &C)
Value * RHS
Value * LHS
BinaryOperator * Mul
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
unsigned getSignificantBits() const
Get the minimum bit size for this signed APInt.
Definition APInt.h:1551
unsigned logBase2() const
Definition APInt.h:1781
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
int64_t getSExtValue() const
Get sign extended value.
Definition APInt.h:1582
LLVM_ABI bool isStaticAlloca() const
Return true if this alloca is in the entry block of the function and is a constant size.
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
void setAlignment(Align Align)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
AnalysisUsage & addRequired()
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
An instruction that atomically checks whether a specified value is in a memory location,...
static unsigned getPointerOperandIndex()
an instruction that atomically reads a memory location, combines it with another value,...
static unsigned getPointerOperandIndex()
Analysis pass providing the BasicBlockSectionsProfileReader.
LLVM_ABI bool isFunctionHot(StringRef FuncName) const
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator end()
Definition BasicBlock.h:452
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:508
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:665
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:170
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
LLVM_ABI void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis pass which computes BranchProbabilityInfo.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
bool isInlineAsm() const
Check if this call is an inline asm statement.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool hasFnAttr(Attribute::AttrKind Kind) const
Determine whether this call has the given attribute.
Value * getArgOperand(unsigned i) const
void setArgOperand(unsigned i, Value *v)
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Conditional Branch instruction.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNeg(Constant *C, bool HasNSW=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static ConstantInt * getSigned(IntegerType *Ty, int64_t V, bool ImplicitTrunc=false)
Return a ConstantInt with the specified value for the specified type.
Definition Constants.h:135
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
Definition Constants.h:174
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI void removeFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LocationType Type
Classification of the debug-info record that this DbgVariableRecord represents.
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
unsigned size() const
Definition DenseMap.h:717
bool erase(const KeyT &Val)
Definition DenseMap.h:930
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Legacy analysis pass which computes a DominatorTree.
Definition Dominators.h:277
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
iterator_range< idx_iterator > indices() const
This instruction compares its operands according to the predicate given to the constructor.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:312
const BasicBlock & getEntryBlock() const
Definition Function.h:803
LLVM_ABI const Value * getStatepoint() const
The statepoint with which this gc.relocate is associated.
Represents calls to the gc.relocate intrinsic.
unsigned getBasePtrIndex() const
The index into the associate statepoint's argument list which contains the base pointer of the pointe...
void compute(FunctionT &F)
Compute the cycle info for a function.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
LLVM_ABI bool canIncreaseAlignment() const
Returns true if the alignment of the value can be unilaterally increased.
Definition Globals.cpp:422
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This instruction compares its operands according to the predicate given to the constructor.
bool isEquality() const
Return true if this predicate is either EQ or NE.
Value * CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1437
Value * CreateURem(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1501
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
user_iterator_impl< Instruction > user_iterator
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI void moveAfter(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
bool hasMetadata() const
Return true if this instruction has any metadata attached to it.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool mayHaveSideEffects() const LLVM_READONLY
Return true if the instruction may have side effects.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
LLVM_ABI bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
user_iterator user_begin()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
user_iterator user_end()
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
LLVM_ABI std::optional< simple_ilist< DbgRecord >::iterator > getDbgReinsertionPosition()
Return an iterator to the position of the "Next" DbgRecord after this instruction,...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Analysis pass that exposes the LoopInfo for a function.
Definition LoopInfo.h:598
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Definition LoopInfo.h:623
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
static MVT getIntegerVT(unsigned BitWidth)
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
bool empty() const
Definition MapVector.h:80
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition MapVector.h:127
VectorType::iterator erase(typename VectorType::iterator Iterator)
Remove the element given by Iterator.
Definition MapVector.h:211
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
op_range incoming_values()
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Analysis providing profile information.
Value * getReturnValue() const
Convenience accessor. Returns null if there is no return value.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type count(const_arg_type key) const
Count the number of elements of a given key in the SetVector.
Definition SetVector.h:268
void clear()
Completely clear the SetVector.
Definition SetVector.h:273
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
value_type pop_back_val()
Definition SetVector.h:285
VectorType * getType() const
Overload to return most specific vector type.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
bool erase(const T &V)
Definition SmallSet.h:200
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
iterator erase(const_iterator CI)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
static unsigned getPointerOperandIndex()
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
int InstructionOpcodeToISD(unsigned Opcode) const
Get the ISD node that corresponds to the Instruction class opcode.
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool isSelectSupported(SelectSupportKind) const
virtual bool shouldFormOverflowOp(unsigned Opcode, EVT VT, bool MathUsed) const
Try to convert math with an overflow comparison into the corresponding DAG node operation.
virtual bool shouldOptimizeMulOverflowWithZeroHighBits(LLVMContext &Context, EVT VT) const
bool isExtLoad(const LoadInst *Load, const Instruction *Ext, const DataLayout &DL) const
Return true if Load and Ext can form an ExtLoad.
virtual bool isSExtCheaperThanZExt(EVT FromTy, EVT ToTy) const
Return true if sign-extension from FromTy to ToTy is cheaper than zero-extension.
const TargetMachine & getTargetMachine() const
virtual bool isCtpopFast(EVT VT) const
Return true if ctpop instruction is fast.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
bool enableExtLdPromotion() const
Return true if the target wants to use the optimization that turns ext(promotableInst1(....
bool isJumpExpensive() const
Return true if Flow Control is an expensive operation that should be avoided.
bool hasExtractBitsInsn() const
Return true if the target has BitExtract instructions.
virtual bool allowsMisalignedMemoryAccesses(EVT, unsigned AddrSpace=0, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *=nullptr) const
Determine if the target supports unaligned memory accesses.
bool isSlowDivBypassed() const
Returns true if target has indicated at least one type should be bypassed.
virtual bool isTruncateFree(Type *FromTy, Type *ToTy) const
Return true if it's free to truncate a value of type FromTy to type ToTy.
virtual MVT getPreferredSwitchConditionType(LLVMContext &Context, EVT ConditionVT) const
Returns preferred type for switch condition.
virtual bool canCombineStoreAndExtract(Type *VectorTy, Value *Idx, unsigned &Cost) const
Return true if the target can combine store(extractelement VectorTy,Idx).
virtual bool shouldConsiderGEPOffsetSplit() const
bool isExtFree(const Instruction *I) const
Return true if the extension represented by I is free.
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
virtual bool getAddrModeArguments(const IntrinsicInst *, SmallVectorImpl< Value * > &, Type *&) const
CodeGenPrepare sinks address calculations into the same BB as Load/Store instructions reading the add...
const DenseMap< unsigned int, unsigned int > & getBypassSlowDivWidths() const
Returns map of slow types for division or remainder with corresponding fast types.
virtual int64_t getPreferredLargeGEPBaseOffset(int64_t MinOffset, int64_t MaxOffset) const
Return the prefered common base offset.
LegalizeTypeAction getTypeAction(LLVMContext &Context, EVT VT) const
Return how we should legalize values of this type, either it is already legal (return 'Legal') or we ...
virtual bool optimizeVectorCrossLaneOperation(Instruction *I, Loop *L) const
virtual bool shouldAlignPointerArgs(CallInst *, unsigned &, Align &) const
Return true if the pointer arguments to CI should be aligned by aligning the object whose address is ...
virtual Type * shouldConvertSplatType(ShuffleVectorInst *SVI) const
Given a shuffle vector SVI representing a vector splat, return a new scalar type of size equal to SVI...
bool isLoadLegal(EVT ValVT, EVT MemVT, Align Alignment, unsigned AddrSpace, unsigned ExtType, bool Atomic) const
Return true if the specified load with extension is legal on this target.
virtual bool addressingModeSupportsTLS(const GlobalValue &) const
Returns true if the targets addressing mode can target thread local storage (TLS).
virtual bool shouldConvertPhiType(Type *From, Type *To) const
Given a set in interconnected phis of type 'From' that are loaded/stored or bitcast to type 'To',...
virtual bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AddrSpace, Instruction *I=nullptr) const
Return true if the addressing mode represented by AM is legal for this target, for a load/store of th...
virtual bool optimizeExtendOrTruncateConversion(Instruction *I, Loop *L, const TargetTransformInfo &TTI) const
Try to optimize extending or truncating conversion instructions (like zext, trunc,...
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
std::vector< AsmOperandInfo > AsmOperandInfoVector
virtual AsmOperandInfoVector ParseConstraints(const DataLayout &DL, const TargetRegisterInfo *TRI, const CallBase &Call) const
Split up the constraint string from the inline assembly value into the specific constraints and their...
virtual void ComputeConstraintToUse(AsmOperandInfo &OpInfo, SDValue Op, SelectionDAG *DAG=nullptr) const
Determines the constraint code and constraint type to use for the specific AsmOperandInfo,...
virtual bool mayBeEmittedAsTailCall(const CallInst *) const
Return true if the target may be able emit the call instruction as a tail call.
virtual bool isNoopAddrSpaceCast(const DataLayout &DL, unsigned SrcAS, unsigned DestAS) const
Returns true if a cast between SrcAS and DestAS is a noop.
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
TargetOptions Options
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Target-Independent Code Generator Pass Configuration Options.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
virtual const TargetLowering * getTargetLowering() const
Wrapper pass for TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr, ArrayRef< const Value * > Scalars={}) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI InstructionCost getIntImmCost(const APInt &Imm, Type *Ty, TargetCostKind CostKind) const
Return the expected cost of materializing for the given integer immediate of the specified type.
LLVM_ABI bool shouldConsiderAddressTypePromotion(const Instruction &I, bool &AllowPromotionWithoutCommonHeader) const
@ TCC_Basic
The cost of a typical 'add' instruction.
LLVM_ABI bool isVectorShiftByScalarCheap(Type *Ty) const
Return true if it's significantly cheaper to shift a vector by a uniform scalar than by an amount whi...
LLVM_ABI bool isProfitableToSinkOperands(Instruction *I, SmallVectorImpl< Use * > &Ops, const LoopInfo *LI=nullptr) const
Return true if sinking I's operands to the same basic block as I is profitable, e....
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI Type * getWithNewBitWidth(unsigned NewBitWidth) const
Given an integer or vector type, change the lane bitwidth to NewBitwidth, whilst keeping the old numb...
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
BasicBlock * getSuccessor(unsigned i=0) const
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
const Use & getOperandUse(unsigned i) const
Definition User.h:220
void setOperand(unsigned i, Value *Val)
Definition User.h:212
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition User.cpp:21
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
user_iterator user_begin()
Definition Value.h:404
LLVM_ABI void setName(const Twine &Name)
Change the name of the value.
Definition Value.cpp:389
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
LLVM_ABI bool isUsedInBasicBlock(const BasicBlock *BB) const
Check if this value is used in the specified basic block.
Definition Value.cpp:234
LLVM_ABI void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Definition Value.h:809
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
bool pointsToAliveValue() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isNonZero() const
Definition TypeSize.h:156
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
unsigned getAddrMode(MCInstrInfo const &MCII, MCInst const &MCI)
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
ap_match< APInt > m_APIntAllowPoison(const APInt *&Res)
Match APInt while allowing poison in splat vector constants.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Ctpop(const Opnd0 &Op0)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
auto m_VScale()
Matches a call to llvm.vscale().
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
Splat_match< T > m_Splat(const T &SubPattern)
Match a vector splat.
PtrAdd_match< PointerOpTy, OffsetOpTy > m_PtrAdd(const DataLayout &DL, const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
Matches GEP with i8 source element type and canonical index type.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true >, DisjointOr_match< LHS, RHS, true > > m_c_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint", with LHS and RHS commutable.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
UAddWithOverflow_match< LHS_t, RHS_t, Sum_t > m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S)
Match an icmp instruction checking for unsigned overflow on addition.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:51
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
SmallVector< Node, 4 > NodeList
Definition RDFGraph.h:550
iterator end() const
Definition BasicBlock.h:89
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
LLVM_ABI iterator begin() const
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
Definition SFrame.h:77
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
@ Offset
Definition DWP.cpp:577
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
LLVM_ABI bool bypassSlowDivision(BasicBlock *BB, const DenseMap< unsigned int, unsigned int > &BypassWidth, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BranchProbabilityInfo *BPI=nullptr)
This optimization identifies DIV instructions in a BB that can be profitably bypassed and carried out...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
APInt operator*(APInt a, uint64_t RHS)
Definition APInt.h:2261
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1833
auto successors(const MachineBasicBlock *BB)
@ Load
The value being inserted comes from a load (InsertElement only).
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI ReturnInst * FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB, BasicBlock *Pred, DomTreeUpdater *DTU=nullptr)
This method duplicates the specified return instruction into a predecessor which ends in an unconditi...
bool operator!=(uint64_t V1, const APInt &V2)
Definition APInt.h:2139
constexpr from_range_t from_range
LLVM_ABI BasicBlock * splitBlockBefore(BasicBlock *Old, BasicBlock::iterator SplitPt, DomTreeUpdater *DTU, LoopInfo *LI, MemorySSAUpdater *MSSAU, const Twine &BBName="")
Split the specified block at the specified instruction SplitPt.
LLVM_ABI Instruction * SplitBlockAndInsertIfElse(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ElseBlock=nullptr)
Similar to SplitBlockAndInsertIfThen, but the inserted block is on the false path of the branch.
LLVM_ABI bool SplitIndirectBrCriticalEdges(Function &F, bool IgnoreBlocksWithoutPHI, BranchProbabilityInfo *BPI=nullptr, BlockFrequencyInfo *BFI=nullptr, DomTreeUpdater *DTU=nullptr)
LLVM_ABI bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
Examine each PHI in the given block and delete it if it is dead.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:703
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2150
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
constexpr auto equal_to(T &&Arg)
Functor variant of std::equal_to that can be used as a UnaryPredicate in functional algorithms like a...
Definition STLExtras.h:2189
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI Value * simplifyAddInst(Value *LHS, Value *RHS, bool IsNSW, bool IsNUW, const SimplifyQuery &Q)
Given operands for an Add, fold the result or return null.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
void erase(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition STLExtras.h:2220
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
LLVM_ABI bool replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI=nullptr, const DominatorTree *DT=nullptr, AssumptionCache *AC=nullptr, SmallSetVector< Instruction *, 8 > *UnsimplifiedUsers=nullptr)
Replace all uses of 'I' with 'SimpleV' and simplify the uses recursively.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3859
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void SplitBlockAndInsertIfThenElse(Value *Cond, BasicBlock::iterator SplitBefore, Instruction **ThenTerm, Instruction **ElseTerm, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr)
SplitBlockAndInsertIfThenElse is similar to SplitBlockAndInsertIfThen, but also creates the ElseBlock...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI FunctionPass * createCodeGenPrepareLegacyPass()
createCodeGenPrepareLegacyPass - Transform the code to expose more pattern matching during instructio...
LLVM_ABI ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred)
getFCmpCondCode - Return the ISD condition code corresponding to the given LLVM IR floating-point con...
Definition Analysis.cpp:214
LLVM_ABI bool VerifyLoopInfo
Enable verification of loop info.
Definition LoopInfo.cpp:54
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI bool attributesPermitTailCall(const Function *F, const Instruction *I, const ReturnInst *Ret, const TargetLoweringBase &TLI, bool *AllowDifferingSizes=nullptr)
Test if given that the input instruction is in the tail call position, if there is an attribute misma...
Definition Analysis.cpp:757
TargetTransformInfo TTI
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
@ Or
Bitwise or logical OR of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool VerifyDomInfo
Enables verification of dominator trees.
constexpr unsigned BitWidth
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
gep_type_iterator gep_type_begin(const User *GEP)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:241
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:777
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::pair< Value *, FPClassTest > fcmpToClassTest(FCmpInst::Predicate Pred, const Function &F, Value *LHS, Value *RHS, bool LookThroughSrc=true)
Returns a pair of values, which if passed to llvm.is.fpclass, returns the same result as an fcmp with...
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI Value * simplifyURemInst(Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a URem, fold the result or return null.
DenseMap< const Value *, Value * > ValueToValueMap
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define NC
Definition regutils.h:42
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Extended Value Type.
Definition ValueTypes.h:35
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:322
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:338
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:411
static LLVM_ABI EVT getEVT(Type *Ty, bool HandleUnknown=false)
Return the value type corresponding to the specified type.
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:354
bool isRound() const
Return true if the size is a power-of-two number of bytes.
Definition ValueTypes.h:286
bool isScalableVector() const
Return true if this is a vector type where the runtime length is machine dependent.
Definition ValueTypes.h:202
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:175
This contains information for each constraint that we are lowering.