1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
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 file implements the visit functions for load, store and alloca.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/MapVector.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/Loads.h"
19 #include "llvm/IR/ConstantRange.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/MDBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Transforms/InstCombine/InstCombiner.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 using namespace llvm;
30 using namespace PatternMatch;
31 
32 #define DEBUG_TYPE "instcombine"
33 
34 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
35 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
36 
37 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
38 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
39 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
40 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
41 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
42 /// the alloca, and if the source pointer is a pointer to a constant global, we
43 /// can optimize this.
44 static bool
45 isOnlyCopiedFromConstantMemory(AAResults *AA,
46                                Value *V, MemTransferInst *&TheCopy,
47                                SmallVectorImpl<Instruction *> &ToDelete) {
48   // We track lifetime intrinsics as we encounter them.  If we decide to go
49   // ahead and replace the value with the global, this lets the caller quickly
50   // eliminate the markers.
51 
52   SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
53   ValuesToInspect.emplace_back(V, false);
54   while (!ValuesToInspect.empty()) {
55     auto ValuePair = ValuesToInspect.pop_back_val();
56     const bool IsOffset = ValuePair.second;
57     for (auto &U : ValuePair.first->uses()) {
58       auto *I = cast<Instruction>(U.getUser());
59 
60       if (auto *LI = dyn_cast<LoadInst>(I)) {
61         // Ignore non-volatile loads, they are always ok.
62         if (!LI->isSimple()) return false;
63         continue;
64       }
65 
66       if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
67         // If uses of the bitcast are ok, we are ok.
68         ValuesToInspect.emplace_back(I, IsOffset);
69         continue;
70       }
71       if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
72         // If the GEP has all zero indices, it doesn't offset the pointer. If it
73         // doesn't, it does.
74         ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
75         continue;
76       }
77 
78       if (auto *Call = dyn_cast<CallBase>(I)) {
79         // If this is the function being called then we treat it like a load and
80         // ignore it.
81         if (Call->isCallee(&U))
82           continue;
83 
84         unsigned DataOpNo = Call->getDataOperandNo(&U);
85         bool IsArgOperand = Call->isArgOperand(&U);
86 
87         // Inalloca arguments are clobbered by the call.
88         if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
89           return false;
90 
91         // If this is a readonly/readnone call site, then we know it is just a
92         // load (but one that potentially returns the value itself), so we can
93         // ignore it if we know that the value isn't captured.
94         if (Call->onlyReadsMemory() &&
95             (Call->use_empty() || Call->doesNotCapture(DataOpNo)))
96           continue;
97 
98         // If this is being passed as a byval argument, the caller is making a
99         // copy, so it is only a read of the alloca.
100         if (IsArgOperand && Call->isByValArgument(DataOpNo))
101           continue;
102       }
103 
104       // Lifetime intrinsics can be handled by the caller.
105       if (I->isLifetimeStartOrEnd()) {
106         assert(I->use_empty() && "Lifetime markers have no result to use!");
107         ToDelete.push_back(I);
108         continue;
109       }
110 
111       // If this is isn't our memcpy/memmove, reject it as something we can't
112       // handle.
113       MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
114       if (!MI)
115         return false;
116 
117       // If the transfer is using the alloca as a source of the transfer, then
118       // ignore it since it is a load (unless the transfer is volatile).
119       if (U.getOperandNo() == 1) {
120         if (MI->isVolatile()) return false;
121         continue;
122       }
123 
124       // If we already have seen a copy, reject the second one.
125       if (TheCopy) return false;
126 
127       // If the pointer has been offset from the start of the alloca, we can't
128       // safely handle this.
129       if (IsOffset) return false;
130 
131       // If the memintrinsic isn't using the alloca as the dest, reject it.
132       if (U.getOperandNo() != 0) return false;
133 
134       // If the source of the memcpy/move is not a constant global, reject it.
135       if (!AA->pointsToConstantMemory(MI->getSource()))
136         return false;
137 
138       // Otherwise, the transform is safe.  Remember the copy instruction.
139       TheCopy = MI;
140     }
141   }
142   return true;
143 }
144 
145 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
146 /// modified by a copy from a constant global.  If we can prove this, we can
147 /// replace any uses of the alloca with uses of the global directly.
148 static MemTransferInst *
149 isOnlyCopiedFromConstantMemory(AAResults *AA,
150                                AllocaInst *AI,
151                                SmallVectorImpl<Instruction *> &ToDelete) {
152   MemTransferInst *TheCopy = nullptr;
153   if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))
154     return TheCopy;
155   return nullptr;
156 }
157 
158 /// Returns true if V is dereferenceable for size of alloca.
159 static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
160                                            const DataLayout &DL) {
161   if (AI->isArrayAllocation())
162     return false;
163   uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
164   if (!AllocaSize)
165     return false;
166   return isDereferenceableAndAlignedPointer(V, Align(AI->getAlignment()),
167                                             APInt(64, AllocaSize), DL);
168 }
169 
170 static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC,
171                                             AllocaInst &AI) {
172   // Check for array size of 1 (scalar allocation).
173   if (!AI.isArrayAllocation()) {
174     // i32 1 is the canonical array size for scalar allocations.
175     if (AI.getArraySize()->getType()->isIntegerTy(32))
176       return nullptr;
177 
178     // Canonicalize it.
179     return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
180   }
181 
182   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
183   if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
184     if (C->getValue().getActiveBits() <= 64) {
185       Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
186       AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName());
187       New->setAlignment(AI.getAlign());
188 
189       // Scan to the end of the allocation instructions, to skip over a block of
190       // allocas if possible...also skip interleaved debug info
191       //
192       BasicBlock::iterator It(New);
193       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
194         ++It;
195 
196       // Now that I is pointing to the first non-allocation-inst in the block,
197       // insert our getelementptr instruction...
198       //
199       Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
200       Value *NullIdx = Constant::getNullValue(IdxTy);
201       Value *Idx[2] = {NullIdx, NullIdx};
202       Instruction *NewI = GetElementPtrInst::CreateInBounds(
203           NewTy, New, Idx, New->getName() + ".sub");
204       IC.InsertNewInstBefore(NewI, *It);
205 
206       // Gracefully handle allocas in other address spaces.
207       if (AI.getType()->getPointerAddressSpace() !=
208           NewI->getType()->getPointerAddressSpace()) {
209         NewI =
210             CastInst::CreatePointerBitCastOrAddrSpaceCast(NewI, AI.getType());
211         IC.InsertNewInstBefore(NewI, *It);
212       }
213 
214       // Now make everything use the getelementptr instead of the original
215       // allocation.
216       return IC.replaceInstUsesWith(AI, NewI);
217     }
218   }
219 
220   if (isa<UndefValue>(AI.getArraySize()))
221     return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
222 
223   // Ensure that the alloca array size argument has type intptr_t, so that
224   // any casting is exposed early.
225   Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
226   if (AI.getArraySize()->getType() != IntPtrTy) {
227     Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
228     return IC.replaceOperand(AI, 0, V);
229   }
230 
231   return nullptr;
232 }
233 
234 namespace {
235 // If I and V are pointers in different address space, it is not allowed to
236 // use replaceAllUsesWith since I and V have different types. A
237 // non-target-specific transformation should not use addrspacecast on V since
238 // the two address space may be disjoint depending on target.
239 //
240 // This class chases down uses of the old pointer until reaching the load
241 // instructions, then replaces the old pointer in the load instructions with
242 // the new pointer. If during the chasing it sees bitcast or GEP, it will
243 // create new bitcast or GEP with the new pointer and use them in the load
244 // instruction.
245 class PointerReplacer {
246 public:
247   PointerReplacer(InstCombinerImpl &IC) : IC(IC) {}
248 
249   bool collectUsers(Instruction &I);
250   void replacePointer(Instruction &I, Value *V);
251 
252 private:
253   void replace(Instruction *I);
254   Value *getReplacement(Value *I);
255 
256   SmallSetVector<Instruction *, 4> Worklist;
257   MapVector<Value *, Value *> WorkMap;
258   InstCombinerImpl &IC;
259 };
260 } // end anonymous namespace
261 
262 bool PointerReplacer::collectUsers(Instruction &I) {
263   for (auto U : I.users()) {
264     Instruction *Inst = cast<Instruction>(&*U);
265     if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) {
266       if (Load->isVolatile())
267         return false;
268       Worklist.insert(Load);
269     } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
270       Worklist.insert(Inst);
271       if (!collectUsers(*Inst))
272         return false;
273     } else if (isa<MemTransferInst>(Inst)) {
274       Worklist.insert(Inst);
275     } else {
276       LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');
277       return false;
278     }
279   }
280 
281   return true;
282 }
283 
284 Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }
285 
286 void PointerReplacer::replace(Instruction *I) {
287   if (getReplacement(I))
288     return;
289 
290   if (auto *LT = dyn_cast<LoadInst>(I)) {
291     auto *V = getReplacement(LT->getPointerOperand());
292     assert(V && "Operand not replaced");
293     auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),
294                               LT->getAlign(), LT->getOrdering(),
295                               LT->getSyncScopeID());
296     NewI->takeName(LT);
297     copyMetadataForLoad(*NewI, *LT);
298 
299     IC.InsertNewInstWith(NewI, *LT);
300     IC.replaceInstUsesWith(*LT, NewI);
301     WorkMap[LT] = NewI;
302   } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
303     auto *V = getReplacement(GEP->getPointerOperand());
304     assert(V && "Operand not replaced");
305     SmallVector<Value *, 8> Indices;
306     Indices.append(GEP->idx_begin(), GEP->idx_end());
307     auto *NewI = GetElementPtrInst::Create(
308         V->getType()->getPointerElementType(), V, Indices);
309     IC.InsertNewInstWith(NewI, *GEP);
310     NewI->takeName(GEP);
311     WorkMap[GEP] = NewI;
312   } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
313     auto *V = getReplacement(BC->getOperand(0));
314     assert(V && "Operand not replaced");
315     auto *NewT = PointerType::get(BC->getType()->getPointerElementType(),
316                                   V->getType()->getPointerAddressSpace());
317     auto *NewI = new BitCastInst(V, NewT);
318     IC.InsertNewInstWith(NewI, *BC);
319     NewI->takeName(BC);
320     WorkMap[BC] = NewI;
321   } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
322     auto *SrcV = getReplacement(MemCpy->getRawSource());
323     // The pointer may appear in the destination of a copy, but we don't want to
324     // replace it.
325     if (!SrcV) {
326       assert(getReplacement(MemCpy->getRawDest()) &&
327              "destination not in replace list");
328       return;
329     }
330 
331     IC.Builder.SetInsertPoint(MemCpy);
332     auto *NewI = IC.Builder.CreateMemTransferInst(
333         MemCpy->getIntrinsicID(), MemCpy->getRawDest(), MemCpy->getDestAlign(),
334         SrcV, MemCpy->getSourceAlign(), MemCpy->getLength(),
335         MemCpy->isVolatile());
336     AAMDNodes AAMD;
337     MemCpy->getAAMetadata(AAMD);
338     if (AAMD)
339       NewI->setAAMetadata(AAMD);
340 
341     IC.eraseInstFromFunction(*MemCpy);
342     WorkMap[MemCpy] = NewI;
343   } else {
344     llvm_unreachable("should never reach here");
345   }
346 }
347 
348 void PointerReplacer::replacePointer(Instruction &I, Value *V) {
349 #ifndef NDEBUG
350   auto *PT = cast<PointerType>(I.getType());
351   auto *NT = cast<PointerType>(V->getType());
352   assert(PT != NT && PT->getElementType() == NT->getElementType() &&
353          "Invalid usage");
354 #endif
355   WorkMap[&I] = V;
356 
357   for (Instruction *Workitem : Worklist)
358     replace(Workitem);
359 }
360 
361 Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) {
362   if (auto *I = simplifyAllocaArraySize(*this, AI))
363     return I;
364 
365   if (AI.getAllocatedType()->isSized()) {
366     // Move all alloca's of zero byte objects to the entry block and merge them
367     // together.  Note that we only do this for alloca's, because malloc should
368     // allocate and return a unique pointer, even for a zero byte allocation.
369     if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinSize() == 0) {
370       // For a zero sized alloca there is no point in doing an array allocation.
371       // This is helpful if the array size is a complicated expression not used
372       // elsewhere.
373       if (AI.isArrayAllocation())
374         return replaceOperand(AI, 0,
375             ConstantInt::get(AI.getArraySize()->getType(), 1));
376 
377       // Get the first instruction in the entry block.
378       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
379       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
380       if (FirstInst != &AI) {
381         // If the entry block doesn't start with a zero-size alloca then move
382         // this one to the start of the entry block.  There is no problem with
383         // dominance as the array size was forced to a constant earlier already.
384         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
385         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
386             DL.getTypeAllocSize(EntryAI->getAllocatedType())
387                     .getKnownMinSize() != 0) {
388           AI.moveBefore(FirstInst);
389           return &AI;
390         }
391 
392         // Replace this zero-sized alloca with the one at the start of the entry
393         // block after ensuring that the address will be aligned enough for both
394         // types.
395         const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
396         EntryAI->setAlignment(MaxAlign);
397         if (AI.getType() != EntryAI->getType())
398           return new BitCastInst(EntryAI, AI.getType());
399         return replaceInstUsesWith(AI, EntryAI);
400       }
401     }
402   }
403 
404   // Check to see if this allocation is only modified by a memcpy/memmove from
405   // a constant whose alignment is equal to or exceeds that of the allocation.
406   // If this is the case, we can change all users to use the constant global
407   // instead.  This is commonly produced by the CFE by constructs like "void
408   // foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' is only subsequently
409   // read.
410   SmallVector<Instruction *, 4> ToDelete;
411   if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {
412     Value *TheSrc = Copy->getSource();
413     Align AllocaAlign = AI.getAlign();
414     Align SourceAlign = getOrEnforceKnownAlignment(
415       TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
416     if (AllocaAlign <= SourceAlign &&
417         isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
418         !isa<Instruction>(TheSrc)) {
419       // FIXME: Can we sink instructions without violating dominance when TheSrc
420       // is an instruction instead of a constant or argument?
421       LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
422       LLVM_DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
423       unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
424       auto *DestTy = PointerType::get(AI.getAllocatedType(), SrcAddrSpace);
425       if (AI.getType()->getAddressSpace() == SrcAddrSpace) {
426         for (Instruction *Delete : ToDelete)
427           eraseInstFromFunction(*Delete);
428 
429         Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
430         Instruction *NewI = replaceInstUsesWith(AI, Cast);
431         eraseInstFromFunction(*Copy);
432         ++NumGlobalCopies;
433         return NewI;
434       }
435 
436       PointerReplacer PtrReplacer(*this);
437       if (PtrReplacer.collectUsers(AI)) {
438         for (Instruction *Delete : ToDelete)
439           eraseInstFromFunction(*Delete);
440 
441         Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
442         PtrReplacer.replacePointer(AI, Cast);
443         ++NumGlobalCopies;
444       }
445     }
446   }
447 
448   // At last, use the generic allocation site handler to aggressively remove
449   // unused allocas.
450   return visitAllocSite(AI);
451 }
452 
453 // Are we allowed to form a atomic load or store of this type?
454 static bool isSupportedAtomicType(Type *Ty) {
455   return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
456 }
457 
458 /// Helper to combine a load to a new type.
459 ///
460 /// This just does the work of combining a load to a new type. It handles
461 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
462 /// loaded *value* type. This will convert it to a pointer, cast the operand to
463 /// that pointer type, load it, etc.
464 ///
465 /// Note that this will create all of the instructions with whatever insert
466 /// point the \c InstCombinerImpl currently is using.
467 LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy,
468                                                  const Twine &Suffix) {
469   assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
470          "can't fold an atomic load to requested type");
471 
472   Value *Ptr = LI.getPointerOperand();
473   unsigned AS = LI.getPointerAddressSpace();
474   Type *NewPtrTy = NewTy->getPointerTo(AS);
475   Value *NewPtr = nullptr;
476   if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
477         NewPtr->getType() == NewPtrTy))
478     NewPtr = Builder.CreateBitCast(Ptr, NewPtrTy);
479 
480   LoadInst *NewLoad = Builder.CreateAlignedLoad(
481       NewTy, NewPtr, LI.getAlign(), LI.isVolatile(), LI.getName() + Suffix);
482   NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
483   copyMetadataForLoad(*NewLoad, LI);
484   return NewLoad;
485 }
486 
487 /// Combine a store to a new type.
488 ///
489 /// Returns the newly created store instruction.
490 static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI,
491                                          Value *V) {
492   assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
493          "can't fold an atomic store of requested type");
494 
495   Value *Ptr = SI.getPointerOperand();
496   unsigned AS = SI.getPointerAddressSpace();
497   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
498   SI.getAllMetadata(MD);
499 
500   StoreInst *NewStore = IC.Builder.CreateAlignedStore(
501       V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
502       SI.getAlign(), SI.isVolatile());
503   NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
504   for (const auto &MDPair : MD) {
505     unsigned ID = MDPair.first;
506     MDNode *N = MDPair.second;
507     // Note, essentially every kind of metadata should be preserved here! This
508     // routine is supposed to clone a store instruction changing *only its
509     // type*. The only metadata it makes sense to drop is metadata which is
510     // invalidated when the pointer type changes. This should essentially
511     // never be the case in LLVM, but we explicitly switch over only known
512     // metadata to be conservatively correct. If you are adding metadata to
513     // LLVM which pertains to stores, you almost certainly want to add it
514     // here.
515     switch (ID) {
516     case LLVMContext::MD_dbg:
517     case LLVMContext::MD_tbaa:
518     case LLVMContext::MD_prof:
519     case LLVMContext::MD_fpmath:
520     case LLVMContext::MD_tbaa_struct:
521     case LLVMContext::MD_alias_scope:
522     case LLVMContext::MD_noalias:
523     case LLVMContext::MD_nontemporal:
524     case LLVMContext::MD_mem_parallel_loop_access:
525     case LLVMContext::MD_access_group:
526       // All of these directly apply.
527       NewStore->setMetadata(ID, N);
528       break;
529     case LLVMContext::MD_invariant_load:
530     case LLVMContext::MD_nonnull:
531     case LLVMContext::MD_noundef:
532     case LLVMContext::MD_range:
533     case LLVMContext::MD_align:
534     case LLVMContext::MD_dereferenceable:
535     case LLVMContext::MD_dereferenceable_or_null:
536       // These don't apply for stores.
537       break;
538     }
539   }
540 
541   return NewStore;
542 }
543 
544 /// Returns true if instruction represent minmax pattern like:
545 ///   select ((cmp load V1, load V2), V1, V2).
546 static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) {
547   assert(V->getType()->isPointerTy() && "Expected pointer type.");
548   // Ignore possible ty* to ixx* bitcast.
549   V = InstCombiner::peekThroughBitcast(V);
550   // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax
551   // pattern.
552   CmpInst::Predicate Pred;
553   Instruction *L1;
554   Instruction *L2;
555   Value *LHS;
556   Value *RHS;
557   if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
558                          m_Value(LHS), m_Value(RHS))))
559     return false;
560   LoadTy = L1->getType();
561   return (match(L1, m_Load(m_Specific(LHS))) &&
562           match(L2, m_Load(m_Specific(RHS)))) ||
563          (match(L1, m_Load(m_Specific(RHS))) &&
564           match(L2, m_Load(m_Specific(LHS))));
565 }
566 
567 /// Combine loads to match the type of their uses' value after looking
568 /// through intervening bitcasts.
569 ///
570 /// The core idea here is that if the result of a load is used in an operation,
571 /// we should load the type most conducive to that operation. For example, when
572 /// loading an integer and converting that immediately to a pointer, we should
573 /// instead directly load a pointer.
574 ///
575 /// However, this routine must never change the width of a load or the number of
576 /// loads as that would introduce a semantic change. This combine is expected to
577 /// be a semantic no-op which just allows loads to more closely model the types
578 /// of their consuming operations.
579 ///
580 /// Currently, we also refuse to change the precise type used for an atomic load
581 /// or a volatile load. This is debatable, and might be reasonable to change
582 /// later. However, it is risky in case some backend or other part of LLVM is
583 /// relying on the exact type loaded to select appropriate atomic operations.
584 static Instruction *combineLoadToOperationType(InstCombinerImpl &IC,
585                                                LoadInst &LI) {
586   // FIXME: We could probably with some care handle both volatile and ordered
587   // atomic loads here but it isn't clear that this is important.
588   if (!LI.isUnordered())
589     return nullptr;
590 
591   if (LI.use_empty())
592     return nullptr;
593 
594   // swifterror values can't be bitcasted.
595   if (LI.getPointerOperand()->isSwiftError())
596     return nullptr;
597 
598   const DataLayout &DL = IC.getDataLayout();
599 
600   // Fold away bit casts of the loaded value by loading the desired type.
601   // Note that we should not do this for pointer<->integer casts,
602   // because that would result in type punning.
603   if (LI.hasOneUse()) {
604     // Don't transform when the type is x86_amx, it makes the pass that lower
605     // x86_amx type happy.
606     if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
607       assert(!LI.getType()->isX86_AMXTy() &&
608              "load from x86_amx* should not happen!");
609       if (BC->getType()->isX86_AMXTy())
610         return nullptr;
611     }
612 
613     if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
614       if (CI->isNoopCast(DL) && LI.getType()->isPtrOrPtrVectorTy() ==
615                                     CI->getDestTy()->isPtrOrPtrVectorTy())
616         if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
617           LoadInst *NewLoad = IC.combineLoadToNewType(LI, CI->getDestTy());
618           CI->replaceAllUsesWith(NewLoad);
619           IC.eraseInstFromFunction(*CI);
620           return &LI;
621         }
622   }
623 
624   // FIXME: We should also canonicalize loads of vectors when their elements are
625   // cast to other types.
626   return nullptr;
627 }
628 
629 static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) {
630   // FIXME: We could probably with some care handle both volatile and atomic
631   // stores here but it isn't clear that this is important.
632   if (!LI.isSimple())
633     return nullptr;
634 
635   Type *T = LI.getType();
636   if (!T->isAggregateType())
637     return nullptr;
638 
639   StringRef Name = LI.getName();
640   assert(LI.getAlignment() && "Alignment must be set at this point");
641 
642   if (auto *ST = dyn_cast<StructType>(T)) {
643     // If the struct only have one element, we unpack.
644     auto NumElements = ST->getNumElements();
645     if (NumElements == 1) {
646       LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
647                                                   ".unpack");
648       AAMDNodes AAMD;
649       LI.getAAMetadata(AAMD);
650       NewLoad->setAAMetadata(AAMD);
651       return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
652         UndefValue::get(T), NewLoad, 0, Name));
653     }
654 
655     // We don't want to break loads with padding here as we'd loose
656     // the knowledge that padding exists for the rest of the pipeline.
657     const DataLayout &DL = IC.getDataLayout();
658     auto *SL = DL.getStructLayout(ST);
659     if (SL->hasPadding())
660       return nullptr;
661 
662     const auto Align = LI.getAlign();
663     auto *Addr = LI.getPointerOperand();
664     auto *IdxType = Type::getInt32Ty(T->getContext());
665     auto *Zero = ConstantInt::get(IdxType, 0);
666 
667     Value *V = UndefValue::get(T);
668     for (unsigned i = 0; i < NumElements; i++) {
669       Value *Indices[2] = {
670         Zero,
671         ConstantInt::get(IdxType, i),
672       };
673       auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
674                                                Name + ".elt");
675       auto *L = IC.Builder.CreateAlignedLoad(
676           ST->getElementType(i), Ptr,
677           commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");
678       // Propagate AA metadata. It'll still be valid on the narrowed load.
679       AAMDNodes AAMD;
680       LI.getAAMetadata(AAMD);
681       L->setAAMetadata(AAMD);
682       V = IC.Builder.CreateInsertValue(V, L, i);
683     }
684 
685     V->setName(Name);
686     return IC.replaceInstUsesWith(LI, V);
687   }
688 
689   if (auto *AT = dyn_cast<ArrayType>(T)) {
690     auto *ET = AT->getElementType();
691     auto NumElements = AT->getNumElements();
692     if (NumElements == 1) {
693       LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
694       AAMDNodes AAMD;
695       LI.getAAMetadata(AAMD);
696       NewLoad->setAAMetadata(AAMD);
697       return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
698         UndefValue::get(T), NewLoad, 0, Name));
699     }
700 
701     // Bail out if the array is too large. Ideally we would like to optimize
702     // arrays of arbitrary size but this has a terrible impact on compile time.
703     // The threshold here is chosen arbitrarily, maybe needs a little bit of
704     // tuning.
705     if (NumElements > IC.MaxArraySizeForCombine)
706       return nullptr;
707 
708     const DataLayout &DL = IC.getDataLayout();
709     auto EltSize = DL.getTypeAllocSize(ET);
710     const auto Align = LI.getAlign();
711 
712     auto *Addr = LI.getPointerOperand();
713     auto *IdxType = Type::getInt64Ty(T->getContext());
714     auto *Zero = ConstantInt::get(IdxType, 0);
715 
716     Value *V = UndefValue::get(T);
717     uint64_t Offset = 0;
718     for (uint64_t i = 0; i < NumElements; i++) {
719       Value *Indices[2] = {
720         Zero,
721         ConstantInt::get(IdxType, i),
722       };
723       auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
724                                                Name + ".elt");
725       auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
726                                              commonAlignment(Align, Offset),
727                                              Name + ".unpack");
728       AAMDNodes AAMD;
729       LI.getAAMetadata(AAMD);
730       L->setAAMetadata(AAMD);
731       V = IC.Builder.CreateInsertValue(V, L, i);
732       Offset += EltSize;
733     }
734 
735     V->setName(Name);
736     return IC.replaceInstUsesWith(LI, V);
737   }
738 
739   return nullptr;
740 }
741 
742 // If we can determine that all possible objects pointed to by the provided
743 // pointer value are, not only dereferenceable, but also definitively less than
744 // or equal to the provided maximum size, then return true. Otherwise, return
745 // false (constant global values and allocas fall into this category).
746 //
747 // FIXME: This should probably live in ValueTracking (or similar).
748 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
749                                      const DataLayout &DL) {
750   SmallPtrSet<Value *, 4> Visited;
751   SmallVector<Value *, 4> Worklist(1, V);
752 
753   do {
754     Value *P = Worklist.pop_back_val();
755     P = P->stripPointerCasts();
756 
757     if (!Visited.insert(P).second)
758       continue;
759 
760     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
761       Worklist.push_back(SI->getTrueValue());
762       Worklist.push_back(SI->getFalseValue());
763       continue;
764     }
765 
766     if (PHINode *PN = dyn_cast<PHINode>(P)) {
767       append_range(Worklist, PN->incoming_values());
768       continue;
769     }
770 
771     if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
772       if (GA->isInterposable())
773         return false;
774       Worklist.push_back(GA->getAliasee());
775       continue;
776     }
777 
778     // If we know how big this object is, and it is less than MaxSize, continue
779     // searching. Otherwise, return false.
780     if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
781       if (!AI->getAllocatedType()->isSized())
782         return false;
783 
784       ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
785       if (!CS)
786         return false;
787 
788       uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
789       // Make sure that, even if the multiplication below would wrap as an
790       // uint64_t, we still do the right thing.
791       if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
792         return false;
793       continue;
794     }
795 
796     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
797       if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
798         return false;
799 
800       uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
801       if (InitSize > MaxSize)
802         return false;
803       continue;
804     }
805 
806     return false;
807   } while (!Worklist.empty());
808 
809   return true;
810 }
811 
812 // If we're indexing into an object of a known size, and the outer index is
813 // not a constant, but having any value but zero would lead to undefined
814 // behavior, replace it with zero.
815 //
816 // For example, if we have:
817 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
818 // ...
819 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
820 // ... = load i32* %arrayidx, align 4
821 // Then we know that we can replace %x in the GEP with i64 0.
822 //
823 // FIXME: We could fold any GEP index to zero that would cause UB if it were
824 // not zero. Currently, we only handle the first such index. Also, we could
825 // also search through non-zero constant indices if we kept track of the
826 // offsets those indices implied.
827 static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC,
828                                      GetElementPtrInst *GEPI, Instruction *MemI,
829                                      unsigned &Idx) {
830   if (GEPI->getNumOperands() < 2)
831     return false;
832 
833   // Find the first non-zero index of a GEP. If all indices are zero, return
834   // one past the last index.
835   auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
836     unsigned I = 1;
837     for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
838       Value *V = GEPI->getOperand(I);
839       if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
840         if (CI->isZero())
841           continue;
842 
843       break;
844     }
845 
846     return I;
847   };
848 
849   // Skip through initial 'zero' indices, and find the corresponding pointer
850   // type. See if the next index is not a constant.
851   Idx = FirstNZIdx(GEPI);
852   if (Idx == GEPI->getNumOperands())
853     return false;
854   if (isa<Constant>(GEPI->getOperand(Idx)))
855     return false;
856 
857   SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
858   Type *SourceElementType = GEPI->getSourceElementType();
859   // Size information about scalable vectors is not available, so we cannot
860   // deduce whether indexing at n is undefined behaviour or not. Bail out.
861   if (isa<ScalableVectorType>(SourceElementType))
862     return false;
863 
864   Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
865   if (!AllocTy || !AllocTy->isSized())
866     return false;
867   const DataLayout &DL = IC.getDataLayout();
868   uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedSize();
869 
870   // If there are more indices after the one we might replace with a zero, make
871   // sure they're all non-negative. If any of them are negative, the overall
872   // address being computed might be before the base address determined by the
873   // first non-zero index.
874   auto IsAllNonNegative = [&]() {
875     for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
876       KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
877       if (Known.isNonNegative())
878         continue;
879       return false;
880     }
881 
882     return true;
883   };
884 
885   // FIXME: If the GEP is not inbounds, and there are extra indices after the
886   // one we'll replace, those could cause the address computation to wrap
887   // (rendering the IsAllNonNegative() check below insufficient). We can do
888   // better, ignoring zero indices (and other indices we can prove small
889   // enough not to wrap).
890   if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
891     return false;
892 
893   // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
894   // also known to be dereferenceable.
895   return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
896          IsAllNonNegative();
897 }
898 
899 // If we're indexing into an object with a variable index for the memory
900 // access, but the object has only one element, we can assume that the index
901 // will always be zero. If we replace the GEP, return it.
902 template <typename T>
903 static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr,
904                                           T &MemI) {
905   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
906     unsigned Idx;
907     if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
908       Instruction *NewGEPI = GEPI->clone();
909       NewGEPI->setOperand(Idx,
910         ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
911       NewGEPI->insertBefore(GEPI);
912       MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
913       return NewGEPI;
914     }
915   }
916 
917   return nullptr;
918 }
919 
920 static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
921   if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
922     return false;
923 
924   auto *Ptr = SI.getPointerOperand();
925   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
926     Ptr = GEPI->getOperand(0);
927   return (isa<ConstantPointerNull>(Ptr) &&
928           !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
929 }
930 
931 static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
932   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
933     const Value *GEPI0 = GEPI->getOperand(0);
934     if (isa<ConstantPointerNull>(GEPI0) &&
935         !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
936       return true;
937   }
938   if (isa<UndefValue>(Op) ||
939       (isa<ConstantPointerNull>(Op) &&
940        !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))
941     return true;
942   return false;
943 }
944 
945 Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) {
946   Value *Op = LI.getOperand(0);
947 
948   // Try to canonicalize the loaded type.
949   if (Instruction *Res = combineLoadToOperationType(*this, LI))
950     return Res;
951 
952   // Attempt to improve the alignment.
953   Align KnownAlign = getOrEnforceKnownAlignment(
954       Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);
955   if (KnownAlign > LI.getAlign())
956     LI.setAlignment(KnownAlign);
957 
958   // Replace GEP indices if possible.
959   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
960       Worklist.push(NewGEPI);
961       return &LI;
962   }
963 
964   if (Instruction *Res = unpackLoadToAggregate(*this, LI))
965     return Res;
966 
967   // Do really simple store-to-load forwarding and load CSE, to catch cases
968   // where there are several consecutive memory accesses to the same location,
969   // separated by a few arithmetic operations.
970   bool IsLoadCSE = false;
971   if (Value *AvailableVal = FindAvailableLoadedValue(&LI, *AA, &IsLoadCSE)) {
972     if (IsLoadCSE)
973       combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
974 
975     return replaceInstUsesWith(
976         LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
977                                            LI.getName() + ".cast"));
978   }
979 
980   // None of the following transforms are legal for volatile/ordered atomic
981   // loads.  Most of them do apply for unordered atomics.
982   if (!LI.isUnordered()) return nullptr;
983 
984   // load(gep null, ...) -> unreachable
985   // load null/undef -> unreachable
986   // TODO: Consider a target hook for valid address spaces for this xforms.
987   if (canSimplifyNullLoadOrGEP(LI, Op)) {
988     // Insert a new store to null instruction before the load to indicate
989     // that this code is not reachable.  We do this instead of inserting
990     // an unreachable instruction directly because we cannot modify the
991     // CFG.
992     StoreInst *SI = new StoreInst(PoisonValue::get(LI.getType()),
993                                   Constant::getNullValue(Op->getType()), &LI);
994     SI->setDebugLoc(LI.getDebugLoc());
995     return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));
996   }
997 
998   if (Op->hasOneUse()) {
999     // Change select and PHI nodes to select values instead of addresses: this
1000     // helps alias analysis out a lot, allows many others simplifications, and
1001     // exposes redundancy in the code.
1002     //
1003     // Note that we cannot do the transformation unless we know that the
1004     // introduced loads cannot trap!  Something like this is valid as long as
1005     // the condition is always false: load (select bool %C, int* null, int* %G),
1006     // but it would not be valid if we transformed it to load from null
1007     // unconditionally.
1008     //
1009     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1010       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
1011       Align Alignment = LI.getAlign();
1012       if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
1013                                       Alignment, DL, SI) &&
1014           isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
1015                                       Alignment, DL, SI)) {
1016         LoadInst *V1 =
1017             Builder.CreateLoad(LI.getType(), SI->getOperand(1),
1018                                SI->getOperand(1)->getName() + ".val");
1019         LoadInst *V2 =
1020             Builder.CreateLoad(LI.getType(), SI->getOperand(2),
1021                                SI->getOperand(2)->getName() + ".val");
1022         assert(LI.isUnordered() && "implied by above");
1023         V1->setAlignment(Alignment);
1024         V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1025         V2->setAlignment(Alignment);
1026         V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1027         return SelectInst::Create(SI->getCondition(), V1, V2);
1028       }
1029 
1030       // load (select (cond, null, P)) -> load P
1031       if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
1032           !NullPointerIsDefined(SI->getFunction(),
1033                                 LI.getPointerAddressSpace()))
1034         return replaceOperand(LI, 0, SI->getOperand(2));
1035 
1036       // load (select (cond, P, null)) -> load P
1037       if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1038           !NullPointerIsDefined(SI->getFunction(),
1039                                 LI.getPointerAddressSpace()))
1040         return replaceOperand(LI, 0, SI->getOperand(1));
1041     }
1042   }
1043   return nullptr;
1044 }
1045 
1046 /// Look for extractelement/insertvalue sequence that acts like a bitcast.
1047 ///
1048 /// \returns underlying value that was "cast", or nullptr otherwise.
1049 ///
1050 /// For example, if we have:
1051 ///
1052 ///     %E0 = extractelement <2 x double> %U, i32 0
1053 ///     %V0 = insertvalue [2 x double] undef, double %E0, 0
1054 ///     %E1 = extractelement <2 x double> %U, i32 1
1055 ///     %V1 = insertvalue [2 x double] %V0, double %E1, 1
1056 ///
1057 /// and the layout of a <2 x double> is isomorphic to a [2 x double],
1058 /// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1059 /// Note that %U may contain non-undef values where %V1 has undef.
1060 static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) {
1061   Value *U = nullptr;
1062   while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1063     auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1064     if (!E)
1065       return nullptr;
1066     auto *W = E->getVectorOperand();
1067     if (!U)
1068       U = W;
1069     else if (U != W)
1070       return nullptr;
1071     auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1072     if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1073       return nullptr;
1074     V = IV->getAggregateOperand();
1075   }
1076   if (!match(V, m_Undef()) || !U)
1077     return nullptr;
1078 
1079   auto *UT = cast<VectorType>(U->getType());
1080   auto *VT = V->getType();
1081   // Check that types UT and VT are bitwise isomorphic.
1082   const auto &DL = IC.getDataLayout();
1083   if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1084     return nullptr;
1085   }
1086   if (auto *AT = dyn_cast<ArrayType>(VT)) {
1087     if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1088       return nullptr;
1089   } else {
1090     auto *ST = cast<StructType>(VT);
1091     if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1092       return nullptr;
1093     for (const auto *EltT : ST->elements()) {
1094       if (EltT != UT->getElementType())
1095         return nullptr;
1096     }
1097   }
1098   return U;
1099 }
1100 
1101 /// Combine stores to match the type of value being stored.
1102 ///
1103 /// The core idea here is that the memory does not have any intrinsic type and
1104 /// where we can we should match the type of a store to the type of value being
1105 /// stored.
1106 ///
1107 /// However, this routine must never change the width of a store or the number of
1108 /// stores as that would introduce a semantic change. This combine is expected to
1109 /// be a semantic no-op which just allows stores to more closely model the types
1110 /// of their incoming values.
1111 ///
1112 /// Currently, we also refuse to change the precise type used for an atomic or
1113 /// volatile store. This is debatable, and might be reasonable to change later.
1114 /// However, it is risky in case some backend or other part of LLVM is relying
1115 /// on the exact type stored to select appropriate atomic operations.
1116 ///
1117 /// \returns true if the store was successfully combined away. This indicates
1118 /// the caller must erase the store instruction. We have to let the caller erase
1119 /// the store instruction as otherwise there is no way to signal whether it was
1120 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
1121 static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) {
1122   // FIXME: We could probably with some care handle both volatile and ordered
1123   // atomic stores here but it isn't clear that this is important.
1124   if (!SI.isUnordered())
1125     return false;
1126 
1127   // swifterror values can't be bitcasted.
1128   if (SI.getPointerOperand()->isSwiftError())
1129     return false;
1130 
1131   Value *V = SI.getValueOperand();
1132 
1133   // Fold away bit casts of the stored value by storing the original type.
1134   if (auto *BC = dyn_cast<BitCastInst>(V)) {
1135     assert(!BC->getType()->isX86_AMXTy() &&
1136            "store to x86_amx* should not happen!");
1137     V = BC->getOperand(0);
1138     // Don't transform when the type is x86_amx, it makes the pass that lower
1139     // x86_amx type happy.
1140     if (V->getType()->isX86_AMXTy())
1141       return false;
1142     if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1143       combineStoreToNewValue(IC, SI, V);
1144       return true;
1145     }
1146   }
1147 
1148   if (Value *U = likeBitCastFromVector(IC, V))
1149     if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1150       combineStoreToNewValue(IC, SI, U);
1151       return true;
1152     }
1153 
1154   // FIXME: We should also canonicalize stores of vectors when their elements
1155   // are cast to other types.
1156   return false;
1157 }
1158 
1159 static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) {
1160   // FIXME: We could probably with some care handle both volatile and atomic
1161   // stores here but it isn't clear that this is important.
1162   if (!SI.isSimple())
1163     return false;
1164 
1165   Value *V = SI.getValueOperand();
1166   Type *T = V->getType();
1167 
1168   if (!T->isAggregateType())
1169     return false;
1170 
1171   if (auto *ST = dyn_cast<StructType>(T)) {
1172     // If the struct only have one element, we unpack.
1173     unsigned Count = ST->getNumElements();
1174     if (Count == 1) {
1175       V = IC.Builder.CreateExtractValue(V, 0);
1176       combineStoreToNewValue(IC, SI, V);
1177       return true;
1178     }
1179 
1180     // We don't want to break loads with padding here as we'd loose
1181     // the knowledge that padding exists for the rest of the pipeline.
1182     const DataLayout &DL = IC.getDataLayout();
1183     auto *SL = DL.getStructLayout(ST);
1184     if (SL->hasPadding())
1185       return false;
1186 
1187     const auto Align = SI.getAlign();
1188 
1189     SmallString<16> EltName = V->getName();
1190     EltName += ".elt";
1191     auto *Addr = SI.getPointerOperand();
1192     SmallString<16> AddrName = Addr->getName();
1193     AddrName += ".repack";
1194 
1195     auto *IdxType = Type::getInt32Ty(ST->getContext());
1196     auto *Zero = ConstantInt::get(IdxType, 0);
1197     for (unsigned i = 0; i < Count; i++) {
1198       Value *Indices[2] = {
1199         Zero,
1200         ConstantInt::get(IdxType, i),
1201       };
1202       auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1203                                                AddrName);
1204       auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1205       auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));
1206       llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1207       AAMDNodes AAMD;
1208       SI.getAAMetadata(AAMD);
1209       NS->setAAMetadata(AAMD);
1210     }
1211 
1212     return true;
1213   }
1214 
1215   if (auto *AT = dyn_cast<ArrayType>(T)) {
1216     // If the array only have one element, we unpack.
1217     auto NumElements = AT->getNumElements();
1218     if (NumElements == 1) {
1219       V = IC.Builder.CreateExtractValue(V, 0);
1220       combineStoreToNewValue(IC, SI, V);
1221       return true;
1222     }
1223 
1224     // Bail out if the array is too large. Ideally we would like to optimize
1225     // arrays of arbitrary size but this has a terrible impact on compile time.
1226     // The threshold here is chosen arbitrarily, maybe needs a little bit of
1227     // tuning.
1228     if (NumElements > IC.MaxArraySizeForCombine)
1229       return false;
1230 
1231     const DataLayout &DL = IC.getDataLayout();
1232     auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1233     const auto Align = SI.getAlign();
1234 
1235     SmallString<16> EltName = V->getName();
1236     EltName += ".elt";
1237     auto *Addr = SI.getPointerOperand();
1238     SmallString<16> AddrName = Addr->getName();
1239     AddrName += ".repack";
1240 
1241     auto *IdxType = Type::getInt64Ty(T->getContext());
1242     auto *Zero = ConstantInt::get(IdxType, 0);
1243 
1244     uint64_t Offset = 0;
1245     for (uint64_t i = 0; i < NumElements; i++) {
1246       Value *Indices[2] = {
1247         Zero,
1248         ConstantInt::get(IdxType, i),
1249       };
1250       auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1251                                                AddrName);
1252       auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1253       auto EltAlign = commonAlignment(Align, Offset);
1254       Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1255       AAMDNodes AAMD;
1256       SI.getAAMetadata(AAMD);
1257       NS->setAAMetadata(AAMD);
1258       Offset += EltSize;
1259     }
1260 
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 /// equivalentAddressValues - Test if A and B will obviously have the same
1268 /// value. This includes recognizing that %t0 and %t1 will have the same
1269 /// value in code like this:
1270 ///   %t0 = getelementptr \@a, 0, 3
1271 ///   store i32 0, i32* %t0
1272 ///   %t1 = getelementptr \@a, 0, 3
1273 ///   %t2 = load i32* %t1
1274 ///
1275 static bool equivalentAddressValues(Value *A, Value *B) {
1276   // Test if the values are trivially equivalent.
1277   if (A == B) return true;
1278 
1279   // Test if the values come form identical arithmetic instructions.
1280   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1281   // its only used to compare two uses within the same basic block, which
1282   // means that they'll always either have the same value or one of them
1283   // will have an undefined value.
1284   if (isa<BinaryOperator>(A) ||
1285       isa<CastInst>(A) ||
1286       isa<PHINode>(A) ||
1287       isa<GetElementPtrInst>(A))
1288     if (Instruction *BI = dyn_cast<Instruction>(B))
1289       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1290         return true;
1291 
1292   // Otherwise they may not be equivalent.
1293   return false;
1294 }
1295 
1296 /// Converts store (bitcast (load (bitcast (select ...)))) to
1297 /// store (load (select ...)), where select is minmax:
1298 /// select ((cmp load V1, load V2), V1, V2).
1299 static bool removeBitcastsFromLoadStoreOnMinMax(InstCombinerImpl &IC,
1300                                                 StoreInst &SI) {
1301   // bitcast?
1302   if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
1303     return false;
1304   // load? integer?
1305   Value *LoadAddr;
1306   if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
1307     return false;
1308   auto *LI = cast<LoadInst>(SI.getValueOperand());
1309   if (!LI->getType()->isIntegerTy())
1310     return false;
1311   Type *CmpLoadTy;
1312   if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy))
1313     return false;
1314 
1315   // Make sure the type would actually change.
1316   // This condition can be hit with chains of bitcasts.
1317   if (LI->getType() == CmpLoadTy)
1318     return false;
1319 
1320   // Make sure we're not changing the size of the load/store.
1321   const auto &DL = IC.getDataLayout();
1322   if (DL.getTypeStoreSizeInBits(LI->getType()) !=
1323       DL.getTypeStoreSizeInBits(CmpLoadTy))
1324     return false;
1325 
1326   if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1327         auto *SI = dyn_cast<StoreInst>(U);
1328         return SI && SI->getPointerOperand() != LI &&
1329                InstCombiner::peekThroughBitcast(SI->getPointerOperand()) !=
1330                    LoadAddr &&
1331                !SI->getPointerOperand()->isSwiftError();
1332       }))
1333     return false;
1334 
1335   IC.Builder.SetInsertPoint(LI);
1336   LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy);
1337   // Replace all the stores with stores of the newly loaded value.
1338   for (auto *UI : LI->users()) {
1339     auto *USI = cast<StoreInst>(UI);
1340     IC.Builder.SetInsertPoint(USI);
1341     combineStoreToNewValue(IC, *USI, NewLI);
1342   }
1343   IC.replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
1344   IC.eraseInstFromFunction(*LI);
1345   return true;
1346 }
1347 
1348 Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) {
1349   Value *Val = SI.getOperand(0);
1350   Value *Ptr = SI.getOperand(1);
1351 
1352   // Try to canonicalize the stored type.
1353   if (combineStoreToValueType(*this, SI))
1354     return eraseInstFromFunction(SI);
1355 
1356   // Attempt to improve the alignment.
1357   const Align KnownAlign = getOrEnforceKnownAlignment(
1358       Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);
1359   if (KnownAlign > SI.getAlign())
1360     SI.setAlignment(KnownAlign);
1361 
1362   // Try to canonicalize the stored type.
1363   if (unpackStoreToAggregate(*this, SI))
1364     return eraseInstFromFunction(SI);
1365 
1366   if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
1367     return eraseInstFromFunction(SI);
1368 
1369   // Replace GEP indices if possible.
1370   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1371       Worklist.push(NewGEPI);
1372       return &SI;
1373   }
1374 
1375   // Don't hack volatile/ordered stores.
1376   // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1377   if (!SI.isUnordered()) return nullptr;
1378 
1379   // If the RHS is an alloca with a single use, zapify the store, making the
1380   // alloca dead.
1381   if (Ptr->hasOneUse()) {
1382     if (isa<AllocaInst>(Ptr))
1383       return eraseInstFromFunction(SI);
1384     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1385       if (isa<AllocaInst>(GEP->getOperand(0))) {
1386         if (GEP->getOperand(0)->hasOneUse())
1387           return eraseInstFromFunction(SI);
1388       }
1389     }
1390   }
1391 
1392   // If we have a store to a location which is known constant, we can conclude
1393   // that the store must be storing the constant value (else the memory
1394   // wouldn't be constant), and this must be a noop.
1395   if (AA->pointsToConstantMemory(Ptr))
1396     return eraseInstFromFunction(SI);
1397 
1398   // Do really simple DSE, to catch cases where there are several consecutive
1399   // stores to the same location, separated by a few arithmetic operations. This
1400   // situation often occurs with bitfield accesses.
1401   BasicBlock::iterator BBI(SI);
1402   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1403        --ScanInsts) {
1404     --BBI;
1405     // Don't count debug info directives, lest they affect codegen,
1406     // and we skip pointer-to-pointer bitcasts, which are NOPs.
1407     if (BBI->isDebugOrPseudoInst() ||
1408         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1409       ScanInsts++;
1410       continue;
1411     }
1412 
1413     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1414       // Prev store isn't volatile, and stores to the same location?
1415       if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
1416                                                         SI.getOperand(1))) {
1417         ++NumDeadStore;
1418         // Manually add back the original store to the worklist now, so it will
1419         // be processed after the operands of the removed store, as this may
1420         // expose additional DSE opportunities.
1421         Worklist.push(&SI);
1422         eraseInstFromFunction(*PrevSI);
1423         return nullptr;
1424       }
1425       break;
1426     }
1427 
1428     // If this is a load, we have to stop.  However, if the loaded value is from
1429     // the pointer we're loading and is producing the pointer we're storing,
1430     // then *this* store is dead (X = load P; store X -> P).
1431     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1432       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1433         assert(SI.isUnordered() && "can't eliminate ordering operation");
1434         return eraseInstFromFunction(SI);
1435       }
1436 
1437       // Otherwise, this is a load from some other location.  Stores before it
1438       // may not be dead.
1439       break;
1440     }
1441 
1442     // Don't skip over loads, throws or things that can modify memory.
1443     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1444       break;
1445   }
1446 
1447   // store X, null    -> turns into 'unreachable' in SimplifyCFG
1448   // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1449   if (canSimplifyNullStoreOrGEP(SI)) {
1450     if (!isa<PoisonValue>(Val))
1451       return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
1452     return nullptr;  // Do not modify these!
1453   }
1454 
1455   // store undef, Ptr -> noop
1456   if (isa<UndefValue>(Val))
1457     return eraseInstFromFunction(SI);
1458 
1459   return nullptr;
1460 }
1461 
1462 /// Try to transform:
1463 ///   if () { *P = v1; } else { *P = v2 }
1464 /// or:
1465 ///   *P = v1; if () { *P = v2; }
1466 /// into a phi node with a store in the successor.
1467 bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) {
1468   if (!SI.isUnordered())
1469     return false; // This code has not been audited for volatile/ordered case.
1470 
1471   // Check if the successor block has exactly 2 incoming edges.
1472   BasicBlock *StoreBB = SI.getParent();
1473   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1474   if (!DestBB->hasNPredecessors(2))
1475     return false;
1476 
1477   // Capture the other block (the block that doesn't contain our store).
1478   pred_iterator PredIter = pred_begin(DestBB);
1479   if (*PredIter == StoreBB)
1480     ++PredIter;
1481   BasicBlock *OtherBB = *PredIter;
1482 
1483   // Bail out if all of the relevant blocks aren't distinct. This can happen,
1484   // for example, if SI is in an infinite loop.
1485   if (StoreBB == DestBB || OtherBB == DestBB)
1486     return false;
1487 
1488   // Verify that the other block ends in a branch and is not otherwise empty.
1489   BasicBlock::iterator BBI(OtherBB->getTerminator());
1490   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1491   if (!OtherBr || BBI == OtherBB->begin())
1492     return false;
1493 
1494   // If the other block ends in an unconditional branch, check for the 'if then
1495   // else' case. There is an instruction before the branch.
1496   StoreInst *OtherStore = nullptr;
1497   if (OtherBr->isUnconditional()) {
1498     --BBI;
1499     // Skip over debugging info.
1500     while (isa<DbgInfoIntrinsic>(BBI) ||
1501            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1502       if (BBI==OtherBB->begin())
1503         return false;
1504       --BBI;
1505     }
1506     // If this isn't a store, isn't a store to the same location, or is not the
1507     // right kind of store, bail out.
1508     OtherStore = dyn_cast<StoreInst>(BBI);
1509     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1510         !SI.isSameOperationAs(OtherStore))
1511       return false;
1512   } else {
1513     // Otherwise, the other block ended with a conditional branch. If one of the
1514     // destinations is StoreBB, then we have the if/then case.
1515     if (OtherBr->getSuccessor(0) != StoreBB &&
1516         OtherBr->getSuccessor(1) != StoreBB)
1517       return false;
1518 
1519     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1520     // if/then triangle. See if there is a store to the same ptr as SI that
1521     // lives in OtherBB.
1522     for (;; --BBI) {
1523       // Check to see if we find the matching store.
1524       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1525         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1526             !SI.isSameOperationAs(OtherStore))
1527           return false;
1528         break;
1529       }
1530       // If we find something that may be using or overwriting the stored
1531       // value, or if we run out of instructions, we can't do the transform.
1532       if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1533           BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1534         return false;
1535     }
1536 
1537     // In order to eliminate the store in OtherBr, we have to make sure nothing
1538     // reads or overwrites the stored value in StoreBB.
1539     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1540       // FIXME: This should really be AA driven.
1541       if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1542         return false;
1543     }
1544   }
1545 
1546   // Insert a PHI node now if we need it.
1547   Value *MergedVal = OtherStore->getOperand(0);
1548   // The debug locations of the original instructions might differ. Merge them.
1549   DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1550                                                      OtherStore->getDebugLoc());
1551   if (MergedVal != SI.getOperand(0)) {
1552     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1553     PN->addIncoming(SI.getOperand(0), SI.getParent());
1554     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1555     MergedVal = InsertNewInstBefore(PN, DestBB->front());
1556     PN->setDebugLoc(MergedLoc);
1557   }
1558 
1559   // Advance to a place where it is safe to insert the new store and insert it.
1560   BBI = DestBB->getFirstInsertionPt();
1561   StoreInst *NewSI =
1562       new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),
1563                     SI.getOrdering(), SI.getSyncScopeID());
1564   InsertNewInstBefore(NewSI, *BBI);
1565   NewSI->setDebugLoc(MergedLoc);
1566 
1567   // If the two stores had AA tags, merge them.
1568   AAMDNodes AATags;
1569   SI.getAAMetadata(AATags);
1570   if (AATags) {
1571     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1572     NewSI->setAAMetadata(AATags);
1573   }
1574 
1575   // Nuke the old stores.
1576   eraseInstFromFunction(SI);
1577   eraseInstFromFunction(*OtherStore);
1578   return true;
1579 }
1580