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