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