LLVM 24.0.0git
InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
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"
15#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/Loads.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/LLVMContext.h"
27using namespace llvm;
28using namespace PatternMatch;
29
30#define DEBUG_TYPE "instcombine"
31
32STATISTIC(NumDeadStore, "Number of dead stores eliminated");
33STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
34
35/// isOnlyCopiedFromConstantMemory - 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 memory
41/// location, we can optimize this.
44 SmallVectorImpl<Instruction *> &ToDelete, unsigned MaxUsers) {
45 // We track lifetime intrinsics as we encounter them. If we decide to go
46 // ahead and replace the value with the memory location, this lets the caller
47 // quickly eliminate the markers.
48
49 using ValueAndIsOffset = PointerIntPair<Value *, 1, bool>;
51 // Check the limit as soon as a value is added, rather than when it is
52 // visited. Otherwise an alloca with many GEP users has all of them scanned
53 // on every visit, which makes repeated visits of the alloca quadratic.
54 auto Push = [&](Value *Val, bool IsOffset) {
55 Worklist.insert(ValueAndIsOffset(Val, IsOffset));
56 return Worklist.size() <= MaxUsers;
57 };
58 if (!Push(V, false))
59 return false;
60 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
61 const auto [Value, IsOffset] = Worklist[Idx];
62 for (auto &U : Value->uses()) {
63 auto *I = cast<Instruction>(U.getUser());
64
65 if (auto *LI = dyn_cast<LoadInst>(I)) {
66 // Ignore non-volatile loads, they are always ok.
67 if (!LI->isSimple()) return false;
68 continue;
69 }
70
72 // We set IsOffset=true, to forbid the memcpy from occurring after the
73 // phi: If one of the phi operands is not based on the alloca, we
74 // would incorrectly omit a write.
75 if (!Push(I, true))
76 return false;
77 continue;
78 }
80 // If uses of the bitcast are ok, we are ok.
81 if (!Push(I, IsOffset))
82 return false;
83 continue;
84 }
85 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
86 // If the GEP has all zero indices, it doesn't offset the pointer. If it
87 // doesn't, it does.
88 if (!Push(I, IsOffset || !GEP->hasAllZeroIndices()))
89 return false;
90 continue;
91 }
92
93 if (auto *Call = dyn_cast<CallBase>(I)) {
94 // If this is the function being called then we treat it like a load and
95 // ignore it.
96 if (Call->isCallee(&U))
97 continue;
98
99 unsigned DataOpNo = Call->getDataOperandNo(&U);
100 bool IsArgOperand = Call->isArgOperand(&U);
101
102 // Inalloca arguments are clobbered by the call.
103 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
104 return false;
105
106 // If this call site doesn't modify the memory, then we know it is just
107 // a load (but one that potentially returns the value itself), so we can
108 // ignore it if we know that the value isn't captured.
109 bool NoCapture = Call->doesNotCapture(DataOpNo);
110 if (NoCapture &&
111 (Call->onlyReadsMemory() || Call->onlyReadsMemory(DataOpNo)))
112 continue;
113 }
114
115 // Lifetime intrinsics can be handled by the caller.
116 if (I->isLifetimeStartOrEnd()) {
117 assert(I->use_empty() && "Lifetime markers have no result to use!");
118 ToDelete.push_back(I);
119 continue;
120 }
121
122 // If this is isn't our memcpy/memmove, reject it as something we can't
123 // handle.
125 if (!MI)
126 return false;
127
128 // If the transfer is volatile, reject it.
129 if (MI->isVolatile())
130 return false;
131
132 // If the transfer is using the alloca as a source of the transfer, then
133 // ignore it since it is a load (unless the transfer is volatile).
134 if (U.getOperandNo() == 1)
135 continue;
136
137 // If we already have seen a copy, reject the second one.
138 if (TheCopy) return false;
139
140 // If the pointer has been offset from the start of the alloca, we can't
141 // safely handle this.
142 if (IsOffset) return false;
143
144 // If the memintrinsic isn't using the alloca as the dest, reject it.
145 if (U.getOperandNo() != 0) return false;
146
147 // If the source of the memcpy/move is not constant, reject it.
148 if (isModSet(AA->getModRefInfoMask(MI->getSource())))
149 return false;
150
151 // Otherwise, the transform is safe. Remember the copy instruction.
152 TheCopy = MI;
153 }
154 }
155 return true;
156}
157
158/// isOnlyCopiedFromConstantMemory - Return true if the specified alloca is only
159/// modified by a copy from a constant memory location. If we can prove this, we
160/// can replace any uses of the alloca with uses of the memory location
161/// directly.
162static MemTransferInst *
165 unsigned MaxUsers) {
166 MemTransferInst *TheCopy = nullptr;
167 if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete, MaxUsers))
168 return TheCopy;
169 return nullptr;
170}
171
172/// Returns true if V is dereferenceable for size of alloca.
173static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
174 const DataLayout &DL) {
175 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL);
176 if (!AllocaSize || AllocaSize->isScalable())
177 return false;
179 APInt(64, *AllocaSize), DL);
180}
181
183 AllocaInst &AI, DominatorTree &DT) {
184 // Check for array size of 1 (scalar allocation).
185 if (!AI.isArrayAllocation()) {
186 // i32 1 is the canonical array size for scalar allocations.
187 if (AI.getArraySize()->getType()->isIntegerTy(32))
188 return nullptr;
189
190 // Canonicalize it.
191 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
192 }
193
194 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
195 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
196 if (C->getValue().getActiveBits() <= 64) {
197 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
198 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),
199 nullptr, AI.getName());
200 New->setAlignment(AI.getAlign());
201 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
202 New->copyMetadata(AI);
203
204 replaceAllDbgUsesWith(AI, *New, *New, DT);
205 return IC.replaceInstUsesWith(AI, New);
206 }
207 }
208
210 return IC.replaceInstUsesWith(AI, PoisonValue::get(AI.getType()));
211
212 // Ensure that the alloca array size argument has type equal to the offset
213 // size of the alloca() pointer, which, in the tyical case, is intptr_t,
214 // so that any casting is exposed early.
215 Type *PtrIdxTy = IC.getDataLayout().getIndexType(AI.getType());
216 if (AI.getArraySize()->getType() != PtrIdxTy) {
217 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), PtrIdxTy, false);
218 return IC.replaceOperand(AI, 0, V);
219 }
220
221 return nullptr;
222}
223
224namespace {
225// If I and V are pointers in different address space, it is not allowed to
226// use replaceAllUsesWith since I and V have different types. A
227// non-target-specific transformation should not use addrspacecast on V since
228// the two address space may be disjoint depending on target.
229//
230// This class chases down uses of the old pointer until reaching the load
231// instructions, then replaces the old pointer in the load instructions with
232// the new pointer. If during the chasing it sees bitcast or GEP, it will
233// create new bitcast or GEP with the new pointer and use them in the load
234// instruction.
235class PointerReplacer {
236public:
237 PointerReplacer(InstCombinerImpl &IC, Instruction &Root, unsigned SrcAS)
238 : IC(IC), Root(Root), FromAS(SrcAS) {}
239
240 bool collectUsers();
241 void replacePointer(Value *V);
242
243private:
244 void replace(Instruction *I);
245 Value *getReplacement(Value *V) const { return WorkMap.lookup(V); }
246 bool isAvailable(Instruction *I) const {
247 return I == &Root || UsersToReplace.contains(I);
248 }
249
250 bool isEqualOrValidAddrSpaceCast(const Instruction *I,
251 unsigned FromAS) const {
252 const auto *ASC = dyn_cast<AddrSpaceCastInst>(I);
253 if (!ASC)
254 return false;
255 unsigned ToAS = ASC->getDestAddressSpace();
256 return (FromAS == ToAS) || IC.isValidAddrSpaceCast(FromAS, ToAS);
257 }
258
259 SmallSetVector<Instruction *, 32> UsersToReplace;
260 DenseMap<Value *, Value *> WorkMap;
261 InstCombinerImpl &IC;
262 Instruction &Root;
263 unsigned FromAS;
264};
265} // end anonymous namespace
266
267bool PointerReplacer::collectUsers() {
268 SmallVector<Instruction *> Worklist;
269 SmallSetVector<Instruction *, 32> ValuesToRevisit;
270
271 auto PushUsersToWorklist = [&](Instruction *Inst) {
272 for (Instruction *I : Inst->users())
273 if (!isAvailable(I) && !ValuesToRevisit.contains(I))
274 Worklist.emplace_back(I);
275 };
276
277 auto TryPushInstOperand = [&](Instruction *InstOp) {
278 if (!UsersToReplace.contains(InstOp)) {
279 if (!ValuesToRevisit.insert(InstOp))
280 return false;
281 Worklist.emplace_back(InstOp);
282 }
283 return true;
284 };
285
286 PushUsersToWorklist(&Root);
287 while (!Worklist.empty()) {
288 Instruction *Inst = Worklist.pop_back_val();
289 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
290 if (Load->isVolatile())
291 return false;
292 UsersToReplace.insert(Load);
293 } else if (auto *PHI = dyn_cast<PHINode>(Inst)) {
294 /// TODO: Handle poison and null pointers for PHI and select.
295 // If all incoming values are available, mark this PHI as
296 // replacable and push it's users into the worklist.
297 bool IsReplaceable = all_of(PHI->incoming_values(),
298 [](Value *V) { return isa<Instruction>(V); });
299 if (IsReplaceable && all_of(PHI->incoming_values(), [&](Value *V) {
300 return isAvailable(cast<Instruction>(V));
301 })) {
302 UsersToReplace.insert(PHI);
303 PushUsersToWorklist(PHI);
304 continue;
305 }
306
307 // Either an incoming value is not an instruction or not all
308 // incoming values are available. If this PHI was already
309 // visited prior to this iteration, return false.
310 if (!IsReplaceable || !ValuesToRevisit.insert(PHI))
311 return false;
312
313 // Push PHI back into the stack, followed by unavailable
314 // incoming values.
315 Worklist.emplace_back(PHI);
316 for (unsigned Idx = 0; Idx < PHI->getNumIncomingValues(); ++Idx) {
317 if (!TryPushInstOperand(cast<Instruction>(PHI->getIncomingValue(Idx))))
318 return false;
319 }
320 } else if (auto *SI = dyn_cast<SelectInst>(Inst)) {
321 auto *TrueInst = dyn_cast<Instruction>(SI->getTrueValue());
322 auto *FalseInst = dyn_cast<Instruction>(SI->getFalseValue());
323 if (!TrueInst || !FalseInst)
324 return false;
325
326 if (isAvailable(TrueInst) && isAvailable(FalseInst)) {
327 UsersToReplace.insert(SI);
328 PushUsersToWorklist(SI);
329 continue;
330 }
331
332 // Push select back onto the stack, followed by unavailable true/false
333 // value.
334 Worklist.emplace_back(SI);
335 if (!TryPushInstOperand(TrueInst) || !TryPushInstOperand(FalseInst))
336 return false;
337 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(Inst)) {
338 auto *PtrOp = dyn_cast<Instruction>(GEP->getPointerOperand());
339 if (!PtrOp)
340 return false;
341 if (isAvailable(PtrOp)) {
342 UsersToReplace.insert(GEP);
343 PushUsersToWorklist(GEP);
344 continue;
345 }
346
347 Worklist.emplace_back(GEP);
348 if (!TryPushInstOperand(PtrOp))
349 return false;
350 } else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {
351 if (MI->isVolatile())
352 return false;
353 UsersToReplace.insert(Inst);
354 } else if (isEqualOrValidAddrSpaceCast(Inst, FromAS)) {
355 UsersToReplace.insert(Inst);
356 PushUsersToWorklist(Inst);
357 } else if (Inst->isLifetimeStartOrEnd()) {
358 continue;
359 } else {
360 // TODO: For arbitrary uses with address space mismatches, should we check
361 // if we can introduce a valid addrspacecast?
362 LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *Inst << '\n');
363 return false;
364 }
365 }
366
367 return true;
368}
369
370void PointerReplacer::replacePointer(Value *V) {
371 assert(cast<PointerType>(Root.getType()) != cast<PointerType>(V->getType()) &&
372 "Invalid usage");
373 WorkMap[&Root] = V;
374 SmallVector<Instruction *> Worklist;
375 SetVector<Instruction *> PostOrderWorklist;
376 SmallPtrSet<Instruction *, 32> Visited;
377
378 // Perform a postorder traversal of the users of Root.
379 Worklist.push_back(&Root);
380 while (!Worklist.empty()) {
381 Instruction *I = Worklist.back();
382
383 // If I has not been processed before, push each of its
384 // replacable users into the worklist.
385 if (Visited.insert(I).second) {
386 for (Instruction *UserInst : I->users()) {
387 if (UsersToReplace.contains(UserInst) && !Visited.contains(UserInst))
388 Worklist.push_back(UserInst);
389 }
390 // Otherwise, users of I have already been pushed into
391 // the PostOrderWorklist. Push I as well.
392 } else {
393 PostOrderWorklist.insert(I);
394 Worklist.pop_back();
395 }
396 }
397
398 // Replace pointers in reverse-postorder.
399 for (Instruction *I : reverse(PostOrderWorklist))
400 replace(I);
401}
402
403void PointerReplacer::replace(Instruction *I) {
404 if (getReplacement(I))
405 return;
406
407 if (auto *LT = dyn_cast<LoadInst>(I)) {
408 auto *V = getReplacement(LT->getPointerOperand());
409 assert(V && "Operand not replaced");
410 auto *NewI = new LoadInst(LT->getType(), V, "", LT->getProperties());
411 NewI->takeName(LT);
412 NewI->copyMetadata(*LT);
413
414 IC.InsertNewInstWith(NewI, LT->getIterator());
415 IC.replaceInstUsesWith(*LT, NewI);
416 // LT has actually been replaced by NewI. It is useless to insert LT into
417 // the map. Instead, we insert NewI into the map to indicate this is the
418 // replacement (new value).
419 WorkMap[NewI] = NewI;
420 } else if (auto *PHI = dyn_cast<PHINode>(I)) {
421 Value *FirstIncoming = PHI->getIncomingValue(0);
422 Value *V = WorkMap.lookup(FirstIncoming);
423 Type *NewType = V ? V->getType() : FirstIncoming->getType();
424 if (PHI->getType() == NewType) {
425 for (unsigned I = 0; I < PHI->getNumIncomingValues(); ++I) {
426 Value *V = WorkMap.lookup(PHI->getIncomingValue(I));
427 PHI->setIncomingValue(I, V ? V : PHI->getIncomingValue(I));
428 }
429 WorkMap[PHI] = PHI;
430 return;
431 }
432
433 auto *NewPHI = PHINode::Create(NewType, PHI->getNumIncomingValues(), "");
434 IC.InsertNewInstWith(NewPHI, PHI->getIterator());
435 NewPHI->takeName(PHI);
436 NewPHI->copyMetadata(*PHI);
437 WorkMap[PHI] = NewPHI;
438 for (auto [IncomingValue, IncomingBlock] :
439 zip_equal(PHI->incoming_values(), PHI->blocks())) {
440 Value *V = WorkMap.lookup(IncomingValue);
441 assert(V && V->getType() == NewType &&
442 "Type-changing PHI incoming value was not replaced");
443 NewPHI->addIncoming(V, IncomingBlock);
444 }
445 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
446 auto *V = getReplacement(GEP->getPointerOperand());
447 assert(V && "Operand not replaced");
448 SmallVector<Value *, 8> Indices(GEP->indices());
449 auto *NewI =
450 GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);
451 IC.InsertNewInstWith(NewI, GEP->getIterator());
452 NewI->takeName(GEP);
453 NewI->setNoWrapFlags(GEP->getNoWrapFlags());
454 WorkMap[GEP] = NewI;
455 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
456 Value *TrueValue = SI->getTrueValue();
457 Value *FalseValue = SI->getFalseValue();
458 if (Value *Replacement = getReplacement(TrueValue))
459 TrueValue = Replacement;
460 if (Value *Replacement = getReplacement(FalseValue))
461 FalseValue = Replacement;
462 auto *NewSI = SelectInst::Create(SI->getCondition(), TrueValue, FalseValue,
463 SI->getName(), nullptr, SI);
464 IC.InsertNewInstWith(NewSI, SI->getIterator());
465 NewSI->takeName(SI);
466 WorkMap[SI] = NewSI;
467 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
468 auto *DestV = MemCpy->getRawDest();
469 auto *SrcV = MemCpy->getRawSource();
470
471 if (auto *DestReplace = getReplacement(DestV))
472 DestV = DestReplace;
473 if (auto *SrcReplace = getReplacement(SrcV))
474 SrcV = SrcReplace;
475
476 IC.Builder.SetInsertPoint(MemCpy);
477 auto *NewI = IC.Builder.CreateMemTransferInst(
478 MemCpy->getIntrinsicID(), DestV, MemCpy->getDestAlign(), SrcV,
479 MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile());
480 AAMDNodes AAMD = MemCpy->getAAMetadata();
481 if (AAMD)
482 NewI->setAAMetadata(AAMD);
483
484 IC.eraseInstFromFunction(*MemCpy);
485 WorkMap[MemCpy] = NewI;
486 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I)) {
487 auto *V = getReplacement(ASC->getPointerOperand());
488 assert(V && "Operand not replaced");
489 assert(isEqualOrValidAddrSpaceCast(
490 ASC, V->getType()->getPointerAddressSpace()) &&
491 "Invalid address space cast!");
492
493 if (V->getType()->getPointerAddressSpace() !=
494 ASC->getType()->getPointerAddressSpace()) {
495 auto *NewI = new AddrSpaceCastInst(V, ASC->getType(), "");
496 NewI->takeName(ASC);
497 IC.InsertNewInstWith(NewI, ASC->getIterator());
498 WorkMap[ASC] = NewI;
499 } else {
500 WorkMap[ASC] = V;
501 }
502
503 } else {
504 llvm_unreachable("should never reach here");
505 }
506}
507
509 if (auto *I = simplifyAllocaArraySize(*this, AI, DT))
510 return I;
511
512 // Move all alloca's of zero byte objects to the entry block and merge them
513 // together. Note that we only do this for alloca's, because malloc should
514 // allocate and return a unique pointer, even for a zero byte allocation.
515 std::optional<TypeSize> Size = AI.getAllocationSize(DL);
516 if (Size && Size->isZero()) {
517 // For a zero sized alloca there is no point in doing an array allocation.
518 // This is helpful if the array size is a complicated expression not used
519 // elsewhere.
520 if (AI.isArrayAllocation())
521 return replaceOperand(AI, 0,
522 ConstantInt::get(AI.getArraySize()->getType(), 1));
523
524 // Get the first instruction in the entry block.
525 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
526 BasicBlock::iterator FirstInst = EntryBlock.getFirstNonPHIOrPseudoProbe();
527 if (&*FirstInst != &AI) {
528 // If the entry block doesn't start with a zero-size alloca then move
529 // this one to the start of the entry block. There is no problem with
530 // dominance as the array size was forced to a constant earlier already.
531 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
532 std::optional<TypeSize> EntryAISize =
533 EntryAI ? EntryAI->getAllocationSize(DL) : std::nullopt;
534 if (!EntryAISize || !EntryAISize->isZero()) {
535 AI.moveBefore(FirstInst);
536 return &AI;
537 }
538
539 // Replace this zero-sized alloca with the one at the start of the entry
540 // block after ensuring that the address will be aligned enough for both
541 // types.
542 const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
543 EntryAI->setAlignment(MaxAlign);
544 return replaceInstUsesWith(AI, EntryAI);
545 }
546 }
547
548 // Check to see if this allocation is only modified by a memcpy/memmove from
549 // a memory location whose alignment is equal to or exceeds that of the
550 // allocation. If this is the case, we can change all users to use the
551 // constant memory location instead. This is commonly produced by the CFE by
552 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
553 // is only subsequently read.
556 AA, &AI, ToDelete, CLOpts.max_copied_from_constant_users)) {
557 Value *TheSrc = Copy->getSource();
558 Align AllocaAlign = AI.getAlign();
559 Align SourceAlign = getOrEnforceKnownAlignment(
560 TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
561 if (AllocaAlign <= SourceAlign &&
562 isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
563 !isa<Instruction>(TheSrc)) {
564 // FIXME: Can we sink instructions without violating dominance when TheSrc
565 // is an instruction instead of a constant or argument?
566 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
567 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
568 unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
569 if (AI.getAddressSpace() == SrcAddrSpace) {
570 for (Instruction *Delete : ToDelete)
571 eraseInstFromFunction(*Delete);
572
573 Instruction *NewI = replaceInstUsesWith(AI, TheSrc);
575 ++NumGlobalCopies;
576 return NewI;
577 }
578
579 PointerReplacer PtrReplacer(*this, AI, SrcAddrSpace);
580 if (PtrReplacer.collectUsers()) {
581 for (Instruction *Delete : ToDelete)
582 eraseInstFromFunction(*Delete);
583
584 PtrReplacer.replacePointer(TheSrc);
585 ++NumGlobalCopies;
586 }
587 }
588 }
589
590 // At last, use the generic allocation site handler to aggressively remove
591 // unused allocas.
592 return visitAllocSite(AI);
593}
594
595// Are we allowed to form a atomic load or store of this type?
596static bool isSupportedAtomicType(Type *Ty) {
597 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
598}
599
600/// Helper to combine a load to a new type.
601///
602/// This just does the work of combining a load to a new type. It handles
603/// metadata, etc., and returns the new instruction. The \c NewTy should be the
604/// loaded *value* type. This will convert it to a pointer, cast the operand to
605/// that pointer type, load it, etc.
606///
607/// Note that this will create all of the instructions with whatever insert
608/// point the \c InstCombinerImpl currently is using.
610 const Twine &Suffix) {
611 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
612 "can't fold an atomic load to requested type");
613
614 LoadInst *NewLoad = Builder.CreateLoad(
615 NewTy, LI.getPointerOperand(), LI.getProperties(), LI.getName() + Suffix);
616 copyMetadataForLoad(*NewLoad, LI);
617 return NewLoad;
618}
619
620/// Combine a store to a new type.
621///
622/// Returns the newly created store instruction.
624 Value *V) {
625 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
626 "can't fold an atomic store of requested type");
627
628 Value *Ptr = SI.getPointerOperand();
630 SI.getAllMetadata(MD);
631
632 StoreInst *NewStore = IC.Builder.CreateStore(V, Ptr, SI.getProperties());
633 for (const auto &MDPair : MD) {
634 unsigned ID = MDPair.first;
635 MDNode *N = MDPair.second;
636 // Note, essentially every kind of metadata should be preserved here! This
637 // routine is supposed to clone a store instruction changing *only its
638 // type*. The only metadata it makes sense to drop is metadata which is
639 // invalidated when the pointer type changes. This should essentially
640 // never be the case in LLVM, but we explicitly switch over only known
641 // metadata to be conservatively correct. If you are adding metadata to
642 // LLVM which pertains to stores, you almost certainly want to add it
643 // here.
644 switch (ID) {
645 case LLVMContext::MD_dbg:
646 case LLVMContext::MD_DIAssignID:
647 case LLVMContext::MD_tbaa:
648 case LLVMContext::MD_prof:
649 case LLVMContext::MD_fpmath:
650 case LLVMContext::MD_tbaa_struct:
651 case LLVMContext::MD_alias_scope:
652 case LLVMContext::MD_noalias:
653 case LLVMContext::MD_nontemporal:
654 case LLVMContext::MD_mem_parallel_loop_access:
655 case LLVMContext::MD_access_group:
656 // All of these directly apply.
657 NewStore->setMetadata(ID, N);
658 break;
659 case LLVMContext::MD_invariant_load:
660 case LLVMContext::MD_nonnull:
661 case LLVMContext::MD_noundef:
662 case LLVMContext::MD_range:
663 case LLVMContext::MD_align:
664 case LLVMContext::MD_dereferenceable:
665 case LLVMContext::MD_dereferenceable_or_null:
666 // These don't apply for stores.
667 break;
668 }
669 }
670
671 return NewStore;
672}
673
674/// Combine loads to match the type of their uses' value after looking
675/// through intervening bitcasts.
676///
677/// The core idea here is that if the result of a load is used in an operation,
678/// we should load the type most conducive to that operation. For example, when
679/// loading an integer and converting that immediately to a pointer, we should
680/// instead directly load a pointer.
681///
682/// However, this routine must never change the width of a load or the number of
683/// loads as that would introduce a semantic change. This combine is expected to
684/// be a semantic no-op which just allows loads to more closely model the types
685/// of their consuming operations.
686///
687/// Currently, we also refuse to change the precise type used for an atomic load
688/// or a volatile load. This is debatable, and might be reasonable to change
689/// later. However, it is risky in case some backend or other part of LLVM is
690/// relying on the exact type loaded to select appropriate atomic operations.
692 LoadInst &Load) {
693 // FIXME: We could probably with some care handle both volatile and ordered
694 // atomic loads here but it isn't clear that this is important.
695 if (!Load.isUnordered())
696 return nullptr;
697
698 if (Load.isElementwise())
699 return nullptr;
700
701 if (Load.use_empty())
702 return nullptr;
703
704 // swifterror values can't be bitcasted.
705 if (Load.getPointerOperand()->isSwiftError())
706 return nullptr;
707
708 // Fold away bit casts of the loaded value by loading the desired type.
709 // Note that we should not do this for pointer<->integer casts,
710 // because that would result in type punning.
711 if (Load.hasOneUse()) {
712 // Don't transform when the type is x86_amx, it makes the pass that lower
713 // x86_amx type happy.
714 Type *LoadTy = Load.getType();
715 if (auto *BC = dyn_cast<BitCastInst>(Load.user_back())) {
716 assert(!LoadTy->isX86_AMXTy() && "Load from x86_amx* should not happen!");
717 if (BC->getType()->isX86_AMXTy())
718 return nullptr;
719 }
720
721 if (auto *CastUser = dyn_cast<CastInst>(Load.user_back())) {
722 Type *DestTy = CastUser->getDestTy();
723 if (CastUser->isNoopCast(IC.getDataLayout()) &&
724 LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&
725 (!Load.isAtomic() || isSupportedAtomicType(DestTy))) {
726 LoadInst *NewLoad = IC.combineLoadToNewType(Load, DestTy);
727 CastUser->replaceAllUsesWith(NewLoad);
728 IC.eraseInstFromFunction(*CastUser);
729 return &Load;
730 }
731 }
732 }
733
734 // FIXME: We should also canonicalize loads of vectors when their elements are
735 // cast to other types.
736 return nullptr;
737}
738
740 // FIXME: We could probably with some care handle both volatile and atomic
741 // stores here but it isn't clear that this is important.
742 if (!LI.isSimple())
743 return nullptr;
744
745 Type *T = LI.getType();
746 if (!T->isAggregateType())
747 return nullptr;
748
749 StringRef Name = LI.getName();
750
751 if (auto *ST = dyn_cast<StructType>(T)) {
752 // If the struct only have one element, we unpack.
753 auto NumElements = ST->getNumElements();
754 if (NumElements == 1) {
755 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
756 ".unpack");
757 NewLoad->setAAMetadata(LI.getAAMetadata());
758 // Copy invariant metadata from parent load.
759 NewLoad->copyMetadata(LI, LLVMContext::MD_invariant_load);
761 PoisonValue::get(T), NewLoad, 0, Name));
762 }
763
764 // We don't want to break loads with padding here as we'd loose
765 // the knowledge that padding exists for the rest of the pipeline.
766 const DataLayout &DL = IC.getDataLayout();
767 auto *SL = DL.getStructLayout(ST);
768
769 if (SL->hasPadding())
770 return nullptr;
771
772 const auto Align = LI.getAlign();
773 auto *Addr = LI.getPointerOperand();
774 auto *IdxType = DL.getIndexType(Addr->getType());
775
777 for (unsigned i = 0; i < NumElements; i++) {
778 auto *Ptr = IC.Builder.CreateInBoundsPtrAdd(
779 Addr, IC.Builder.CreateTypeSize(IdxType, SL->getElementOffset(i)),
780 Name + ".elt");
781 auto *L = IC.Builder.CreateAlignedLoad(
782 ST->getElementType(i), Ptr,
783 commonAlignment(Align, SL->getElementOffset(i).getKnownMinValue()),
784 Name + ".unpack");
785 // Propagate AA metadata. It'll still be valid on the narrowed load.
786 L->setAAMetadata(LI.getAAMetadata());
787 // Copy invariant metadata from parent load.
788 L->copyMetadata(LI, LLVMContext::MD_invariant_load);
789 V = IC.Builder.CreateInsertValue(V, L, i);
790 }
791
792 V->setName(Name);
793 return IC.replaceInstUsesWith(LI, V);
794 }
795
796 if (auto *AT = dyn_cast<ArrayType>(T)) {
797 auto *ET = AT->getElementType();
798 auto NumElements = AT->getNumElements();
799 if (NumElements == 1) {
800 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
801 NewLoad->setAAMetadata(LI.getAAMetadata());
803 PoisonValue::get(T), NewLoad, 0, Name));
804 }
805
806 // Bail out if the array is too large. Ideally we would like to optimize
807 // arrays of arbitrary size but this has a terrible impact on compile time.
808 // The threshold here is chosen arbitrarily, maybe needs a little bit of
809 // tuning.
810 if (NumElements > IC.CLOpts.maxarray_size)
811 return nullptr;
812
813 const DataLayout &DL = IC.getDataLayout();
814 TypeSize EltSize = DL.getTypeAllocSize(ET);
815 const auto Align = LI.getAlign();
816
817 auto *Addr = LI.getPointerOperand();
818 auto *IdxType = Type::getInt64Ty(T->getContext());
819 auto *Zero = ConstantInt::get(IdxType, 0);
820
823 for (uint64_t i = 0; i < NumElements; i++) {
824 Value *Indices[2] = {
825 Zero,
826 ConstantInt::get(IdxType, i),
827 };
828 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices),
829 Name + ".elt");
830 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
831 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
832 EltAlign, Name + ".unpack");
833 L->setAAMetadata(LI.getAAMetadata());
834 V = IC.Builder.CreateInsertValue(V, L, i);
835 Offset += EltSize;
836 }
837
838 V->setName(Name);
839 return IC.replaceInstUsesWith(LI, V);
840 }
841
842 return nullptr;
843}
844
845// If we can determine that all possible objects pointed to by the provided
846// pointer value are, not only dereferenceable, but also definitively less than
847// or equal to the provided maximum size, then return true. Otherwise, return
848// false (constant global values and allocas fall into this category).
849//
850// FIXME: This should probably live in ValueTracking (or similar).
852 const DataLayout &DL) {
854 SmallVector<Value *, 4> Worklist(1, V);
855
856 do {
857 Value *P = Worklist.pop_back_val();
858 P = P->stripPointerCasts();
859
860 if (!Visited.insert(P).second)
861 continue;
862
864 Worklist.push_back(SI->getTrueValue());
865 Worklist.push_back(SI->getFalseValue());
866 continue;
867 }
868
869 if (PHINode *PN = dyn_cast<PHINode>(P)) {
870 append_range(Worklist, PN->incoming_values());
871 continue;
872 }
873
875 if (GA->isInterposable())
876 return false;
877 Worklist.push_back(GA->getAliasee());
878 continue;
879 }
880
881 // If we know how big this object is, and it is less than MaxSize, continue
882 // searching. Otherwise, return false.
883 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
884 std::optional<TypeSize> AllocSize = AI->getAllocationSize(DL);
885 if (!AllocSize || AllocSize->isScalable() ||
886 AllocSize->getFixedValue() > MaxSize)
887 return false;
888 continue;
889 }
890
892 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
893 return false;
894
895 uint64_t InitSize = GV->getGlobalSize(DL);
896 if (InitSize > MaxSize)
897 return false;
898 continue;
899 }
900
901 return false;
902 } while (!Worklist.empty());
903
904 return true;
905}
906
907// If we're indexing into an object of a known size, and the outer index is
908// not a constant, but having any value but zero would lead to undefined
909// behavior, replace it with zero.
910//
911// For example, if we have:
912// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
913// ...
914// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
915// ... = load i32* %arrayidx, align 4
916// Then we know that we can replace %x in the GEP with i64 0.
917//
918// FIXME: We could fold any GEP index to zero that would cause UB if it were
919// not zero. Currently, we only handle the first such index. Also, we could
920// also search through non-zero constant indices if we kept track of the
921// offsets those indices implied.
923 GetElementPtrInst *GEPI, Instruction *MemI,
924 unsigned &Idx) {
925 if (GEPI->getNumOperands() < 2)
926 return false;
927
928 // Find the first non-zero index of a GEP. If all indices are zero, return
929 // one past the last index.
930 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
931 unsigned I = 1;
932 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
933 Value *V = GEPI->getOperand(I);
934 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
935 if (CI->isZero())
936 continue;
937
938 break;
939 }
940
941 return I;
942 };
943
944 // Skip through initial 'zero' indices, and find the corresponding pointer
945 // type. See if the next index is not a constant.
946 Idx = FirstNZIdx(GEPI);
947 if (Idx == GEPI->getNumOperands())
948 return false;
949 if (isa<Constant>(GEPI->getOperand(Idx)))
950 return false;
951
952 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
953 Type *SourceElementType = GEPI->getSourceElementType();
954 // Size information about scalable vectors is not available, so we cannot
955 // deduce whether indexing at n is undefined behaviour or not. Bail out.
956 if (SourceElementType->isScalableTy())
957 return false;
958
959 Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
960 if (!AllocTy || !AllocTy->isSized())
961 return false;
962 const DataLayout &DL = IC.getDataLayout();
963 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedValue();
964
965 // If there are more indices after the one we might replace with a zero, make
966 // sure they're all non-negative. If any of them are negative, the overall
967 // address being computed might be before the base address determined by the
968 // first non-zero index.
969 auto IsAllNonNegative = [&]() {
970 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
971 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), MemI);
972 if (Known.isNonNegative())
973 continue;
974 return false;
975 }
976
977 return true;
978 };
979
980 // FIXME: If the GEP is not inbounds, and there are extra indices after the
981 // one we'll replace, those could cause the address computation to wrap
982 // (rendering the IsAllNonNegative() check below insufficient). We can do
983 // better, ignoring zero indices (and other indices we can prove small
984 // enough not to wrap).
985 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
986 return false;
987
988 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
989 // also known to be dereferenceable.
990 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
991 IsAllNonNegative();
992}
993
994// If we're indexing into an object with a variable index for the memory
995// access, but the object has only one element, we can assume that the index
996// will always be zero. If we replace the GEP, return it.
998 Instruction &MemI) {
1000 unsigned Idx;
1001 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
1002 Instruction *NewGEPI = GEPI->clone();
1003 NewGEPI->setOperand(Idx,
1004 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
1005 IC.InsertNewInstBefore(NewGEPI, GEPI->getIterator());
1006 // If the memory instruction is guaranteed to execute whenever the GEP
1007 // does, the dereference proves the index is unconditionally zero.
1008 // Replace the GEP for all users so they all benefit.
1009 if (GEPI->getParent() == MemI.getParent() &&
1011 MemI.getIterator())) {
1012 IC.replaceInstUsesWith(*GEPI, NewGEPI);
1013 IC.eraseInstFromFunction(*GEPI);
1014 }
1015 return NewGEPI;
1016 }
1017 }
1018
1019 return nullptr;
1020}
1021
1023 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
1024 return false;
1025
1026 auto *Ptr = SI.getPointerOperand();
1028 Ptr = GEPI->getOperand(0);
1029 return (isa<ConstantPointerNull>(Ptr) &&
1030 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
1031}
1032
1035 const Value *GEPI0 = GEPI->getOperand(0);
1036 if (isa<ConstantPointerNull>(GEPI0) &&
1037 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
1038 return true;
1039 }
1040 if (isa<UndefValue>(Op) ||
1043 return true;
1044 return false;
1045}
1046
1047Value *InstCombinerImpl::simplifyNonNullOperand(Value *V, bool UseProvenance,
1048 unsigned Depth) {
1049 if (auto *Sel = dyn_cast<SelectInst>(V)) {
1050 if (isa<ConstantPointerNull>(Sel->getOperand(1)))
1051 return Sel->getOperand(2);
1052
1053 if (isa<ConstantPointerNull>(Sel->getOperand(2)))
1054 return Sel->getOperand(1);
1055 }
1056
1057 if (!V->hasOneUse())
1058 return nullptr;
1059
1060 constexpr unsigned RecursionLimit = 3;
1061 if (Depth == RecursionLimit)
1062 return nullptr;
1063
1064 if (auto *GEP = dyn_cast<GetElementPtrInst>(V)) {
1065 // If UseProvenance is true, we know by precondition that null pointers are
1066 // not defined in this address-space. And we know that the GEP has
1067 // provenance for a valid object. Therefore, the operand must also have
1068 // valid provenance. We assume ConstantPointerNull does not have provenance.
1069 // (The address could be equal to zero, but that doesn't matter.)
1070 //
1071 // If UseProvenance is false, we know that the address is some non-zero
1072 // value. If the GEP is inbounds, and null pointers can't point to valid
1073 // objects, the operand must also have a non-zero value.
1074 if (UseProvenance ||
1075 (GEP->isInBounds() &&
1076 !NullPointerIsDefined(GEP->getFunction(), GEP->getAddressSpace()))) {
1077 if (auto *Res = simplifyNonNullOperand(GEP->getPointerOperand(),
1078 UseProvenance, Depth + 1)) {
1079 replaceOperand(*GEP, 0, Res);
1081 return nullptr;
1082 }
1083 }
1084 }
1085
1086 if (auto *PHI = dyn_cast<PHINode>(V)) {
1087 bool Changed = false;
1088 for (Use &U : PHI->incoming_values()) {
1089 // We set Depth to RecursionLimit to avoid expensive recursion.
1090 if (auto *Res =
1091 simplifyNonNullOperand(U.get(), UseProvenance, RecursionLimit)) {
1092 replaceUse(U, Res);
1093 Changed = true;
1094 }
1095 }
1096 if (Changed)
1098 return nullptr;
1099 }
1100
1101 return nullptr;
1102}
1103
1104/// load (gep (select Cond, TrueC, FalseC), IndexC)
1105/// --> select Cond, (load TrueC'), (load FalseC')
1106/// Only done when both arms fold to a constant, which makes this profitable
1107/// regardless of the use count of the select: no new load is created.
1109 const DataLayout &DL) {
1110 Value *Op = LI.getOperand(0);
1111 // In canonical IR the pattern is load (select) or load (gep (select)).
1112 Value *Base = Op;
1113 if (auto *GEP = dyn_cast<GEPOperator>(Base))
1114 Base = GEP->getPointerOperand();
1115 Value *Cond;
1116 Constant *TrueC, *FalseC;
1117 if (!match(Base,
1118 m_Select(m_Value(Cond), m_Constant(TrueC), m_Constant(FalseC))))
1119 return nullptr;
1120
1121 APInt Offset(DL.getIndexTypeSizeInBits(Op->getType()), 0);
1122 if (Op->stripAndAccumulateConstantOffsets(DL, Offset,
1123 /*AllowNonInbounds=*/true) != Base)
1124 return nullptr;
1125
1126 // Stripping an addrspacecast may have changed the index width.
1127 if (DL.getIndexTypeSizeInBits(Base->getType()) != Offset.getBitWidth())
1128 return nullptr;
1129
1130 Constant *TrueVal =
1132 if (!TrueVal)
1133 return nullptr;
1134 Constant *FalseVal =
1136 if (!FalseVal)
1137 return nullptr;
1138
1139 return SelectInst::Create(Cond, TrueVal, FalseVal, "", nullptr,
1141}
1142
1144 Value *Op = LI.getOperand(0);
1145 if (Value *Res = simplifyLoadInst(&LI, Op, SQ.getWithInstruction(&LI)))
1146 return replaceInstUsesWith(LI, Res);
1147
1148 // Try to canonicalize the loaded type.
1149 if (Instruction *Res = combineLoadToOperationType(*this, LI))
1150 return Res;
1151
1152 // Replace GEP indices if possible.
1153 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI))
1154 return replaceOperand(LI, 0, NewGEPI);
1155
1156 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1157 return Res;
1158
1159 // Do really simple store-to-load forwarding and load CSE, to catch cases
1160 // where there are several consecutive memory accesses to the same location,
1161 // separated by a few arithmetic operations.
1162 bool IsLoadCSE = false;
1163 BatchAAResults BatchAA(*AA);
1164 if (Value *AvailableVal = FindAvailableLoadedValue(&LI, BatchAA, &IsLoadCSE)) {
1165 if (IsLoadCSE)
1166 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
1167
1168 return replaceInstUsesWith(
1169 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1170 LI.getName() + ".cast"));
1171 }
1172
1173 // None of the following transforms are legal for volatile/ordered atomic
1174 // loads. Most of them do apply for unordered atomics.
1175 if (!LI.isUnordered()) return nullptr;
1176
1177 // load(gep null, ...) -> unreachable
1178 // load null/undef -> unreachable
1179 // TODO: Consider a target hook for valid address spaces for this xforms.
1180 if (canSimplifyNullLoadOrGEP(LI, Op)) {
1183 }
1184
1185 if (Op->hasOneUse()) {
1186 // Change select and PHI nodes to select values instead of addresses: this
1187 // helps alias analysis out a lot, allows many others simplifications, and
1188 // exposes redundancy in the code.
1189 //
1190 // Note that we cannot do the transformation unless we know that the
1191 // introduced loads cannot trap! Something like this is valid as long as
1192 // the condition is always false: load (select bool %C, int* null, int* %G),
1193 // but it would not be valid if we transformed it to load from null
1194 // unconditionally.
1195 //
1196
1198 Value *SelectOp = Op;
1199 if (ASC && ASC->getOperand(0)->hasOneUse())
1200 SelectOp = ASC->getOperand(0);
1201 if (SelectInst *SI = dyn_cast<SelectInst>(SelectOp)) {
1202 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
1203 // or
1204 // load (addrspacecast(select (Cond, &V1, &V2))) -->
1205 // select(Cond, load (addrspacecast(&V1)), load (addrspacecast(&V2))).
1206 Align Alignment = LI.getAlign();
1207 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
1208 Alignment, SQ.getWithInstruction(SI)) &&
1209 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
1210 Alignment, SQ.getWithInstruction(SI))) {
1211
1212 auto MaybeCastedLoadOperand = [&](Value *Op) {
1213 if (ASC)
1214 return Builder.CreateAddrSpaceCast(Op, ASC->getType(),
1215 Op->getName() + ".cast");
1216 return Op;
1217 };
1218 Value *LoadOp1 = MaybeCastedLoadOperand(SI->getOperand(1));
1219 LoadInst *V1 =
1220 Builder.CreateLoad(LI.getType(), LoadOp1, LI.getProperties(),
1221 LoadOp1->getName() + ".val");
1222
1223 Value *LoadOp2 = MaybeCastedLoadOperand(SI->getOperand(2));
1224 LoadInst *V2 =
1225 Builder.CreateLoad(LI.getType(), LoadOp2, LI.getProperties(),
1226 LoadOp2->getName() + ".val");
1227 assert(LI.isUnordered() && "implied by above");
1228 // It is safe to copy any metadata that does not trigger UB. Copy any
1229 // poison-generating metadata.
1230 V1->copyMetadata(LI, Metadata::PoisonGeneratingIDs);
1232 return SelectInst::Create(SI->getCondition(), V1, V2, "", nullptr, SI);
1233 }
1234 }
1235 }
1236
1238 return Res;
1239
1241 if (Value *V = simplifyNonNullOperand(Op, /*UseProvenance=*/true))
1242 return replaceOperand(LI, 0, V);
1243
1244 // load(llvm.protected.field.ptr(ptr)) -> llvm.ptrauth.auth(load(ptr))
1245 if (isa<PointerType>(LI.getType())) {
1246 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
1247 if (II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1248 std::vector<OperandBundleDef> DSBundle;
1249 if (auto Bundle =
1250 II->getOperandBundle(LLVMContext::OB_deactivation_symbol))
1251 DSBundle.push_back(OperandBundleDef(
1252 "deactivation-symbol", cast<GlobalValue>(Bundle->Inputs[0])));
1253
1255 Builder.SetInsertPoint(&LI);
1256
1257 auto *NewLI = cast<LoadInst>(LI.clone());
1258 NewLI->setOperand(0, II->getOperand(0));
1259 Builder.Insert(NewLI);
1260
1262 F.getParent(), Intrinsic::ptrauth_auth, {});
1263 auto *LIInt = Builder.CreatePtrToInt(NewLI, Builder.getInt64Ty());
1264 Value *Auth = Builder.CreateCall(
1265 AuthIntr,
1266 {LIInt, Builder.getInt32(/*AArch64PACKey::DA*/ 2),
1267 II->getOperand(1)},
1268 DSBundle);
1269 Auth = Builder.CreateIntToPtr(Auth, Builder.getPtrTy());
1270 return replaceInstUsesWith(LI, Auth);
1271 }
1272 }
1273 }
1274
1275 return nullptr;
1276}
1277
1278/// Look for extractelement/insertvalue sequence that acts like a bitcast.
1279///
1280/// \returns underlying value that was "cast", or nullptr otherwise.
1281///
1282/// For example, if we have:
1283///
1284/// %E0 = extractelement <2 x double> %U, i32 0
1285/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1286/// %E1 = extractelement <2 x double> %U, i32 1
1287/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1288///
1289/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1290/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1291/// Note that %U may contain non-undef values where %V1 has undef.
1293 Value *U = nullptr;
1294 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1295 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1296 if (!E)
1297 return nullptr;
1298 auto *W = E->getVectorOperand();
1299 if (!U)
1300 U = W;
1301 else if (U != W)
1302 return nullptr;
1303 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1304 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1305 return nullptr;
1306 V = IV->getAggregateOperand();
1307 }
1308 if (!match(V, m_Undef()) || !U)
1309 return nullptr;
1310
1311 auto *UT = cast<VectorType>(U->getType());
1312 auto *VT = V->getType();
1313 // Check that types UT and VT are bitwise isomorphic.
1314 const auto &DL = IC.getDataLayout();
1315 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1316 return nullptr;
1317 }
1318 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1319 if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1320 return nullptr;
1321 } else {
1322 auto *ST = cast<StructType>(VT);
1323 if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1324 return nullptr;
1325 for (const auto *EltT : ST->elements()) {
1326 if (EltT != UT->getElementType())
1327 return nullptr;
1328 }
1329 }
1330 return U;
1331}
1332
1333/// Combine stores to match the type of value being stored.
1334///
1335/// The core idea here is that the memory does not have any intrinsic type and
1336/// where we can we should match the type of a store to the type of value being
1337/// stored.
1338///
1339/// However, this routine must never change the width of a store or the number of
1340/// stores as that would introduce a semantic change. This combine is expected to
1341/// be a semantic no-op which just allows stores to more closely model the types
1342/// of their incoming values.
1343///
1344/// Currently, we also refuse to change the precise type used for an atomic or
1345/// volatile store. This is debatable, and might be reasonable to change later.
1346/// However, it is risky in case some backend or other part of LLVM is relying
1347/// on the exact type stored to select appropriate atomic operations.
1348///
1349/// \returns true if the store was successfully combined away. This indicates
1350/// the caller must erase the store instruction. We have to let the caller erase
1351/// the store instruction as otherwise there is no way to signal whether it was
1352/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1354 // FIXME: We could probably with some care handle both volatile and ordered
1355 // atomic stores here but it isn't clear that this is important.
1356 if (!SI.isUnordered())
1357 return false;
1358
1359 if (SI.isElementwise())
1360 return false;
1361
1362 // swifterror values can't be bitcasted.
1363 if (SI.getPointerOperand()->isSwiftError())
1364 return false;
1365
1366 Value *V = SI.getValueOperand();
1367
1368 // Fold away bit casts of the stored value by storing the original type.
1369 if (auto *BC = dyn_cast<BitCastInst>(V)) {
1370 assert(!BC->getType()->isX86_AMXTy() &&
1371 "store to x86_amx* should not happen!");
1372 V = BC->getOperand(0);
1373 // Don't transform when the type is x86_amx, it makes the pass that lower
1374 // x86_amx type happy.
1375 if (V->getType()->isX86_AMXTy())
1376 return false;
1377 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1379 return true;
1380 }
1381 }
1382
1383 if (Value *U = likeBitCastFromVector(IC, V))
1384 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1385 combineStoreToNewValue(IC, SI, U);
1386 return true;
1387 }
1388
1389 // FIXME: We should also canonicalize stores of vectors when their elements
1390 // are cast to other types.
1391 return false;
1392}
1393
1395 // FIXME: We could probably with some care handle both volatile and atomic
1396 // stores here but it isn't clear that this is important.
1397 if (!SI.isSimple())
1398 return false;
1399
1400 Value *V = SI.getValueOperand();
1401 Type *T = V->getType();
1402
1403 if (!T->isAggregateType())
1404 return false;
1405
1406 if (auto *ST = dyn_cast<StructType>(T)) {
1407 // If the struct only have one element, we unpack.
1408 unsigned Count = ST->getNumElements();
1409 if (Count == 1) {
1410 V = IC.Builder.CreateExtractValue(V, 0);
1412 return true;
1413 }
1414
1415 // We don't want to break loads with padding here as we'd loose
1416 // the knowledge that padding exists for the rest of the pipeline.
1417 const DataLayout &DL = IC.getDataLayout();
1418 auto *SL = DL.getStructLayout(ST);
1419
1420 if (SL->hasPadding())
1421 return false;
1422
1423 const auto Align = SI.getAlign();
1424
1425 SmallString<16> EltName = V->getName();
1426 EltName += ".elt";
1427 auto *Addr = SI.getPointerOperand();
1428 SmallString<16> AddrName = Addr->getName();
1429 AddrName += ".repack";
1430
1431 auto *IdxType = DL.getIndexType(Addr->getType());
1432 for (unsigned i = 0; i < Count; i++) {
1433 auto *Ptr = IC.Builder.CreateInBoundsPtrAdd(
1434 Addr, IC.Builder.CreateTypeSize(IdxType, SL->getElementOffset(i)),
1435 AddrName);
1436 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1437 auto EltAlign =
1438 commonAlignment(Align, SL->getElementOffset(i).getKnownMinValue());
1439 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1440 NS->setAAMetadata(SI.getAAMetadata());
1441 }
1442
1443 return true;
1444 }
1445
1446 if (auto *AT = dyn_cast<ArrayType>(T)) {
1447 // If the array only have one element, we unpack.
1448 auto NumElements = AT->getNumElements();
1449 if (NumElements == 1) {
1450 V = IC.Builder.CreateExtractValue(V, 0);
1452 return true;
1453 }
1454
1455 // Bail out if the array is too large. Ideally we would like to optimize
1456 // arrays of arbitrary size but this has a terrible impact on compile time.
1457 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1458 // tuning.
1459 if (NumElements > IC.CLOpts.maxarray_size)
1460 return false;
1461
1462 const DataLayout &DL = IC.getDataLayout();
1463 TypeSize EltSize = DL.getTypeAllocSize(AT->getElementType());
1464 const auto Align = SI.getAlign();
1465
1466 SmallString<16> EltName = V->getName();
1467 EltName += ".elt";
1468 auto *Addr = SI.getPointerOperand();
1469 SmallString<16> AddrName = Addr->getName();
1470 AddrName += ".repack";
1471
1472 auto *IdxType = Type::getInt64Ty(T->getContext());
1473 auto *Zero = ConstantInt::get(IdxType, 0);
1474
1476 for (uint64_t i = 0; i < NumElements; i++) {
1477 Value *Indices[2] = {
1478 Zero,
1479 ConstantInt::get(IdxType, i),
1480 };
1481 auto *Ptr =
1482 IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices), AddrName);
1483 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1484 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
1485 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1486 NS->setAAMetadata(SI.getAAMetadata());
1487 Offset += EltSize;
1488 }
1489
1490 return true;
1491 }
1492
1493 return false;
1494}
1495
1496/// equivalentAddressValues - Test if A and B will obviously have the same
1497/// value. This includes recognizing that %t0 and %t1 will have the same
1498/// value in code like this:
1499/// %t0 = getelementptr \@a, 0, 3
1500/// store i32 0, i32* %t0
1501/// %t1 = getelementptr \@a, 0, 3
1502/// %t2 = load i32* %t1
1503///
1505 // Test if the values are trivially equivalent.
1506 if (A == B) return true;
1507
1508 // Test if the values come form identical arithmetic instructions.
1509 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1510 // its only used to compare two uses within the same basic block, which
1511 // means that they'll always either have the same value or one of them
1512 // will have an undefined value.
1513 if (isa<BinaryOperator>(A) ||
1514 isa<CastInst>(A) ||
1515 isa<PHINode>(A) ||
1518 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1519 return true;
1520
1521 // Otherwise they may not be equivalent.
1522 return false;
1523}
1524
1526 Value *Val = SI.getOperand(0);
1527 Value *Ptr = SI.getOperand(1);
1528
1529 // Try to canonicalize the stored type.
1530 if (combineStoreToValueType(*this, SI))
1531 return eraseInstFromFunction(SI);
1532
1533 // Try to canonicalize the stored type.
1534 if (unpackStoreToAggregate(*this, SI))
1535 return eraseInstFromFunction(SI);
1536
1537 // Replace GEP indices if possible.
1538 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI))
1539 return replaceOperand(SI, 1, NewGEPI);
1540
1541 // Don't hack volatile/ordered stores.
1542 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1543 if (!SI.isUnordered()) return nullptr;
1544
1545 // If the RHS is an alloca with a single use, zapify the store, making the
1546 // alloca dead.
1547 if (Ptr->hasOneUse()) {
1548 if (isa<AllocaInst>(Ptr))
1549 return eraseInstFromFunction(SI);
1551 if (isa<AllocaInst>(GEP->getOperand(0))) {
1552 if (GEP->getOperand(0)->hasOneUse())
1553 return eraseInstFromFunction(SI);
1554 }
1555 }
1556 }
1557
1558 // If we have a store to a location which is known constant, we can conclude
1559 // that the store must be storing the constant value (else the memory
1560 // wouldn't be constant), and this must be a noop.
1561 if (!isModSet(AA->getModRefInfoMask(Ptr)))
1562 return eraseInstFromFunction(SI);
1563
1564 // Do really simple DSE, to catch cases where there are several consecutive
1565 // stores to the same location, separated by a few arithmetic operations. This
1566 // situation often occurs with bitfield accesses.
1568 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1569 --ScanInsts) {
1570 --BBI;
1571 // Don't count pseudo probes, lest they affect codegen.
1572 if (isa<PseudoProbeInst>(BBI)) {
1573 ScanInsts++;
1574 continue;
1575 }
1576
1577 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1578 // Prev store isn't volatile, and stores to the same location?
1579 if (PrevSI->isUnordered() &&
1580 equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&
1581 PrevSI->getValueOperand()->getType() ==
1582 SI.getValueOperand()->getType()) {
1583 ++NumDeadStore;
1584 // Manually add back the original store to the worklist now, so it will
1585 // be processed after the operands of the removed store, as this may
1586 // expose additional DSE opportunities.
1587 Worklist.push(&SI);
1588 eraseInstFromFunction(*PrevSI);
1589 return nullptr;
1590 }
1591 break;
1592 }
1593
1594 // If this is a load, we have to stop. However, if the loaded value is from
1595 // the pointer we're loading and is producing the pointer we're storing,
1596 // then *this* store is dead (X = load P; store X -> P).
1597 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1598 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1599 assert(SI.isUnordered() && "can't eliminate ordering operation");
1600 return eraseInstFromFunction(SI);
1601 }
1602
1603 // Otherwise, this is a load from some other location. Stores before it
1604 // may not be dead.
1605 break;
1606 }
1607
1608 // Don't skip over loads, throws or things that can modify memory.
1609 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1610 break;
1611 }
1612
1613 // store X, null -> turns into 'unreachable' in SimplifyCFG
1614 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1616 if (!isa<PoisonValue>(Val))
1617 return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
1618 return nullptr; // Do not modify these!
1619 }
1620
1621 // This is a non-terminator unreachable marker. Don't remove it.
1622 if (isa<UndefValue>(Ptr)) {
1623 // Remove guaranteed-to-transfer instructions before the marker.
1625
1626 // Remove all instructions after the marker and handle dead blocks this
1627 // implies.
1629 handleUnreachableFrom(SI.getNextNode(), Worklist);
1631 return nullptr;
1632 }
1633
1634 // store undef, Ptr -> noop
1635 // Non-byte-sized stores of undef (e.g. i12) are padded with zeros, so we
1636 // can't remove the instruction.
1637 // FIXME: It's incorrect to overwrite poison with undef
1638 if (isa<PoisonValue>(Val) ||
1639 (isa<UndefValue>(Val) && DL.typeSizeEqualsStoreSize(Val->getType())))
1640 return eraseInstFromFunction(SI);
1641
1642 // Replace byte constants with integer constants in stores.
1643 Constant *C;
1644 if (Val->getType()->isByteOrByteVectorTy() && match(Val, m_ImmConstant(C)))
1645 return replaceOperand(
1646 SI, 0,
1648
1649 if (!NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
1650 if (Value *V = simplifyNonNullOperand(Ptr, /*UseProvenance=*/true))
1651 return replaceOperand(SI, 1, V);
1652
1653 // store(ptr1, llvm.protected.field.ptr(ptr2)) ->
1654 // store(llvm.ptrauth.sign(ptr1), ptr2)
1655 if (isa<PointerType>(Val->getType())) {
1656 if (auto *II = dyn_cast<IntrinsicInst>(Ptr)) {
1657 if (II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1658 std::vector<OperandBundleDef> DSBundle;
1659 if (auto Bundle =
1660 II->getOperandBundle(LLVMContext::OB_deactivation_symbol))
1661 DSBundle.push_back(OperandBundleDef(
1662 "deactivation-symbol", cast<GlobalValue>(Bundle->Inputs[0])));
1663
1665 Builder.SetInsertPoint(&SI);
1666
1668 F.getParent(), Intrinsic::ptrauth_sign, {});
1669 auto *ValInt = Builder.CreatePtrToInt(Val, Builder.getInt64Ty());
1670 Value *Sign = Builder.CreateCall(
1671 SignIntr,
1672 {ValInt, Builder.getInt32(/*AArch64PACKey::DA*/ 2),
1673 II->getOperand(1)},
1674 DSBundle);
1675 Sign = Builder.CreateIntToPtr(Sign, Builder.getPtrTy());
1676
1677 replaceOperand(SI, 0, Sign);
1678 replaceOperand(SI, 1, II->getOperand(0));
1679 return &SI;
1680 }
1681 }
1682 }
1683
1684 return nullptr;
1685}
1686
1687/// Try to transform:
1688/// if () { *P = v1; } else { *P = v2 }
1689/// or:
1690/// *P = v1; if () { *P = v2; }
1691/// into a phi node with a store in the successor.
1693 if (!SI.isUnordered())
1694 return false; // This code has not been audited for volatile/ordered case.
1695
1696 // Check if the successor block has exactly 2 incoming edges.
1697 BasicBlock *StoreBB = SI.getParent();
1698 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1699 if (!DestBB->hasNPredecessors(2))
1700 return false;
1701
1702 // Capture the other block (the block that doesn't contain our store).
1703 pred_iterator PredIter = pred_begin(DestBB);
1704 if (*PredIter == StoreBB)
1705 ++PredIter;
1706 BasicBlock *OtherBB = *PredIter;
1707
1708 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1709 // for example, if SI is in an infinite loop.
1710 if (StoreBB == DestBB || OtherBB == DestBB)
1711 return false;
1712
1713 // Verify that the other block is not empty apart from the terminator.
1714 BasicBlock::iterator BBI(OtherBB->getTerminator());
1715 if (BBI == OtherBB->begin())
1716 return false;
1717
1718 auto OtherStoreIsMergeable = [&](StoreInst *OtherStore) -> bool {
1719 if (!OtherStore ||
1720 OtherStore->getPointerOperand() != SI.getPointerOperand())
1721 return false;
1722
1723 auto *SIVTy = SI.getValueOperand()->getType();
1724 auto *OSVTy = OtherStore->getValueOperand()->getType();
1725 if (!CastInst::isBitOrNoopPointerCastable(OSVTy, SIVTy, DL) ||
1726 !SI.hasSameSpecialState(OtherStore))
1727 return false;
1728
1729 // Elementwise atomic stores behave as one atomic store per vector
1730 // element. Do not split or merge those atomic accesses by changing the
1731 // element size.
1732 return !SI.isElementwise() ||
1733 DL.getTypeStoreSize(SIVTy->getScalarType()) ==
1734 DL.getTypeStoreSize(OSVTy->getScalarType());
1735 };
1736
1737 // If the other block ends in an unconditional branch, check for the 'if then
1738 // else' case. There is an instruction before the branch.
1739 StoreInst *OtherStore = nullptr;
1740 if (isa<UncondBrInst>(BBI)) {
1741 --BBI;
1742 // Skip over pseudo probes.
1743 while (isa<PseudoProbeInst>(BBI)) {
1744 if (BBI==OtherBB->begin())
1745 return false;
1746 --BBI;
1747 }
1748 // If this isn't a store, isn't a store to the same location, or is not the
1749 // right kind of store, bail out.
1750 OtherStore = dyn_cast<StoreInst>(BBI);
1751 if (!OtherStoreIsMergeable(OtherStore))
1752 return false;
1753 } else if (auto *OtherBr = dyn_cast<CondBrInst>(BBI)) {
1754 // Otherwise, the other block ended with a conditional branch. If one of the
1755 // destinations is StoreBB, then we have the if/then case.
1756 if (OtherBr->getSuccessor(0) != StoreBB &&
1757 OtherBr->getSuccessor(1) != StoreBB)
1758 return false;
1759
1760 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1761 // if/then triangle. See if there is a store to the same ptr as SI that
1762 // lives in OtherBB.
1763 for (;; --BBI) {
1764 // Check to see if we find the matching store.
1765 OtherStore = dyn_cast<StoreInst>(BBI);
1766 if (OtherStoreIsMergeable(OtherStore))
1767 break;
1768
1769 // If we find something that may be using or overwriting the stored
1770 // value, or if we run out of instructions, we can't do the transform.
1771 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1772 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1773 return false;
1774 }
1775
1776 // In order to eliminate the store in OtherBr, we have to make sure nothing
1777 // reads or overwrites the stored value in StoreBB.
1778 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1779 // FIXME: This should really be AA driven.
1780 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1781 return false;
1782 }
1783 } else
1784 return false;
1785
1786 // Insert a PHI node now if we need it.
1787 Value *MergedVal = OtherStore->getValueOperand();
1788 // The debug locations of the original instructions might differ. Merge them.
1789 DebugLoc MergedLoc =
1790 DebugLoc::getMergedLocation(SI.getDebugLoc(), OtherStore->getDebugLoc());
1791 if (MergedVal != SI.getValueOperand()) {
1792 PHINode *PN =
1793 PHINode::Create(SI.getValueOperand()->getType(), 2, "storemerge");
1794 PN->addIncoming(SI.getValueOperand(), SI.getParent());
1795 Builder.SetInsertPoint(OtherStore);
1796 PN->addIncoming(Builder.CreateBitOrPointerCast(MergedVal, PN->getType()),
1797 OtherBB);
1798 MergedVal = InsertNewInstBefore(PN, DestBB->begin());
1799 PN->setDebugLoc(MergedLoc);
1800 }
1801
1802 // Advance to a place where it is safe to insert the new store and insert it.
1803 BBI = DestBB->getFirstInsertionPt();
1804 StoreInst *NewSI =
1805 new StoreInst(MergedVal, SI.getOperand(1), SI.getProperties());
1806 InsertNewInstBefore(NewSI, BBI);
1807 NewSI->setDebugLoc(MergedLoc);
1808 NewSI->mergeDIAssignID({&SI, OtherStore});
1809
1810 // If the two stores had AA tags, merge them.
1811 AAMDNodes AATags = SI.getAAMetadata();
1812 if (AATags)
1813 NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));
1814
1815 // If the two stores had access groups, intersect them.
1816 NewSI->setMetadata(LLVMContext::MD_access_group,
1817 intersectAccessGroups(&SI, OtherStore));
1818
1819 // The merged store stands for both, so it requests the PC sections of either.
1820 NewSI->setMetadata(LLVMContext::MD_pcsections,
1822 SI.getMetadata(LLVMContext::MD_pcsections),
1823 OtherStore->getMetadata(LLVMContext::MD_pcsections)));
1824
1825 // Nuke the old stores.
1827 eraseInstFromFunction(*OtherStore);
1828 return true;
1829}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void addToWorklist(Instruction &I, SmallVector< Instruction *, 4 > &Worklist)
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides internal interfaces used to implement the InstCombine.
static StoreInst * combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
static Instruction * combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &Load)
Combine loads to match the type of their uses' value after looking through intervening bitcasts.
static Instruction * replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, Instruction &MemI)
static Instruction * simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI, DominatorTree &DT)
static bool canSimplifyNullStoreOrGEP(StoreInst &SI)
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op)
static bool isSupportedAtomicType(Type *Ty)
static bool isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete, unsigned MaxUsers)
isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived) pointer to an alloca.
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL)
Returns true if V is dereferenceable for size of alloca.
static Instruction * unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI)
static Instruction * foldLoadOfSelectOfConstPtrs(LoadInst &LI, const DataLayout &DL)
load (gep (select Cond, TrueC, FalseC), IndexC) --> select Cond, (load TrueC'), (load FalseC') Only d...
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI)
static Value * likeBitCastFromVector(InstCombinerImpl &IC, Value *V)
Look for extractelement/insertvalue sequence that acts like a bitcast.
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
This file provides the interface for the instcombine pass implementation.
@ RecursionLimit
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
SmallVector< MachineOperand, 4 > Cond
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
#define P(N)
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
PointerType * getType() const
Overload to return most specific pointer type.
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
unsigned getAddressSpace() const
Return the address space for the allocation.
LLVM_ABI std::optional< TypeSize > getAllocationSize(const DataLayout &DL) const
Get allocation size in bytes.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
const Value * getArraySize() const
Get the number of elements allocated.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:439
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI InstListType::const_iterator getFirstNonPHIOrPseudoProbe() const
Returns an iterator to the first instruction in this block that is not a PHINode or a pseudo operatio...
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
static LLVM_ABI bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
static LLVM_ABI Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
A debug info location.
Definition DebugLoc.h:126
static LLVM_ABI DebugLoc getMergedLocation(DebugLoc LocA, DebugLoc LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
Definition DebugLoc.cpp:186
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
LLVM_ABI bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Type * getSourceElementType() const
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition IRBuilder.h:1886
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2802
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2021
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
LLVM_ABI Value * CreateTypeSize(Type *Ty, TypeSize Size)
Create an expression which evaluates to the number of units in Size at runtime.
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition IRBuilder.h:2399
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition IRBuilder.h:1959
Value * CreateInBoundsPtrAdd(Value *Ptr, Value *Offset, const Twine &Name="")
Definition IRBuilder.h:2105
LLVM_ABI CallInst * CreateMemTransferInst(Intrinsic::ID IntrID, Value *Dst, MaybeAlign DstAlign, Value *Src, MaybeAlign SrcAlign, Value *Size, bool isVolatile=false, const AAMDNodes &AAInfo=AAMDNodes())
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * visitLoadInst(LoadInst &LI)
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitStoreInst(StoreInst &SI)
const InstCombineCLOptions & CLOpts
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; }...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
bool removeInstructionsBeforeUnreachable(Instruction &I)
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitAllocaInst(AllocaInst &AI)
SimplifyQuery SQ
const DataLayout & getDataLayout() const
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
AssumptionCache & AC
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
void computeKnownBits(const Value *V, KnownBits &Known, const Instruction *CtxI, unsigned Depth=0) const
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI bool isLifetimeStartOrEnd() const LLVM_READONLY
Return true if the instruction is a llvm.lifetime.start or llvm.lifetime.end marker.
LLVM_ABI void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI void moveBefore(InstListType::iterator InsertPos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Value * getPointerOperand()
bool isAtomic() const
Return true if this load has an atomic ordering.
bool isUnordered() const
LoadStoreInstProperties getProperties() const
Returns the properties of this load instruction.
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
Metadata node.
Definition Metadata.h:1087
static LLVM_ABI MDNode * getMergedPCSectionsMetadata(MDNode *A, MDNode *B)
Merge !pcsections of two merged instructions: the result requests every section that either requests.
This class wraps the llvm.memcpy/memmove intrinsics.
static constexpr const unsigned PoisonGeneratingIDs[]
Metadata IDs that may generate poison.
Definition Metadata.h:147
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Value * getValueOperand()
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getZero()
Definition TypeSize.h:358
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:295
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
bool isByteOrByteVectorTy() const
Return true if this is a byte type or a vector of byte types.
Definition Type.h:243
static LLVM_ABI Type * getIntFromByteType(Type *)
Returns an integer (vector of integer) type with the same size of a byte of the given byte (vector of...
Definition Type.cpp:302
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition Type.h:202
LLVM_ABI bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
Definition Type.cpp:61
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
bool match(Val *V, const Pattern &P)
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
LLVM_ABI bool isAvailable()
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
@ Known
Known to have no common set bits.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1607
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition Local.cpp:3194
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition Loads.cpp:555
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2493
LLVM_ABI Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3185
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:457
OperandBundleDefT< Value * > OperandBundleDef
Definition AutoUpgrade.h:35
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
PredIterator< BasicBlock, Value::user_iterator > pred_iterator
Definition CFG.h:93
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:247
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
LLVM_ABI Constant * ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, APInt Offset, const DataLayout &DL)
Return the value that a load from C with offset Offset would produce if it is constant and determinab...
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39