instcombine: alloca: Split out simplifyAllocaArraySize(), NFC
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineLoadStoreAlloca.cpp
1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visit functions for load, store and alloca.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/MDBuilder.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 using namespace llvm;
24
25 #define DEBUG_TYPE "instcombine"
26
27 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
28 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
29
30 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
31 /// some part of a constant global variable.  This intentionally only accepts
32 /// constant expressions because we can't rewrite arbitrary instructions.
33 static bool pointsToConstantGlobal(Value *V) {
34   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
35     return GV->isConstant();
36
37   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
38     if (CE->getOpcode() == Instruction::BitCast ||
39         CE->getOpcode() == Instruction::AddrSpaceCast ||
40         CE->getOpcode() == Instruction::GetElementPtr)
41       return pointsToConstantGlobal(CE->getOperand(0));
42   }
43   return false;
44 }
45
46 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
47 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
48 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
49 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
50 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
51 /// the alloca, and if the source pointer is a pointer to a constant global, we
52 /// can optimize this.
53 static bool
54 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
55                                SmallVectorImpl<Instruction *> &ToDelete) {
56   // We track lifetime intrinsics as we encounter them.  If we decide to go
57   // ahead and replace the value with the global, this lets the caller quickly
58   // eliminate the markers.
59
60   SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
61   ValuesToInspect.push_back(std::make_pair(V, false));
62   while (!ValuesToInspect.empty()) {
63     auto ValuePair = ValuesToInspect.pop_back_val();
64     const bool IsOffset = ValuePair.second;
65     for (auto &U : ValuePair.first->uses()) {
66       Instruction *I = cast<Instruction>(U.getUser());
67
68       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
69         // Ignore non-volatile loads, they are always ok.
70         if (!LI->isSimple()) return false;
71         continue;
72       }
73
74       if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
75         // If uses of the bitcast are ok, we are ok.
76         ValuesToInspect.push_back(std::make_pair(I, IsOffset));
77         continue;
78       }
79       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
80         // If the GEP has all zero indices, it doesn't offset the pointer. If it
81         // doesn't, it does.
82         ValuesToInspect.push_back(
83             std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
84         continue;
85       }
86
87       if (CallSite CS = I) {
88         // If this is the function being called then we treat it like a load and
89         // ignore it.
90         if (CS.isCallee(&U))
91           continue;
92
93         // Inalloca arguments are clobbered by the call.
94         unsigned ArgNo = CS.getArgumentNo(&U);
95         if (CS.isInAllocaArgument(ArgNo))
96           return false;
97
98         // If this is a readonly/readnone call site, then we know it is just a
99         // load (but one that potentially returns the value itself), so we can
100         // ignore it if we know that the value isn't captured.
101         if (CS.onlyReadsMemory() &&
102             (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
103           continue;
104
105         // If this is being passed as a byval argument, the caller is making a
106         // copy, so it is only a read of the alloca.
107         if (CS.isByValArgument(ArgNo))
108           continue;
109       }
110
111       // Lifetime intrinsics can be handled by the caller.
112       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
113         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
114             II->getIntrinsicID() == Intrinsic::lifetime_end) {
115           assert(II->use_empty() && "Lifetime markers have no result to use!");
116           ToDelete.push_back(II);
117           continue;
118         }
119       }
120
121       // If this is isn't our memcpy/memmove, reject it as something we can't
122       // handle.
123       MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
124       if (!MI)
125         return false;
126
127       // If the transfer is using the alloca as a source of the transfer, then
128       // ignore it since it is a load (unless the transfer is volatile).
129       if (U.getOperandNo() == 1) {
130         if (MI->isVolatile()) return false;
131         continue;
132       }
133
134       // If we already have seen a copy, reject the second one.
135       if (TheCopy) return false;
136
137       // If the pointer has been offset from the start of the alloca, we can't
138       // safely handle this.
139       if (IsOffset) return false;
140
141       // If the memintrinsic isn't using the alloca as the dest, reject it.
142       if (U.getOperandNo() != 0) return false;
143
144       // If the source of the memcpy/move is not a constant global, reject it.
145       if (!pointsToConstantGlobal(MI->getSource()))
146         return false;
147
148       // Otherwise, the transform is safe.  Remember the copy instruction.
149       TheCopy = MI;
150     }
151   }
152   return true;
153 }
154
155 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
156 /// modified by a copy from a constant global.  If we can prove this, we can
157 /// replace any uses of the alloca with uses of the global directly.
158 static MemTransferInst *
159 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
160                                SmallVectorImpl<Instruction *> &ToDelete) {
161   MemTransferInst *TheCopy = nullptr;
162   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
163     return TheCopy;
164   return nullptr;
165 }
166
167 static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
168   // Ensure that the alloca array size argument has type intptr_t, so that
169   // any casting is exposed early.
170   Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
171   if (AI.getArraySize()->getType() != IntPtrTy) {
172     Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
173     AI.setOperand(0, V);
174     return &AI;
175   }
176
177   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
178   if (AI.isArrayAllocation()) {  // Check C != 1
179     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
180       Type *NewTy =
181         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
182       AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
183       New->setAlignment(AI.getAlignment());
184
185       // Scan to the end of the allocation instructions, to skip over a block of
186       // allocas if possible...also skip interleaved debug info
187       //
188       BasicBlock::iterator It = New;
189       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
190
191       // Now that I is pointing to the first non-allocation-inst in the block,
192       // insert our getelementptr instruction...
193       //
194       Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
195       Value *NullIdx = Constant::getNullValue(IdxTy);
196       Value *Idx[2] = { NullIdx, NullIdx };
197       Instruction *GEP =
198         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
199       IC.InsertNewInstBefore(GEP, *It);
200
201       // Now make everything use the getelementptr instead of the original
202       // allocation.
203       return IC.ReplaceInstUsesWith(AI, GEP);
204     } else if (isa<UndefValue>(AI.getArraySize())) {
205       return IC.ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
206     }
207   }
208
209   return nullptr;
210 }
211
212 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
213   if (auto *I = simplifyAllocaArraySize(*this, AI))
214     return I;
215
216   if (AI.getAllocatedType()->isSized()) {
217     // If the alignment is 0 (unspecified), assign it the preferred alignment.
218     if (AI.getAlignment() == 0)
219       AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
220
221     // Move all alloca's of zero byte objects to the entry block and merge them
222     // together.  Note that we only do this for alloca's, because malloc should
223     // allocate and return a unique pointer, even for a zero byte allocation.
224     if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
225       // For a zero sized alloca there is no point in doing an array allocation.
226       // This is helpful if the array size is a complicated expression not used
227       // elsewhere.
228       if (AI.isArrayAllocation()) {
229         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
230         return &AI;
231       }
232
233       // Get the first instruction in the entry block.
234       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
235       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
236       if (FirstInst != &AI) {
237         // If the entry block doesn't start with a zero-size alloca then move
238         // this one to the start of the entry block.  There is no problem with
239         // dominance as the array size was forced to a constant earlier already.
240         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
241         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
242             DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
243           AI.moveBefore(FirstInst);
244           return &AI;
245         }
246
247         // If the alignment of the entry block alloca is 0 (unspecified),
248         // assign it the preferred alignment.
249         if (EntryAI->getAlignment() == 0)
250           EntryAI->setAlignment(
251               DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
252         // Replace this zero-sized alloca with the one at the start of the entry
253         // block after ensuring that the address will be aligned enough for both
254         // types.
255         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
256                                      AI.getAlignment());
257         EntryAI->setAlignment(MaxAlign);
258         if (AI.getType() != EntryAI->getType())
259           return new BitCastInst(EntryAI, AI.getType());
260         return ReplaceInstUsesWith(AI, EntryAI);
261       }
262     }
263   }
264
265   if (AI.getAlignment()) {
266     // Check to see if this allocation is only modified by a memcpy/memmove from
267     // a constant global whose alignment is equal to or exceeds that of the
268     // allocation.  If this is the case, we can change all users to use
269     // the constant global instead.  This is commonly produced by the CFE by
270     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
271     // is only subsequently read.
272     SmallVector<Instruction *, 4> ToDelete;
273     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
274       unsigned SourceAlign = getOrEnforceKnownAlignment(
275           Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
276       if (AI.getAlignment() <= SourceAlign) {
277         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
278         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
279         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
280           EraseInstFromFunction(*ToDelete[i]);
281         Constant *TheSrc = cast<Constant>(Copy->getSource());
282         Constant *Cast
283           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
284         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
285         EraseInstFromFunction(*Copy);
286         ++NumGlobalCopies;
287         return NewI;
288       }
289     }
290   }
291
292   // At last, use the generic allocation site handler to aggressively remove
293   // unused allocas.
294   return visitAllocSite(AI);
295 }
296
297 /// \brief Helper to combine a load to a new type.
298 ///
299 /// This just does the work of combining a load to a new type. It handles
300 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
301 /// loaded *value* type. This will convert it to a pointer, cast the operand to
302 /// that pointer type, load it, etc.
303 ///
304 /// Note that this will create all of the instructions with whatever insert
305 /// point the \c InstCombiner currently is using.
306 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
307   Value *Ptr = LI.getPointerOperand();
308   unsigned AS = LI.getPointerAddressSpace();
309   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
310   LI.getAllMetadata(MD);
311
312   LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
313       IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
314       LI.getAlignment(), LI.getName());
315   MDBuilder MDB(NewLoad->getContext());
316   for (const auto &MDPair : MD) {
317     unsigned ID = MDPair.first;
318     MDNode *N = MDPair.second;
319     // Note, essentially every kind of metadata should be preserved here! This
320     // routine is supposed to clone a load instruction changing *only its type*.
321     // The only metadata it makes sense to drop is metadata which is invalidated
322     // when the pointer type changes. This should essentially never be the case
323     // in LLVM, but we explicitly switch over only known metadata to be
324     // conservatively correct. If you are adding metadata to LLVM which pertains
325     // to loads, you almost certainly want to add it here.
326     switch (ID) {
327     case LLVMContext::MD_dbg:
328     case LLVMContext::MD_tbaa:
329     case LLVMContext::MD_prof:
330     case LLVMContext::MD_fpmath:
331     case LLVMContext::MD_tbaa_struct:
332     case LLVMContext::MD_invariant_load:
333     case LLVMContext::MD_alias_scope:
334     case LLVMContext::MD_noalias:
335     case LLVMContext::MD_nontemporal:
336     case LLVMContext::MD_mem_parallel_loop_access:
337       // All of these directly apply.
338       NewLoad->setMetadata(ID, N);
339       break;
340
341     case LLVMContext::MD_nonnull:
342       // This only directly applies if the new type is also a pointer.
343       if (NewTy->isPointerTy()) {
344         NewLoad->setMetadata(ID, N);
345         break;
346       }
347       // If it's integral now, translate it to !range metadata.
348       if (NewTy->isIntegerTy()) {
349         auto *ITy = cast<IntegerType>(NewTy);
350         auto *NullInt = ConstantExpr::getPtrToInt(
351             ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
352         auto *NonNullInt =
353             ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
354         NewLoad->setMetadata(LLVMContext::MD_range,
355                              MDB.createRange(NonNullInt, NullInt));
356       }
357       break;
358
359     case LLVMContext::MD_range:
360       // FIXME: It would be nice to propagate this in some way, but the type
361       // conversions make it hard. If the new type is a pointer, we could
362       // translate it to !nonnull metadata.
363       break;
364     }
365   }
366   return NewLoad;
367 }
368
369 /// \brief Combine a store to a new type.
370 ///
371 /// Returns the newly created store instruction.
372 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
373   Value *Ptr = SI.getPointerOperand();
374   unsigned AS = SI.getPointerAddressSpace();
375   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
376   SI.getAllMetadata(MD);
377
378   StoreInst *NewStore = IC.Builder->CreateAlignedStore(
379       V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
380       SI.getAlignment());
381   for (const auto &MDPair : MD) {
382     unsigned ID = MDPair.first;
383     MDNode *N = MDPair.second;
384     // Note, essentially every kind of metadata should be preserved here! This
385     // routine is supposed to clone a store instruction changing *only its
386     // type*. The only metadata it makes sense to drop is metadata which is
387     // invalidated when the pointer type changes. This should essentially
388     // never be the case in LLVM, but we explicitly switch over only known
389     // metadata to be conservatively correct. If you are adding metadata to
390     // LLVM which pertains to stores, you almost certainly want to add it
391     // here.
392     switch (ID) {
393     case LLVMContext::MD_dbg:
394     case LLVMContext::MD_tbaa:
395     case LLVMContext::MD_prof:
396     case LLVMContext::MD_fpmath:
397     case LLVMContext::MD_tbaa_struct:
398     case LLVMContext::MD_alias_scope:
399     case LLVMContext::MD_noalias:
400     case LLVMContext::MD_nontemporal:
401     case LLVMContext::MD_mem_parallel_loop_access:
402       // All of these directly apply.
403       NewStore->setMetadata(ID, N);
404       break;
405
406     case LLVMContext::MD_invariant_load:
407     case LLVMContext::MD_nonnull:
408     case LLVMContext::MD_range:
409       // These don't apply for stores.
410       break;
411     }
412   }
413
414   return NewStore;
415 }
416
417 /// \brief Combine loads to match the type of value their uses after looking
418 /// through intervening bitcasts.
419 ///
420 /// The core idea here is that if the result of a load is used in an operation,
421 /// we should load the type most conducive to that operation. For example, when
422 /// loading an integer and converting that immediately to a pointer, we should
423 /// instead directly load a pointer.
424 ///
425 /// However, this routine must never change the width of a load or the number of
426 /// loads as that would introduce a semantic change. This combine is expected to
427 /// be a semantic no-op which just allows loads to more closely model the types
428 /// of their consuming operations.
429 ///
430 /// Currently, we also refuse to change the precise type used for an atomic load
431 /// or a volatile load. This is debatable, and might be reasonable to change
432 /// later. However, it is risky in case some backend or other part of LLVM is
433 /// relying on the exact type loaded to select appropriate atomic operations.
434 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
435   // FIXME: We could probably with some care handle both volatile and atomic
436   // loads here but it isn't clear that this is important.
437   if (!LI.isSimple())
438     return nullptr;
439
440   if (LI.use_empty())
441     return nullptr;
442
443   Type *Ty = LI.getType();
444   const DataLayout &DL = IC.getDataLayout();
445
446   // Try to canonicalize loads which are only ever stored to operate over
447   // integers instead of any other type. We only do this when the loaded type
448   // is sized and has a size exactly the same as its store size and the store
449   // size is a legal integer type.
450   if (!Ty->isIntegerTy() && Ty->isSized() &&
451       DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
452       DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
453     if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
454           auto *SI = dyn_cast<StoreInst>(U);
455           return SI && SI->getPointerOperand() != &LI;
456         })) {
457       LoadInst *NewLoad = combineLoadToNewType(
458           IC, LI,
459           Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
460       // Replace all the stores with stores of the newly loaded value.
461       for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
462         auto *SI = cast<StoreInst>(*UI++);
463         IC.Builder->SetInsertPoint(SI);
464         combineStoreToNewValue(IC, *SI, NewLoad);
465         IC.EraseInstFromFunction(*SI);
466       }
467       assert(LI.use_empty() && "Failed to remove all users of the load!");
468       // Return the old load so the combiner can delete it safely.
469       return &LI;
470     }
471   }
472
473   // Fold away bit casts of the loaded value by loading the desired type.
474   if (LI.hasOneUse())
475     if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
476       LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
477       BC->replaceAllUsesWith(NewLoad);
478       IC.EraseInstFromFunction(*BC);
479       return &LI;
480     }
481
482   // FIXME: We should also canonicalize loads of vectors when their elements are
483   // cast to other types.
484   return nullptr;
485 }
486
487 // If we can determine that all possible objects pointed to by the provided
488 // pointer value are, not only dereferenceable, but also definitively less than
489 // or equal to the provided maximum size, then return true. Otherwise, return
490 // false (constant global values and allocas fall into this category).
491 //
492 // FIXME: This should probably live in ValueTracking (or similar).
493 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
494                                      const DataLayout &DL) {
495   SmallPtrSet<Value *, 4> Visited;
496   SmallVector<Value *, 4> Worklist(1, V);
497
498   do {
499     Value *P = Worklist.pop_back_val();
500     P = P->stripPointerCasts();
501
502     if (!Visited.insert(P).second)
503       continue;
504
505     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
506       Worklist.push_back(SI->getTrueValue());
507       Worklist.push_back(SI->getFalseValue());
508       continue;
509     }
510
511     if (PHINode *PN = dyn_cast<PHINode>(P)) {
512       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
513         Worklist.push_back(PN->getIncomingValue(i));
514       continue;
515     }
516
517     if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
518       if (GA->mayBeOverridden())
519         return false;
520       Worklist.push_back(GA->getAliasee());
521       continue;
522     }
523
524     // If we know how big this object is, and it is less than MaxSize, continue
525     // searching. Otherwise, return false.
526     if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
527       if (!AI->getAllocatedType()->isSized())
528         return false;
529
530       ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
531       if (!CS)
532         return false;
533
534       uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
535       // Make sure that, even if the multiplication below would wrap as an
536       // uint64_t, we still do the right thing.
537       if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
538         return false;
539       continue;
540     }
541
542     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
543       if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
544         return false;
545
546       uint64_t InitSize = DL.getTypeAllocSize(GV->getType()->getElementType());
547       if (InitSize > MaxSize)
548         return false;
549       continue;
550     }
551
552     return false;
553   } while (!Worklist.empty());
554
555   return true;
556 }
557
558 // If we're indexing into an object of a known size, and the outer index is
559 // not a constant, but having any value but zero would lead to undefined
560 // behavior, replace it with zero.
561 //
562 // For example, if we have:
563 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
564 // ...
565 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
566 // ... = load i32* %arrayidx, align 4
567 // Then we know that we can replace %x in the GEP with i64 0.
568 //
569 // FIXME: We could fold any GEP index to zero that would cause UB if it were
570 // not zero. Currently, we only handle the first such index. Also, we could
571 // also search through non-zero constant indices if we kept track of the
572 // offsets those indices implied.
573 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
574                                      Instruction *MemI, unsigned &Idx) {
575   if (GEPI->getNumOperands() < 2)
576     return false;
577
578   // Find the first non-zero index of a GEP. If all indices are zero, return
579   // one past the last index.
580   auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
581     unsigned I = 1;
582     for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
583       Value *V = GEPI->getOperand(I);
584       if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
585         if (CI->isZero())
586           continue;
587
588       break;
589     }
590
591     return I;
592   };
593
594   // Skip through initial 'zero' indices, and find the corresponding pointer
595   // type. See if the next index is not a constant.
596   Idx = FirstNZIdx(GEPI);
597   if (Idx == GEPI->getNumOperands())
598     return false;
599   if (isa<Constant>(GEPI->getOperand(Idx)))
600     return false;
601
602   SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
603   Type *AllocTy =
604     GetElementPtrInst::getIndexedType(GEPI->getOperand(0)->getType(), Ops);
605   if (!AllocTy || !AllocTy->isSized())
606     return false;
607   const DataLayout &DL = IC.getDataLayout();
608   uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
609
610   // If there are more indices after the one we might replace with a zero, make
611   // sure they're all non-negative. If any of them are negative, the overall
612   // address being computed might be before the base address determined by the
613   // first non-zero index.
614   auto IsAllNonNegative = [&]() {
615     for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
616       bool KnownNonNegative, KnownNegative;
617       IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
618                         KnownNegative, 0, MemI);
619       if (KnownNonNegative)
620         continue;
621       return false;
622     }
623
624     return true;
625   };
626
627   // FIXME: If the GEP is not inbounds, and there are extra indices after the
628   // one we'll replace, those could cause the address computation to wrap
629   // (rendering the IsAllNonNegative() check below insufficient). We can do
630   // better, ignoring zero indicies (and other indicies we can prove small
631   // enough not to wrap).
632   if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
633     return false;
634
635   // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
636   // also known to be dereferenceable.
637   return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
638          IsAllNonNegative();
639 }
640
641 // If we're indexing into an object with a variable index for the memory
642 // access, but the object has only one element, we can assume that the index
643 // will always be zero. If we replace the GEP, return it.
644 template <typename T>
645 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
646                                           T &MemI) {
647   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
648     unsigned Idx;
649     if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
650       Instruction *NewGEPI = GEPI->clone();
651       NewGEPI->setOperand(Idx,
652         ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
653       NewGEPI->insertBefore(GEPI);
654       MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
655       return NewGEPI;
656     }
657   }
658
659   return nullptr;
660 }
661
662 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
663   Value *Op = LI.getOperand(0);
664
665   // Try to canonicalize the loaded type.
666   if (Instruction *Res = combineLoadToOperationType(*this, LI))
667     return Res;
668
669   // Attempt to improve the alignment.
670   unsigned KnownAlign = getOrEnforceKnownAlignment(
671       Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
672   unsigned LoadAlign = LI.getAlignment();
673   unsigned EffectiveLoadAlign =
674       LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
675
676   if (KnownAlign > EffectiveLoadAlign)
677     LI.setAlignment(KnownAlign);
678   else if (LoadAlign == 0)
679     LI.setAlignment(EffectiveLoadAlign);
680
681   // Replace GEP indices if possible.
682   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
683       Worklist.Add(NewGEPI);
684       return &LI;
685   }
686
687   // None of the following transforms are legal for volatile/atomic loads.
688   // FIXME: Some of it is okay for atomic loads; needs refactoring.
689   if (!LI.isSimple()) return nullptr;
690
691   // Do really simple store-to-load forwarding and load CSE, to catch cases
692   // where there are several consecutive memory accesses to the same location,
693   // separated by a few arithmetic operations.
694   BasicBlock::iterator BBI = &LI;
695   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
696     return ReplaceInstUsesWith(
697         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
698                                             LI.getName() + ".cast"));
699
700   // load(gep null, ...) -> unreachable
701   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
702     const Value *GEPI0 = GEPI->getOperand(0);
703     // TODO: Consider a target hook for valid address spaces for this xform.
704     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
705       // Insert a new store to null instruction before the load to indicate
706       // that this code is not reachable.  We do this instead of inserting
707       // an unreachable instruction directly because we cannot modify the
708       // CFG.
709       new StoreInst(UndefValue::get(LI.getType()),
710                     Constant::getNullValue(Op->getType()), &LI);
711       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
712     }
713   }
714
715   // load null/undef -> unreachable
716   // TODO: Consider a target hook for valid address spaces for this xform.
717   if (isa<UndefValue>(Op) ||
718       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
719     // Insert a new store to null instruction before the load to indicate that
720     // this code is not reachable.  We do this instead of inserting an
721     // unreachable instruction directly because we cannot modify the CFG.
722     new StoreInst(UndefValue::get(LI.getType()),
723                   Constant::getNullValue(Op->getType()), &LI);
724     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
725   }
726
727   if (Op->hasOneUse()) {
728     // Change select and PHI nodes to select values instead of addresses: this
729     // helps alias analysis out a lot, allows many others simplifications, and
730     // exposes redundancy in the code.
731     //
732     // Note that we cannot do the transformation unless we know that the
733     // introduced loads cannot trap!  Something like this is valid as long as
734     // the condition is always false: load (select bool %C, int* null, int* %G),
735     // but it would not be valid if we transformed it to load from null
736     // unconditionally.
737     //
738     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
739       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
740       unsigned Align = LI.getAlignment();
741       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align) &&
742           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align)) {
743         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
744                                            SI->getOperand(1)->getName()+".val");
745         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
746                                            SI->getOperand(2)->getName()+".val");
747         V1->setAlignment(Align);
748         V2->setAlignment(Align);
749         return SelectInst::Create(SI->getCondition(), V1, V2);
750       }
751
752       // load (select (cond, null, P)) -> load P
753       if (isa<ConstantPointerNull>(SI->getOperand(1)) && 
754           LI.getPointerAddressSpace() == 0) {
755         LI.setOperand(0, SI->getOperand(2));
756         return &LI;
757       }
758
759       // load (select (cond, P, null)) -> load P
760       if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
761           LI.getPointerAddressSpace() == 0) {
762         LI.setOperand(0, SI->getOperand(1));
763         return &LI;
764       }
765     }
766   }
767   return nullptr;
768 }
769
770 /// \brief Combine stores to match the type of value being stored.
771 ///
772 /// The core idea here is that the memory does not have any intrinsic type and
773 /// where we can we should match the type of a store to the type of value being
774 /// stored.
775 ///
776 /// However, this routine must never change the width of a store or the number of
777 /// stores as that would introduce a semantic change. This combine is expected to
778 /// be a semantic no-op which just allows stores to more closely model the types
779 /// of their incoming values.
780 ///
781 /// Currently, we also refuse to change the precise type used for an atomic or
782 /// volatile store. This is debatable, and might be reasonable to change later.
783 /// However, it is risky in case some backend or other part of LLVM is relying
784 /// on the exact type stored to select appropriate atomic operations.
785 ///
786 /// \returns true if the store was successfully combined away. This indicates
787 /// the caller must erase the store instruction. We have to let the caller erase
788 /// the store instruction sas otherwise there is no way to signal whether it was
789 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
790 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
791   // FIXME: We could probably with some care handle both volatile and atomic
792   // stores here but it isn't clear that this is important.
793   if (!SI.isSimple())
794     return false;
795
796   Value *V = SI.getValueOperand();
797
798   // Fold away bit casts of the stored value by storing the original type.
799   if (auto *BC = dyn_cast<BitCastInst>(V)) {
800     V = BC->getOperand(0);
801     combineStoreToNewValue(IC, SI, V);
802     return true;
803   }
804
805   // FIXME: We should also canonicalize loads of vectors when their elements are
806   // cast to other types.
807   return false;
808 }
809
810 /// equivalentAddressValues - Test if A and B will obviously have the same
811 /// value. This includes recognizing that %t0 and %t1 will have the same
812 /// value in code like this:
813 ///   %t0 = getelementptr \@a, 0, 3
814 ///   store i32 0, i32* %t0
815 ///   %t1 = getelementptr \@a, 0, 3
816 ///   %t2 = load i32* %t1
817 ///
818 static bool equivalentAddressValues(Value *A, Value *B) {
819   // Test if the values are trivially equivalent.
820   if (A == B) return true;
821
822   // Test if the values come form identical arithmetic instructions.
823   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
824   // its only used to compare two uses within the same basic block, which
825   // means that they'll always either have the same value or one of them
826   // will have an undefined value.
827   if (isa<BinaryOperator>(A) ||
828       isa<CastInst>(A) ||
829       isa<PHINode>(A) ||
830       isa<GetElementPtrInst>(A))
831     if (Instruction *BI = dyn_cast<Instruction>(B))
832       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
833         return true;
834
835   // Otherwise they may not be equivalent.
836   return false;
837 }
838
839 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
840   Value *Val = SI.getOperand(0);
841   Value *Ptr = SI.getOperand(1);
842
843   // Try to canonicalize the stored type.
844   if (combineStoreToValueType(*this, SI))
845     return EraseInstFromFunction(SI);
846
847   // Attempt to improve the alignment.
848   unsigned KnownAlign = getOrEnforceKnownAlignment(
849       Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
850   unsigned StoreAlign = SI.getAlignment();
851   unsigned EffectiveStoreAlign =
852       StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
853
854   if (KnownAlign > EffectiveStoreAlign)
855     SI.setAlignment(KnownAlign);
856   else if (StoreAlign == 0)
857     SI.setAlignment(EffectiveStoreAlign);
858
859   // Replace GEP indices if possible.
860   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
861       Worklist.Add(NewGEPI);
862       return &SI;
863   }
864
865   // Don't hack volatile/atomic stores.
866   // FIXME: Some bits are legal for atomic stores; needs refactoring.
867   if (!SI.isSimple()) return nullptr;
868
869   // If the RHS is an alloca with a single use, zapify the store, making the
870   // alloca dead.
871   if (Ptr->hasOneUse()) {
872     if (isa<AllocaInst>(Ptr))
873       return EraseInstFromFunction(SI);
874     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
875       if (isa<AllocaInst>(GEP->getOperand(0))) {
876         if (GEP->getOperand(0)->hasOneUse())
877           return EraseInstFromFunction(SI);
878       }
879     }
880   }
881
882   // Do really simple DSE, to catch cases where there are several consecutive
883   // stores to the same location, separated by a few arithmetic operations. This
884   // situation often occurs with bitfield accesses.
885   BasicBlock::iterator BBI = &SI;
886   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
887        --ScanInsts) {
888     --BBI;
889     // Don't count debug info directives, lest they affect codegen,
890     // and we skip pointer-to-pointer bitcasts, which are NOPs.
891     if (isa<DbgInfoIntrinsic>(BBI) ||
892         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
893       ScanInsts++;
894       continue;
895     }
896
897     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
898       // Prev store isn't volatile, and stores to the same location?
899       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
900                                                         SI.getOperand(1))) {
901         ++NumDeadStore;
902         ++BBI;
903         EraseInstFromFunction(*PrevSI);
904         continue;
905       }
906       break;
907     }
908
909     // If this is a load, we have to stop.  However, if the loaded value is from
910     // the pointer we're loading and is producing the pointer we're storing,
911     // then *this* store is dead (X = load P; store X -> P).
912     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
913       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
914           LI->isSimple())
915         return EraseInstFromFunction(SI);
916
917       // Otherwise, this is a load from some other location.  Stores before it
918       // may not be dead.
919       break;
920     }
921
922     // Don't skip over loads or things that can modify memory.
923     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
924       break;
925   }
926
927   // store X, null    -> turns into 'unreachable' in SimplifyCFG
928   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
929     if (!isa<UndefValue>(Val)) {
930       SI.setOperand(0, UndefValue::get(Val->getType()));
931       if (Instruction *U = dyn_cast<Instruction>(Val))
932         Worklist.Add(U);  // Dropped a use.
933     }
934     return nullptr;  // Do not modify these!
935   }
936
937   // store undef, Ptr -> noop
938   if (isa<UndefValue>(Val))
939     return EraseInstFromFunction(SI);
940
941   // If this store is the last instruction in the basic block (possibly
942   // excepting debug info instructions), and if the block ends with an
943   // unconditional branch, try to move it to the successor block.
944   BBI = &SI;
945   do {
946     ++BBI;
947   } while (isa<DbgInfoIntrinsic>(BBI) ||
948            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
949   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
950     if (BI->isUnconditional())
951       if (SimplifyStoreAtEndOfBlock(SI))
952         return nullptr;  // xform done!
953
954   return nullptr;
955 }
956
957 /// SimplifyStoreAtEndOfBlock - Turn things like:
958 ///   if () { *P = v1; } else { *P = v2 }
959 /// into a phi node with a store in the successor.
960 ///
961 /// Simplify things like:
962 ///   *P = v1; if () { *P = v2; }
963 /// into a phi node with a store in the successor.
964 ///
965 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
966   BasicBlock *StoreBB = SI.getParent();
967
968   // Check to see if the successor block has exactly two incoming edges.  If
969   // so, see if the other predecessor contains a store to the same location.
970   // if so, insert a PHI node (if needed) and move the stores down.
971   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
972
973   // Determine whether Dest has exactly two predecessors and, if so, compute
974   // the other predecessor.
975   pred_iterator PI = pred_begin(DestBB);
976   BasicBlock *P = *PI;
977   BasicBlock *OtherBB = nullptr;
978
979   if (P != StoreBB)
980     OtherBB = P;
981
982   if (++PI == pred_end(DestBB))
983     return false;
984
985   P = *PI;
986   if (P != StoreBB) {
987     if (OtherBB)
988       return false;
989     OtherBB = P;
990   }
991   if (++PI != pred_end(DestBB))
992     return false;
993
994   // Bail out if all the relevant blocks aren't distinct (this can happen,
995   // for example, if SI is in an infinite loop)
996   if (StoreBB == DestBB || OtherBB == DestBB)
997     return false;
998
999   // Verify that the other block ends in a branch and is not otherwise empty.
1000   BasicBlock::iterator BBI = OtherBB->getTerminator();
1001   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1002   if (!OtherBr || BBI == OtherBB->begin())
1003     return false;
1004
1005   // If the other block ends in an unconditional branch, check for the 'if then
1006   // else' case.  there is an instruction before the branch.
1007   StoreInst *OtherStore = nullptr;
1008   if (OtherBr->isUnconditional()) {
1009     --BBI;
1010     // Skip over debugging info.
1011     while (isa<DbgInfoIntrinsic>(BBI) ||
1012            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1013       if (BBI==OtherBB->begin())
1014         return false;
1015       --BBI;
1016     }
1017     // If this isn't a store, isn't a store to the same location, or is not the
1018     // right kind of store, bail out.
1019     OtherStore = dyn_cast<StoreInst>(BBI);
1020     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1021         !SI.isSameOperationAs(OtherStore))
1022       return false;
1023   } else {
1024     // Otherwise, the other block ended with a conditional branch. If one of the
1025     // destinations is StoreBB, then we have the if/then case.
1026     if (OtherBr->getSuccessor(0) != StoreBB &&
1027         OtherBr->getSuccessor(1) != StoreBB)
1028       return false;
1029
1030     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1031     // if/then triangle.  See if there is a store to the same ptr as SI that
1032     // lives in OtherBB.
1033     for (;; --BBI) {
1034       // Check to see if we find the matching store.
1035       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1036         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1037             !SI.isSameOperationAs(OtherStore))
1038           return false;
1039         break;
1040       }
1041       // If we find something that may be using or overwriting the stored
1042       // value, or if we run out of instructions, we can't do the xform.
1043       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1044           BBI == OtherBB->begin())
1045         return false;
1046     }
1047
1048     // In order to eliminate the store in OtherBr, we have to
1049     // make sure nothing reads or overwrites the stored value in
1050     // StoreBB.
1051     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1052       // FIXME: This should really be AA driven.
1053       if (I->mayReadFromMemory() || I->mayWriteToMemory())
1054         return false;
1055     }
1056   }
1057
1058   // Insert a PHI node now if we need it.
1059   Value *MergedVal = OtherStore->getOperand(0);
1060   if (MergedVal != SI.getOperand(0)) {
1061     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1062     PN->addIncoming(SI.getOperand(0), SI.getParent());
1063     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1064     MergedVal = InsertNewInstBefore(PN, DestBB->front());
1065   }
1066
1067   // Advance to a place where it is safe to insert the new store and
1068   // insert it.
1069   BBI = DestBB->getFirstInsertionPt();
1070   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
1071                                    SI.isVolatile(),
1072                                    SI.getAlignment(),
1073                                    SI.getOrdering(),
1074                                    SI.getSynchScope());
1075   InsertNewInstBefore(NewSI, *BBI);
1076   NewSI->setDebugLoc(OtherStore->getDebugLoc());
1077
1078   // If the two stores had AA tags, merge them.
1079   AAMDNodes AATags;
1080   SI.getAAMetadata(AATags);
1081   if (AATags) {
1082     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1083     NewSI->setAAMetadata(AATags);
1084   }
1085
1086   // Nuke the old stores.
1087   EraseInstFromFunction(SI);
1088   EraseInstFromFunction(*OtherStore);
1089   return true;
1090 }