LLVM 24.0.0git
InstCombinePHI.cpp
Go to the documentation of this file.
1//===- InstCombinePHI.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 visitPHINode function.
10//
11//===----------------------------------------------------------------------===//
12
13#include "InstCombineInternal.h"
14#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/Statistic.h"
22#include <optional>
23
24using namespace llvm;
25using namespace llvm::PatternMatch;
26
27#define DEBUG_TYPE "instcombine"
28
29STATISTIC(NumPHIsOfInsertValues,
30 "Number of phi-of-insertvalue turned into insertvalue-of-phis");
31STATISTIC(NumPHIsOfExtractValues,
32 "Number of phi-of-extractvalue turned into extractvalue-of-phi");
33STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
34
35/// The PHI arguments will be folded into a single operation with a PHI node
36/// as input. The debug location of the single operation will be the merged
37/// locations of the original PHI node arguments.
39 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
40 Inst->setDebugLoc(FirstInst->getDebugLoc());
41 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
42 // will be inefficient.
43 assert(!isa<CallInst>(Inst));
44
45 for (Value *V : drop_begin(PN.incoming_values())) {
46 auto *I = cast<Instruction>(V);
47 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
48 }
49}
50
51/// If the phi is within a phi web, which is formed by the def-use chain
52/// of phis and all the phis in the web are only used in the other phis.
53/// In this case, these phis are dead and we will remove all of them.
57 Stack.push_back(&PN);
58 Visited.insert(&PN);
59 while (!Stack.empty()) {
60 PHINode *Phi = Stack.pop_back_val();
61 for (User *Use : Phi->users()) {
62 if (PHINode *PhiUse = dyn_cast<PHINode>(Use)) {
63 if (!Visited.insert(PhiUse).second)
64 continue;
65 // Early stop if the set of PHIs is large
66 if (Visited.size() >= 16)
67 return false;
68 Stack.push_back(PhiUse);
69 } else
70 return false;
71 }
72 }
73 for (PHINode *Phi : Visited)
74 replaceInstUsesWith(*Phi, PoisonValue::get(Phi->getType()));
75 for (PHINode *Phi : Visited)
77 return true;
78}
79
80// Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
81// If there is an existing pointer typed PHI that produces the same value as PN,
82// replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
83// PHI node:
84//
85// Case-1:
86// bb1:
87// int_init = PtrToInt(ptr_init)
88// br label %bb2
89// bb2:
90// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
91// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
92// ptr_val2 = IntToPtr(int_val)
93// ...
94// use(ptr_val2)
95// ptr_val_inc = ...
96// inc_val_inc = PtrToInt(ptr_val_inc)
97//
98// ==>
99// bb1:
100// br label %bb2
101// bb2:
102// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
103// ...
104// use(ptr_val)
105// ptr_val_inc = ...
106//
107// Case-2:
108// bb1:
109// int_ptr = BitCast(ptr_ptr)
110// int_init = Load(int_ptr)
111// br label %bb2
112// bb2:
113// int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
114// ptr_val2 = IntToPtr(int_val)
115// ...
116// use(ptr_val2)
117// ptr_val_inc = ...
118// inc_val_inc = PtrToInt(ptr_val_inc)
119// ==>
120// bb1:
121// ptr_init = Load(ptr_ptr)
122// br label %bb2
123// bb2:
124// ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
125// ...
126// use(ptr_val)
127// ptr_val_inc = ...
128// ...
129//
131 if (!PN.getType()->isIntegerTy())
132 return false;
133 if (!PN.hasOneUse())
134 return false;
135
136 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
137 if (!IntToPtr)
138 return false;
139
140 // Check if the pointer is actually used as pointer:
141 auto HasPointerUse = [](Instruction *IIP) {
142 for (User *U : IIP->users()) {
143 Value *Ptr = nullptr;
144 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
145 Ptr = LoadI->getPointerOperand();
146 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
147 Ptr = SI->getPointerOperand();
149 Ptr = GI->getPointerOperand();
150 }
151
152 if (Ptr && Ptr == IIP)
153 return true;
154 }
155 return false;
156 };
157
158 if (!HasPointerUse(IntToPtr))
159 return false;
160
161 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
162 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
163 return false;
164
165 SmallVector<Value *, 4> AvailablePtrVals;
166 for (auto Incoming : zip(PN.blocks(), PN.incoming_values())) {
167 BasicBlock *BB = std::get<0>(Incoming);
168 Value *Arg = std::get<1>(Incoming);
169
170 // Arg could be a constant, constant expr, etc., which we don't cover here.
171 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
172 return false;
173
174 // First look backward:
175 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
176 if (PI->getOperand(0)->getType() == IntToPtr->getType()) {
177 AvailablePtrVals.emplace_back(PI->getOperand(0));
178 continue;
179 }
180 }
181
182 // Next look forward:
183 Value *ArgIntToPtr = nullptr;
184 for (User *U : Arg->users()) {
185 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
186 (DT.dominates(cast<Instruction>(U), BB) ||
187 cast<Instruction>(U)->getParent() == BB)) {
188 ArgIntToPtr = U;
189 break;
190 }
191 }
192
193 if (ArgIntToPtr) {
194 AvailablePtrVals.emplace_back(ArgIntToPtr);
195 continue;
196 }
197
198 // If Arg is defined by a PHI, allow it. This will also create
199 // more opportunities iteratively.
200 if (isa<PHINode>(Arg)) {
201 AvailablePtrVals.emplace_back(Arg);
202 continue;
203 }
204
205 // For a single use integer load:
206 auto *LoadI = dyn_cast<LoadInst>(Arg);
207 if (!LoadI)
208 return false;
209
210 if (!LoadI->hasOneUse())
211 return false;
212
213 // Push the integer typed Load instruction into the available
214 // value set, and fix it up later when the pointer typed PHI
215 // is synthesized.
216 AvailablePtrVals.emplace_back(LoadI);
217 }
218
219 // Now search for a matching PHI
220 auto *BB = PN.getParent();
221 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
222 "Not enough available ptr typed incoming values");
223 PHINode *MatchingPtrPHI = nullptr;
224 unsigned NumPhis = 0;
225 for (PHINode &PtrPHI : BB->phis()) {
226 // FIXME: consider handling this in AggressiveInstCombine
227 if (NumPhis++ > CLOpts.max_num_phis)
228 return false;
229 if (&PtrPHI == &PN || PtrPHI.getType() != IntToPtr->getType())
230 continue;
231 if (any_of(zip(PN.blocks(), AvailablePtrVals),
232 [&](const auto &BlockAndValue) {
233 BasicBlock *BB = std::get<0>(BlockAndValue);
234 Value *V = std::get<1>(BlockAndValue);
235 return PtrPHI.getIncomingValueForBlock(BB) != V;
236 }))
237 continue;
238 MatchingPtrPHI = &PtrPHI;
239 break;
240 }
241
242 if (MatchingPtrPHI) {
243 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
244 "Phi's Type does not match with IntToPtr");
245 // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
246 // to make sure another transform can't undo it in the meantime.
247 replaceInstUsesWith(*IntToPtr, MatchingPtrPHI);
248 eraseInstFromFunction(*IntToPtr);
250 return true;
251 }
252
253 // If it requires a conversion for every PHI operand, do not do it.
254 if (all_of(AvailablePtrVals, [&](Value *V) {
255 return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
256 }))
257 return false;
258
259 // If any of the operand that requires casting is a terminator
260 // instruction, do not do it. Similarly, do not do the transform if the value
261 // is PHI in a block with no insertion point, for example, a catchswitch
262 // block, since we will not be able to insert a cast after the PHI.
263 if (any_of(AvailablePtrVals, [&](Value *V) {
264 if (V->getType() == IntToPtr->getType())
265 return false;
266 auto *Inst = dyn_cast<Instruction>(V);
267 if (!Inst)
268 return false;
269 if (Inst->isTerminator())
270 return true;
271 auto *BB = Inst->getParent();
272 if (isa<PHINode>(Inst) && !BB->hasInsertionPt())
273 return true;
274 return false;
275 }))
276 return false;
277
278 PHINode *NewPtrPHI = PHINode::Create(
279 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
280
281 InsertNewInstBefore(NewPtrPHI, PN.getIterator());
283 for (auto Incoming : zip(PN.blocks(), AvailablePtrVals)) {
284 auto *IncomingBB = std::get<0>(Incoming);
285 auto *IncomingVal = std::get<1>(Incoming);
286
287 if (IncomingVal->getType() == IntToPtr->getType()) {
288 NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
289 continue;
290 }
291
292#ifndef NDEBUG
293 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
294 assert((isa<PHINode>(IncomingVal) ||
295 IncomingVal->getType()->isPointerTy() ||
296 (LoadI && LoadI->hasOneUse())) &&
297 "Can not replace LoadInst with multiple uses");
298#endif
299 // Need to insert a BitCast.
300 // For an integer Load instruction with a single use, the load + IntToPtr
301 // cast will be simplified into a pointer load:
302 // %v = load i64, i64* %a.ip, align 8
303 // %v.cast = inttoptr i64 %v to float **
304 // ==>
305 // %v.ptrp = bitcast i64 * %a.ip to float **
306 // %v.cast = load float *, float ** %v.ptrp, align 8
307 Instruction *&CI = Casts[IncomingVal];
308 if (!CI) {
309 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
310 IncomingVal->getName() + ".ptr");
311 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
312 BasicBlock::iterator InsertPos(IncomingI);
313 InsertPos++;
314 BasicBlock *BB = IncomingI->getParent();
315 if (isa<PHINode>(IncomingI))
316 InsertPos = BB->getFirstInsertionPt();
317 assert(InsertPos != BB->end() && "should have checked above");
318 InsertNewInstBefore(CI, InsertPos);
319 } else {
320 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
321 InsertNewInstBefore(CI, InsertBB->getFirstInsertionPt());
322 }
323 }
324 NewPtrPHI->addIncoming(CI, IncomingBB);
325 }
326
327 // Explicitly replace the inttoptr (rather than inserting a ptrtoint) here,
328 // to make sure another transform can't undo it in the meantime.
329 replaceInstUsesWith(*IntToPtr, NewPtrPHI);
330 eraseInstFromFunction(*IntToPtr);
332 return true;
333}
334
335// Remove RoundTrip IntToPtr/PtrToInt Cast on PHI-Operand and
336// fold Phi-operand to bitcast.
338 // convert ptr2int ( phi[ int2ptr(ptr2int(x))] ) --> ptr2int ( phi [ x ] )
339 // Make sure all uses of phi are ptr2int.
341 return nullptr;
342
343 // Iterating over all operands to check presence of target pointers for
344 // optimization.
345 bool OperandWithRoundTripCast = false;
346 for (unsigned OpNum = 0; OpNum != PN.getNumIncomingValues(); ++OpNum) {
347 if (auto *NewOp =
348 simplifyIntToPtrRoundTripCast(PN.getIncomingValue(OpNum))) {
349 replaceOperand(PN, OpNum, NewOp);
350 OperandWithRoundTripCast = true;
351 }
352 }
353 if (!OperandWithRoundTripCast)
354 return nullptr;
355 return &PN;
356}
357
358/// If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)],
359/// turn this into a phi[a,c] and phi[b,d] and a single insertvalue.
362 auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0));
363
364 // Scan to see if all operands are `insertvalue`'s with the same indices,
365 // and all have a single use.
366 for (Value *V : drop_begin(PN.incoming_values())) {
367 auto *I = dyn_cast<InsertValueInst>(V);
368 if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices())
369 return nullptr;
370 }
371
372 // For each operand of an `insertvalue`
373 std::array<PHINode *, 2> NewOperands;
374 for (int OpIdx : {0, 1}) {
375 auto *&NewOperand = NewOperands[OpIdx];
376 // Create a new PHI node to receive the values the operand has in each
377 // incoming basic block.
378 NewOperand = PHINode::Create(
379 FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(),
380 FirstIVI->getOperand(OpIdx)->getName() + ".pn");
381 // And populate each operand's PHI with said values.
382 for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
383 NewOperand->addIncoming(
384 cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx),
385 std::get<0>(Incoming));
386 InsertNewInstBefore(NewOperand, PN.getIterator());
387 }
388
389 // And finally, create `insertvalue` over the newly-formed PHI nodes.
390 auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1],
391 FirstIVI->getIndices(), PN.getName());
392
393 PHIArgMergedDebugLoc(NewIVI, PN);
394 ++NumPHIsOfInsertValues;
395 return NewIVI;
396}
397
398/// If we have something like phi [extractvalue(a,0), extractvalue(b,0)],
399/// turn this into a phi[a,b] and a single extractvalue.
402 auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0));
403
404 // Scan to see if all operands are `extractvalue`'s with the same indices,
405 // and all have a single use.
406 for (Value *V : drop_begin(PN.incoming_values())) {
407 auto *I = dyn_cast<ExtractValueInst>(V);
408 if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() ||
409 I->getAggregateOperand()->getType() !=
410 FirstEVI->getAggregateOperand()->getType())
411 return nullptr;
412 }
413
414 // Create a new PHI node to receive the values the aggregate operand has
415 // in each incoming basic block.
416 auto *NewAggregateOperand = PHINode::Create(
417 FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(),
418 FirstEVI->getAggregateOperand()->getName() + ".pn");
419 // And populate the PHI with said values.
420 for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
421 NewAggregateOperand->addIncoming(
422 cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(),
423 std::get<0>(Incoming));
424 InsertNewInstBefore(NewAggregateOperand, PN.getIterator());
425
426 // And finally, create `extractvalue` over the newly-formed PHI nodes.
427 auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand,
428 FirstEVI->getIndices(), PN.getName());
429
430 PHIArgMergedDebugLoc(NewEVI, PN);
431 ++NumPHIsOfExtractValues;
432 return NewEVI;
433}
434
435/// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
436/// adds all have a single user, turn this into a phi and a single binop.
439 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
440 unsigned Opc = FirstInst->getOpcode();
441 Value *LHSVal = FirstInst->getOperand(0);
442 Value *RHSVal = FirstInst->getOperand(1);
443
444 Type *LHSType = LHSVal->getType();
445 Type *RHSType = RHSVal->getType();
446
447 // Scan to see if all operands are the same opcode, and all have one user.
448 for (Value *V : drop_begin(PN.incoming_values())) {
450 if (!I || I->getOpcode() != Opc || !I->hasOneUser() ||
451 // Verify type of the LHS matches so we don't fold cmp's of different
452 // types.
453 I->getOperand(0)->getType() != LHSType ||
454 I->getOperand(1)->getType() != RHSType)
455 return nullptr;
456
457 // If they are CmpInst instructions, check their predicates
458 if (CmpInst *CI = dyn_cast<CmpInst>(I))
459 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
460 return nullptr;
461
462 // Keep track of which operand needs a phi node.
463 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
464 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
465 }
466
467 // If both LHS and RHS would need a PHI, don't do this transformation,
468 // because it would increase the number of PHIs entering the block,
469 // which leads to higher register pressure. This is especially
470 // bad when the PHIs are in the header of a loop.
471 if (!LHSVal && !RHSVal)
472 return nullptr;
473
474 // Otherwise, this is safe to transform!
475
476 Value *InLHS = FirstInst->getOperand(0);
477 Value *InRHS = FirstInst->getOperand(1);
478 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
479 if (!LHSVal) {
480 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
481 FirstInst->getOperand(0)->getName() + ".pn");
482 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
483 InsertNewInstBefore(NewLHS, PN.getIterator());
484 LHSVal = NewLHS;
485 }
486
487 if (!RHSVal) {
488 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
489 FirstInst->getOperand(1)->getName() + ".pn");
490 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
491 InsertNewInstBefore(NewRHS, PN.getIterator());
492 RHSVal = NewRHS;
493 }
494
495 // Add all operands to the new PHIs.
496 if (NewLHS || NewRHS) {
497 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
498 BasicBlock *InBB = std::get<0>(Incoming);
499 Value *InVal = std::get<1>(Incoming);
500 Instruction *InInst = cast<Instruction>(InVal);
501 if (NewLHS) {
502 Value *NewInLHS = InInst->getOperand(0);
503 NewLHS->addIncoming(NewInLHS, InBB);
504 }
505 if (NewRHS) {
506 Value *NewInRHS = InInst->getOperand(1);
507 NewRHS->addIncoming(NewInRHS, InBB);
508 }
509 }
510 }
511
512 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
513 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
514 LHSVal, RHSVal);
515 PHIArgMergedDebugLoc(NewCI, PN);
516 return NewCI;
517 }
518
519 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
520 BinaryOperator *NewBinOp =
521 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
522
523 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
524
525 for (Value *V : drop_begin(PN.incoming_values()))
526 NewBinOp->andIRFlags(V);
527
528 PHIArgMergedDebugLoc(NewBinOp, PN);
529 return NewBinOp;
530}
531
534
535 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
536 FirstInst->op_end());
537 // This is true if all GEP bases are allocas and if all indices into them are
538 // constants.
539 bool AllBasePointersAreAllocas = true;
540
541 // We don't want to replace this phi if the replacement would require
542 // more than one phi, which leads to higher register pressure. This is
543 // especially bad when the PHIs are in the header of a loop.
544 bool NeededPhi = false;
545
546 // Remember flags of the first phi-operand getelementptr.
547 GEPNoWrapFlags NW = FirstInst->getNoWrapFlags();
548
549 // Scan to see if all operands are the same opcode, and all have one user.
550 for (Value *V : drop_begin(PN.incoming_values())) {
552 if (!GEP || !GEP->hasOneUser() ||
553 GEP->getSourceElementType() != FirstInst->getSourceElementType() ||
554 GEP->getNumOperands() != FirstInst->getNumOperands())
555 return nullptr;
556
557 NW &= GEP->getNoWrapFlags();
558
559 // Keep track of whether or not all GEPs are of alloca pointers.
560 if (AllBasePointersAreAllocas &&
561 (!isa<AllocaInst>(GEP->getOperand(0)) ||
562 !GEP->hasAllConstantIndices()))
563 AllBasePointersAreAllocas = false;
564
565 // Compare the operand lists.
566 for (unsigned Op = 0, E = FirstInst->getNumOperands(); Op != E; ++Op) {
567 if (FirstInst->getOperand(Op) == GEP->getOperand(Op))
568 continue;
569
570 // Don't merge two GEPs when two operands differ (introducing phi nodes)
571 // if one of the PHIs has a constant for the index. The index may be
572 // substantially cheaper to compute for the constants, so making it a
573 // variable index could pessimize the path. This also handles the case
574 // for struct indices, which must always be constant.
575 if (isa<Constant>(FirstInst->getOperand(Op)) ||
576 isa<Constant>(GEP->getOperand(Op)))
577 return nullptr;
578
579 if (FirstInst->getOperand(Op)->getType() !=
580 GEP->getOperand(Op)->getType())
581 return nullptr;
582
583 // If we already needed a PHI for an earlier operand, and another operand
584 // also requires a PHI, we'd be introducing more PHIs than we're
585 // eliminating, which increases register pressure on entry to the PHI's
586 // block.
587 if (NeededPhi)
588 return nullptr;
589
590 FixedOperands[Op] = nullptr; // Needs a PHI.
591 NeededPhi = true;
592 }
593 }
594
595 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
596 // bother doing this transformation. At best, this will just save a bit of
597 // offset calculation, but all the predecessors will have to materialize the
598 // stack address into a register anyway. We'd actually rather *clone* the
599 // load up into the predecessors so that we have a load of a gep of an alloca,
600 // which can usually all be folded into the load.
601 if (AllBasePointersAreAllocas)
602 return nullptr;
603
604 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
605 // that is variable.
606 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
607
608 bool HasAnyPHIs = false;
609 for (unsigned I = 0, E = FixedOperands.size(); I != E; ++I) {
610 if (FixedOperands[I])
611 continue; // operand doesn't need a phi.
612 Value *FirstOp = FirstInst->getOperand(I);
613 PHINode *NewPN =
614 PHINode::Create(FirstOp->getType(), E, FirstOp->getName() + ".pn");
615 InsertNewInstBefore(NewPN, PN.getIterator());
616
617 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
618 OperandPhis[I] = NewPN;
619 FixedOperands[I] = NewPN;
620 HasAnyPHIs = true;
621 }
622
623 // Add all operands to the new PHIs.
624 if (HasAnyPHIs) {
625 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
626 BasicBlock *InBB = std::get<0>(Incoming);
627 Value *InVal = std::get<1>(Incoming);
629
630 for (unsigned Op = 0, E = OperandPhis.size(); Op != E; ++Op)
631 if (PHINode *OpPhi = OperandPhis[Op])
632 OpPhi->addIncoming(InGEP->getOperand(Op), InBB);
633 }
634 }
635
636 Value *Base = FixedOperands[0];
637 GetElementPtrInst *NewGEP =
639 ArrayRef(FixedOperands).slice(1), NW);
640 PHIArgMergedDebugLoc(NewGEP, PN);
641 return NewGEP;
642}
643
644/// Return true if we know that it is safe to sink the load out of the block
645/// that defines it. This means that it must be obvious the value of the load is
646/// not changed from the point of the load to the end of the block it is in.
647///
648/// Finally, it is safe, but not profitable, to sink a load targeting a
649/// non-address-taken alloca. Doing so will cause us to not promote the alloca
650/// to a register.
652 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
653
654 for (++BBI; BBI != E; ++BBI)
655 if (BBI->mayWriteToMemory()) {
656 // Calls that only access inaccessible memory do not block sinking the
657 // load.
658 if (auto *CB = dyn_cast<CallBase>(BBI))
659 if (CB->onlyAccessesInaccessibleMemory())
660 continue;
661 return false;
662 }
663
664 // Check for non-address taken alloca. If not address-taken already, it isn't
665 // profitable to do this xform.
666 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
667 bool IsAddressTaken = false;
668 for (User *U : AI->users()) {
669 if (isa<LoadInst>(U)) continue;
670 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
671 // If storing TO the alloca, then the address isn't taken.
672 if (SI->getOperand(1) == AI) continue;
673 }
674 IsAddressTaken = true;
675 break;
676 }
677
678 if (!IsAddressTaken && AI->isStaticAlloca())
679 return false;
680 }
681
682 // If this load is a load from a GEP with a constant offset from an alloca,
683 // then we don't want to sink it. In its present form, it will be
684 // load [constant stack offset]. Sinking it will cause us to have to
685 // materialize the stack addresses in each predecessor in a register only to
686 // do a shared load from register in the successor.
687 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
688 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
689 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
690 return false;
691
692 return true;
693}
694
696 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
697
698 if (!canReplaceOperandWithVariable(FirstLI, 0))
699 return nullptr;
700
701 // FIXME: This is overconservative; this transform is allowed in some cases
702 // for atomic operations.
703 if (!FirstLI->isSimple())
704 return nullptr;
705
706 // When processing loads, we need to propagate the alignment and address
707 // space of the load.
708 Align LoadAlignment = FirstLI->getAlign();
709 const unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
710
711 // We can't sink the load if the loaded value could be modified between the
712 // load and the PHI.
713 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
715 return nullptr;
716
717 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
718 BasicBlock *InBB = std::get<0>(Incoming);
719 Value *InVal = std::get<1>(Incoming);
720 LoadInst *LI = dyn_cast<LoadInst>(InVal);
721 if (!LI || !LI->hasOneUser() || !LI->isSimple())
722 return nullptr;
723
724 // Make sure all arguments are the same type of operation.
725 if (LI->getPointerAddressSpace() != LoadAddrSpace)
726 return nullptr;
727
729 return nullptr;
730
731 // We can't sink the load if the loaded value could be modified between
732 // the load and the PHI.
733 if (LI->getParent() != InBB || !isSafeAndProfitableToSinkLoad(LI))
734 return nullptr;
735
736 LoadAlignment = std::min(LoadAlignment, LI->getAlign());
737 }
738
739 // Okay, they are all the same operation. Create a new PHI node of the
740 // correct type, and PHI together all of the LHS's of the instructions.
741 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
743 PN.getName()+".in");
744
745 Value *InVal = FirstLI->getOperand(0);
746 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
747 LoadInst *NewLI = new LoadInst(FirstLI->getType(), NewPN, "",
748 /*IsVolatile=*/false, LoadAlignment);
749 NewLI->copyMetadata(*FirstLI);
750
751 // Add all operands to the new PHI and combine TBAA metadata.
752 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
753 BasicBlock *BB = std::get<0>(Incoming);
754 Value *V = std::get<1>(Incoming);
755 LoadInst *LI = cast<LoadInst>(V);
756 combineMetadataForCSE(NewLI, LI, true);
757 Value *NewInVal = LI->getOperand(0);
758 if (NewInVal != InVal)
759 InVal = nullptr;
760 NewPN->addIncoming(NewInVal, BB);
761 }
762
763 if (InVal) {
764 // The new PHI unions all of the same values together. This is really
765 // common, so we handle it intelligently here for compile-time speed.
766 NewLI->setOperand(0, InVal);
767 delete NewPN;
768 } else {
769 InsertNewInstBefore(NewPN, PN.getIterator());
770 }
771
772 PHIArgMergedDebugLoc(NewLI, PN);
773 return NewLI;
774}
775
776/// TODO: This function could handle other cast types, but then it might
777/// require special-casing a cast from the 'i1' type. See the comment in
778/// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
780 // We cannot create a new instruction after the PHI if the terminator is an
781 // EHPad because there is no valid insertion point.
782 if (Phi.getParent()->getTerminator()->isEHPad())
783 return nullptr;
784
785 // Early exit for the common case of a phi with two operands. These are
786 // handled elsewhere. See the comment below where we check the count of zexts
787 // and constants for more details.
788 unsigned NumIncomingValues = Phi.getNumIncomingValues();
789 if (NumIncomingValues < 3)
790 return nullptr;
791
792 // Find the narrower type specified by the first zext.
793 Type *NarrowType = nullptr;
794 for (Value *V : Phi.incoming_values()) {
795 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
796 NarrowType = Zext->getSrcTy();
797 break;
798 }
799 }
800 if (!NarrowType)
801 return nullptr;
802
803 // Walk the phi operands checking that we only have zexts or constants that
804 // we can shrink for free. Store the new operands for the new phi.
805 SmallVector<Value *, 4> NewIncoming;
806 unsigned NumZexts = 0;
807 unsigned NumConsts = 0;
808 for (Value *V : Phi.incoming_values()) {
809 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
810 // All zexts must be identical and have one user.
811 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser())
812 return nullptr;
813 NewIncoming.push_back(Zext->getOperand(0));
814 NumZexts++;
815 } else if (auto *C = dyn_cast<Constant>(V)) {
816 // Make sure that constants can fit in the new type.
817 Constant *Trunc = getLosslessUnsignedTrunc(C, NarrowType, DL);
818 if (!Trunc)
819 return nullptr;
820 NewIncoming.push_back(Trunc);
821 NumConsts++;
822 } else {
823 // If it's not a cast or a constant, bail out.
824 return nullptr;
825 }
826 }
827
828 // The more common cases of a phi with no constant operands or just one
829 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
830 // respectively. foldOpIntoPhi() wants to do the opposite transform that is
831 // performed here. It tries to replicate a cast in the phi operand's basic
832 // block to expose other folding opportunities. Thus, InstCombine will
833 // infinite loop without this check.
834 if (NumConsts == 0 || NumZexts < 2)
835 return nullptr;
836
837 // All incoming values are zexts or constants that are safe to truncate.
838 // Create a new phi node of the narrow type, phi together all of the new
839 // operands, and zext the result back to the original type.
840 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
841 Phi.getName() + ".shrunk");
842 for (unsigned I = 0; I != NumIncomingValues; ++I)
843 NewPhi->addIncoming(NewIncoming[I], Phi.getIncomingBlock(I));
844
845 InsertNewInstBefore(NewPhi, Phi.getIterator());
846 auto *CI = CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
847
848 // We use a dropped location here because the new ZExt is necessarily a merge
849 // of ZExtInsts and at least one constant from incoming branches; the presence
850 // of the constant means we have no viable DebugLoc from that branch, and
851 // therefore we must use a dropped location.
852 CI->setDebugLoc(DebugLoc::getDropped());
853 return CI;
854}
855
856/// If all operands to a PHI node are the same "unary" operator and they all are
857/// only used by the PHI, PHI together their inputs, and do the operation once,
858/// to the result of the PHI.
860 // We cannot create a new instruction after the PHI if the terminator is an
861 // EHPad because there is no valid insertion point.
862 if (PN.getParent()->getTerminator()->isEHPad())
863 return nullptr;
864
866
867 if (isa<GetElementPtrInst>(FirstInst))
868 return foldPHIArgGEPIntoPHI(PN);
869 if (isa<LoadInst>(FirstInst))
870 return foldPHIArgLoadIntoPHI(PN);
871 if (isa<InsertValueInst>(FirstInst))
873 if (isa<ExtractValueInst>(FirstInst))
875
876 // Scan the instruction, looking for input operations that can be folded away.
877 // If all input operands to the phi are the same instruction (e.g. a cast from
878 // the same type or "+42") we can pull the operation through the PHI, reducing
879 // code size and simplifying code.
880 Constant *ConstantOp = nullptr;
881 Type *CastSrcTy = nullptr;
882
883 if (isa<CastInst>(FirstInst)) {
884 CastSrcTy = FirstInst->getOperand(0)->getType();
885
886 // Be careful about transforming integer PHIs. We don't want to pessimize
887 // the code by turning an i32 into an i1293.
888 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
889 if (!shouldChangeType(PN.getType(), CastSrcTy))
890 return nullptr;
891 }
892 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
893 // Can fold binop, compare or shift here if the RHS is a constant,
894 // otherwise call FoldPHIArgBinOpIntoPHI.
895 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
896 if (!ConstantOp)
897 return foldPHIArgBinOpIntoPHI(PN);
898 } else {
899 return nullptr; // Cannot fold this operation.
900 }
901
902 // Check to see if all arguments are the same operation.
903 for (Value *V : drop_begin(PN.incoming_values())) {
905 if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst))
906 return nullptr;
907 if (CastSrcTy) {
908 if (I->getOperand(0)->getType() != CastSrcTy)
909 return nullptr; // Cast operation must match.
910 } else if (I->getOperand(1) != ConstantOp) {
911 return nullptr;
912 }
913 }
914
915 // Okay, they are all the same operation. Create a new PHI node of the
916 // correct type, and PHI together all of the LHS's of the instructions.
917 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
919 PN.getName()+".in");
920
921 Value *InVal = FirstInst->getOperand(0);
922 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
923
924 // Add all operands to the new PHI.
925 for (auto Incoming : drop_begin(zip(PN.blocks(), PN.incoming_values()))) {
926 BasicBlock *BB = std::get<0>(Incoming);
927 Value *V = std::get<1>(Incoming);
928 Value *NewInVal = cast<Instruction>(V)->getOperand(0);
929 if (NewInVal != InVal)
930 InVal = nullptr;
931 NewPN->addIncoming(NewInVal, BB);
932 }
933
934 Value *PhiVal;
935 if (InVal) {
936 // The new PHI unions all of the same values together. This is really
937 // common, so we handle it intelligently here for compile-time speed.
938 PhiVal = InVal;
939 delete NewPN;
940 } else {
941 InsertNewInstBefore(NewPN, PN.getIterator());
942 PhiVal = NewPN;
943 }
944
945 // Insert and return the new operation.
946 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
947 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
948 PN.getType());
949 PHIArgMergedDebugLoc(NewCI, PN);
950 return NewCI;
951 }
952
953 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
954 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
955 BinOp->copyIRFlags(PN.getIncomingValue(0));
956
957 for (Value *V : drop_begin(PN.incoming_values()))
958 BinOp->andIRFlags(V);
959
960 PHIArgMergedDebugLoc(BinOp, PN);
961 return BinOp;
962 }
963
964 CmpInst *CIOp = cast<CmpInst>(FirstInst);
965 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
966 PhiVal, ConstantOp);
967 PHIArgMergedDebugLoc(NewCI, PN);
968 return NewCI;
969}
970
971/// Return true if this phi node is always equal to NonPhiInVal.
972/// This happens with mutually cyclic phi nodes like:
973/// z = some value; x = phi (y, z); y = phi (x, z)
974static bool PHIsEqualValue(PHINode *PN, Value *&NonPhiInVal,
975 SmallPtrSetImpl<PHINode *> &ValueEqualPHIs) {
976 // See if we already saw this PHI node.
977 if (!ValueEqualPHIs.insert(PN).second)
978 return true;
979
980 // Don't scan crazily complex things.
981 if (ValueEqualPHIs.size() >= 16)
982 return false;
983
984 // Scan the operands to see if they are either phi nodes or are equal to
985 // the value.
986 for (Value *Op : PN->incoming_values()) {
987 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
988 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs)) {
989 if (NonPhiInVal)
990 return false;
991 NonPhiInVal = OpPN;
992 }
993 } else if (Op != NonPhiInVal)
994 return false;
995 }
996
997 return true;
998}
999
1000/// Return an existing non-zero constant if this phi node has one, otherwise
1001/// return constant 1.
1003 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
1004 for (Value *V : PN.operands())
1005 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
1006 if (!ConstVA->isZero())
1007 return ConstVA;
1008 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
1009}
1010
1011namespace {
1012struct PHIUsageRecord {
1013 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
1014 unsigned Shift; // The amount shifted.
1015 Instruction *Inst; // The trunc instruction.
1016
1017 PHIUsageRecord(unsigned Pn, unsigned Sh, Instruction *User)
1018 : PHIId(Pn), Shift(Sh), Inst(User) {}
1019
1020 bool operator<(const PHIUsageRecord &RHS) const {
1021 if (PHIId < RHS.PHIId) return true;
1022 if (PHIId > RHS.PHIId) return false;
1023 if (Shift < RHS.Shift) return true;
1024 if (Shift > RHS.Shift) return false;
1025 return Inst->getType()->getPrimitiveSizeInBits() <
1027 }
1028};
1029
1030struct LoweredPHIRecord {
1031 PHINode *PN; // The PHI that was lowered.
1032 unsigned Shift; // The amount shifted.
1033 unsigned Width; // The width extracted.
1034
1035 LoweredPHIRecord(PHINode *Phi, unsigned Sh, Type *Ty)
1036 : PN(Phi), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
1037
1038 // Ctor form used by DenseMap.
1039 LoweredPHIRecord(PHINode *Phi, unsigned Sh) : PN(Phi), Shift(Sh), Width(0) {}
1040};
1041} // namespace
1042
1043template <> struct llvm::DenseMapInfo<LoweredPHIRecord> {
1044 static unsigned getHashValue(const LoweredPHIRecord &Val) {
1045 return DenseMapInfo<PHINode *>::getHashValue(Val.PN) ^ (Val.Shift >> 3) ^
1046 (Val.Width >> 3);
1047 }
1048 static bool isEqual(const LoweredPHIRecord &LHS,
1049 const LoweredPHIRecord &RHS) {
1050 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift && LHS.Width == RHS.Width;
1051 }
1052};
1053
1054/// This is an integer PHI and we know that it has an illegal type: see if it is
1055/// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
1056/// the various pieces being extracted. This sort of thing is introduced when
1057/// SROA promotes an aggregate to large integer values.
1058///
1059/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
1060/// inttoptr. We should produce new PHIs in the right type.
1061///
1063 // PHIUsers - Keep track of all of the truncated values extracted from a set
1064 // of PHIs, along with their offset. These are the things we want to rewrite.
1066
1067 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
1068 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
1069 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
1070 // check the uses of (to ensure they are all extracts).
1071 SmallVector<PHINode*, 8> PHIsToSlice;
1072 SmallPtrSet<PHINode*, 8> PHIsInspected;
1073
1074 PHIsToSlice.push_back(&FirstPhi);
1075 PHIsInspected.insert(&FirstPhi);
1076
1077 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
1078 PHINode *PN = PHIsToSlice[PHIId];
1079
1080 for (User *U : PN->users()) {
1081 Instruction *UserI = cast<Instruction>(U);
1082
1083 // If the user is a PHI, inspect its uses recursively.
1084 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
1085 if (PHIsInspected.insert(UserPN).second)
1086 PHIsToSlice.push_back(UserPN);
1087 continue;
1088 }
1089
1090 // Truncates are always ok.
1091 if (isa<TruncInst>(UserI)) {
1092 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
1093 continue;
1094 }
1095
1096 // Otherwise it must be a lshr which can only be used by one trunc.
1097 if (UserI->getOpcode() != Instruction::LShr ||
1098 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
1099 !isa<ConstantInt>(UserI->getOperand(1)))
1100 return nullptr;
1101
1102 // Bail on out of range shifts.
1103 unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
1104 if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
1105 return nullptr;
1106
1107 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1108 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
1109 }
1110 }
1111
1112 for (const auto &PN : PHIsToSlice) {
1113 // Scan the input list of the PHI. If any input is an invoke, and if the
1114 // input is defined in the predecessor, then we won't be split the critical
1115 // edge which is required to insert a truncate. Because of this, we have to
1116 // bail out.
1117 for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
1118 BasicBlock *BB = std::get<0>(Incoming);
1119 Value *V = std::get<1>(Incoming);
1121 if (!II)
1122 continue;
1123 if (II->getParent() != BB)
1124 continue;
1125
1126 // If we have a phi, and if it's directly in the predecessor, then we have
1127 // a critical edge where we need to put the truncate. Since we can't
1128 // split the edge in instcombine, we have to bail out.
1129 return nullptr;
1130 }
1131
1132 // If the incoming value is a PHI node before a catchswitch, we cannot
1133 // extract the value within that BB because we cannot insert any non-PHI
1134 // instructions in the BB.
1135 for (auto *Pred : PN->blocks())
1136 if (!Pred->hasInsertionPt())
1137 return nullptr;
1138 }
1139
1140 // If we have no users, they must be all self uses, just nuke the PHI.
1141 if (PHIUsers.empty())
1142 return replaceInstUsesWith(FirstPhi, PoisonValue::get(FirstPhi.getType()));
1143
1144 // If this phi node is transformable, create new PHIs for all the pieces
1145 // extracted out of it. First, sort the users by their offset and size.
1146 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
1147
1148 LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1149 for (unsigned I = 1; I != PHIsToSlice.size(); ++I) dbgs()
1150 << "AND USER PHI #" << I << ": " << *PHIsToSlice[I] << '\n');
1151
1152 // PredValues - This is a temporary used when rewriting PHI nodes. It is
1153 // hoisted out here to avoid construction/destruction thrashing.
1155
1156 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1157 // introduce redundant PHIs.
1159
1160 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1161 unsigned PHIId = PHIUsers[UserI].PHIId;
1162 PHINode *PN = PHIsToSlice[PHIId];
1163 unsigned Offset = PHIUsers[UserI].Shift;
1164 Type *Ty = PHIUsers[UserI].Inst->getType();
1165
1166 PHINode *EltPHI;
1167
1168 // If we've already lowered a user like this, reuse the previously lowered
1169 // value.
1170 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
1171
1172 // Otherwise, Create the new PHI node for this user.
1173 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1174 PN->getName() + ".off" + Twine(Offset),
1175 PN->getIterator());
1176 assert(EltPHI->getType() != PN->getType() &&
1177 "Truncate didn't shrink phi?");
1178
1179 for (auto Incoming : zip(PN->blocks(), PN->incoming_values())) {
1180 BasicBlock *Pred = std::get<0>(Incoming);
1181 Value *InVal = std::get<1>(Incoming);
1182 Value *&PredVal = PredValues[Pred];
1183
1184 // If we already have a value for this predecessor, reuse it.
1185 if (PredVal) {
1186 EltPHI->addIncoming(PredVal, Pred);
1187 continue;
1188 }
1189
1190 // Handle the PHI self-reuse case.
1191 if (InVal == PN) {
1192 PredVal = EltPHI;
1193 EltPHI->addIncoming(PredVal, Pred);
1194 continue;
1195 }
1196
1197 // If the incoming value was a PHI, and if it was one of the PHIs we
1198 // already rewrote it, just use the lowered value.
1199 if (Value *Res = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) {
1200 PredVal = Res;
1201 EltPHI->addIncoming(PredVal, Pred);
1202 continue;
1203 }
1204
1205 // Otherwise, do an extract in the predecessor.
1206 Builder.SetInsertPoint(Pred->getTerminator());
1207 Value *Res = InVal;
1208 if (Offset)
1209 Res = Builder.CreateLShr(
1210 Res, ConstantInt::get(InVal->getType(), Offset), "extract");
1211 Res = Builder.CreateTrunc(Res, Ty, "extract.t");
1212 PredVal = Res;
1213 EltPHI->addIncoming(Res, Pred);
1214
1215 // If the incoming value was a PHI, and if it was one of the PHIs we are
1216 // rewriting, we will ultimately delete the code we inserted. This
1217 // means we need to revisit that PHI to make sure we extract out the
1218 // needed piece.
1219 if (PHINode *OldInVal = dyn_cast<PHINode>(InVal))
1220 if (PHIsInspected.count(OldInVal)) {
1221 unsigned RefPHIId =
1222 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1223 PHIUsers.push_back(
1224 PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Res)));
1225 ++UserE;
1226 }
1227 }
1228 PredValues.clear();
1229
1230 LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
1231 << *EltPHI << '\n');
1232 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1233 }
1234
1235 // Replace the use of this piece with the PHI node.
1236 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1237 }
1238
1239 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1240 // with poison.
1241 Value *Poison = PoisonValue::get(FirstPhi.getType());
1242 for (PHINode *PHI : drop_begin(PHIsToSlice))
1243 replaceInstUsesWith(*PHI, Poison);
1244 return replaceInstUsesWith(FirstPhi, Poison);
1245}
1246
1248 const DominatorTree &DT) {
1249 // Simplify the following patterns:
1250 // if (cond)
1251 // / \
1252 // ... ...
1253 // \ /
1254 // phi [true] [false]
1255 // and
1256 // switch (cond)
1257 // case v1: / \ case v2:
1258 // ... ...
1259 // \ /
1260 // phi [v1] [v2]
1261 // Make sure all inputs are constants.
1263 return nullptr;
1264
1265 BasicBlock *BB = PN.getParent();
1266 // Do not bother with unreachable instructions.
1267 if (!DT.isReachableFromEntry(BB))
1268 return nullptr;
1269
1270 // Determine which value the condition of the idom has for which successor.
1271 LLVMContext &Context = PN.getContext();
1272 auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
1273 Value *Cond;
1276 auto AddSucc = [&](ConstantInt *C, BasicBlock *Succ) {
1277 SuccForValue[C] = Succ;
1278 ++SuccCount[Succ];
1279 };
1280 if (auto *BI = dyn_cast<CondBrInst>(IDom->getTerminator())) {
1281 Cond = BI->getCondition();
1282 AddSucc(ConstantInt::getTrue(Context), BI->getSuccessor(0));
1283 AddSucc(ConstantInt::getFalse(Context), BI->getSuccessor(1));
1284 } else if (auto *SI = dyn_cast<SwitchInst>(IDom->getTerminator())) {
1285 Cond = SI->getCondition();
1286 ++SuccCount[SI->getDefaultDest()];
1287 for (auto Case : SI->cases())
1288 AddSucc(Case.getCaseValue(), Case.getCaseSuccessor());
1289 } else {
1290 return nullptr;
1291 }
1292
1293 if (Cond->getType() != PN.getType())
1294 return nullptr;
1295
1296 // Check that edges outgoing from the idom's terminators dominate respective
1297 // inputs of the Phi.
1298 std::optional<bool> Invert;
1299 for (auto Pair : zip(PN.incoming_values(), PN.blocks())) {
1300 auto *Input = cast<ConstantInt>(std::get<0>(Pair));
1301 BasicBlock *Pred = std::get<1>(Pair);
1302 auto IsCorrectInput = [&](ConstantInt *Input) {
1303 // The input needs to be dominated by the corresponding edge of the idom.
1304 // This edge cannot be a multi-edge, as that would imply that multiple
1305 // different condition values follow the same edge.
1306 auto It = SuccForValue.find(Input);
1307 return It != SuccForValue.end() && SuccCount[It->second] == 1 &&
1308 DT.dominates(BasicBlockEdge(IDom, It->second),
1309 BasicBlockEdge(Pred, BB));
1310 };
1311
1312 // Depending on the constant, the condition may need to be inverted.
1313 bool NeedsInvert;
1314 if (IsCorrectInput(Input))
1315 NeedsInvert = false;
1316 else if (IsCorrectInput(cast<ConstantInt>(ConstantExpr::getNot(Input))))
1317 NeedsInvert = true;
1318 else
1319 return nullptr;
1320
1321 // Make sure the inversion requirement is always the same.
1322 if (Invert && *Invert != NeedsInvert)
1323 return nullptr;
1324
1325 Invert = NeedsInvert;
1326 }
1327
1328 if (!*Invert)
1329 return Cond;
1330
1331 // This Phi is actually opposite to branching condition of IDom. We invert
1332 // the condition that will potentially open up some opportunities for
1333 // sinking.
1334 auto InsertPt = BB->getFirstInsertionPt();
1335 if (InsertPt != BB->end()) {
1336 Self.Builder.SetInsertPoint(InsertPt);
1337 return Self.Builder.CreateNot(Cond);
1338 }
1339
1340 return nullptr;
1341}
1342
1343// Fold iv = phi(start, iv.next = iv2.next op start)
1344// where iv2 = phi(iv2.start, iv2.next = iv2 + iv2.step)
1345// and iv2.start op start = start
1346// to iv = iv2 op start
1348 BasicBlock *BB = PN.getParent();
1349 if (PN.getNumIncomingValues() != 2)
1350 return nullptr;
1351
1352 Value *Start;
1353 Instruction *IvNext;
1354 BinaryOperator *Iv2Next;
1355 auto MatchOuterIV = [&](Value *V1, Value *V2) {
1356 if (match(V2, m_c_BinOp(m_Specific(V1), m_BinOp(Iv2Next))) ||
1357 match(V2, m_GEP(m_Specific(V1), m_BinOp(Iv2Next)))) {
1358 Start = V1;
1359 IvNext = cast<Instruction>(V2);
1360 return true;
1361 }
1362 return false;
1363 };
1364
1365 if (!MatchOuterIV(PN.getIncomingValue(0), PN.getIncomingValue(1)) &&
1366 !MatchOuterIV(PN.getIncomingValue(1), PN.getIncomingValue(0)))
1367 return nullptr;
1368
1369 PHINode *Iv2;
1370 Value *Iv2Start, *Iv2Step;
1371 if (!matchSimpleRecurrence(Iv2Next, Iv2, Iv2Start, Iv2Step) ||
1372 Iv2->getParent() != BB)
1373 return nullptr;
1374
1375 auto *BO = dyn_cast<BinaryOperator>(IvNext);
1376 Constant *Identity =
1377 BO ? ConstantExpr::getBinOpIdentity(BO->getOpcode(), Iv2Start->getType())
1378 : Constant::getNullValue(Iv2Start->getType());
1379 if (Iv2Start != Identity)
1380 return nullptr;
1381
1382 Builder.SetInsertPoint(BB->getFirstInsertionPt());
1383 if (!BO) {
1384 auto *GEP = cast<GEPOperator>(IvNext);
1385 return Builder.CreateGEP(GEP->getSourceElementType(), Start, Iv2, "",
1386 cast<GEPOperator>(IvNext)->getNoWrapFlags());
1387 }
1388
1389 assert(BO->isCommutative() && "Must be commutative");
1390 Value *Res = Builder.CreateBinOp(BO->getOpcode(), Iv2, Start);
1391 cast<Instruction>(Res)->copyIRFlags(BO);
1392 return Res;
1393}
1394
1395// PHINode simplification
1396//
1398 if (Value *V = simplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
1399 return replaceInstUsesWith(PN, V);
1400
1401 if (Instruction *Result = foldPHIArgZextsIntoPHI(PN))
1402 return Result;
1403
1404 if (Instruction *Result = foldPHIArgIntToPtrToPHI(PN))
1405 return Result;
1406
1407 // If all PHI operands are the same operation, pull them through the PHI,
1408 // reducing code size.
1409 auto *Inst0 = dyn_cast<Instruction>(PN.getIncomingValue(0));
1410 auto *Inst1 = dyn_cast<Instruction>(PN.getIncomingValue(1));
1411 if (Inst0 && Inst1 && Inst0->getOpcode() == Inst1->getOpcode() &&
1412 Inst0->hasOneUser())
1413 if (Instruction *Result = foldPHIArgOpIntoPHI(PN))
1414 return Result;
1415
1416 // If the incoming values are pointer casts of the same original value,
1417 // replace the phi with a single cast iff we can insert a non-PHI instruction.
1418 if (PN.getType()->isPointerTy() && PN.getParent()->hasInsertionPt()) {
1419 Value *IV0 = PN.getIncomingValue(0);
1420 Value *IV0Stripped = IV0->stripPointerCasts();
1421 // Set to keep track of values known to be equal to IV0Stripped after
1422 // stripping pointer casts.
1423 SmallPtrSet<Value *, 4> CheckedIVs;
1424 CheckedIVs.insert(IV0);
1425 if (IV0 != IV0Stripped &&
1426 all_of(PN.incoming_values(), [&CheckedIVs, IV0Stripped](Value *IV) {
1427 return !CheckedIVs.insert(IV).second ||
1428 IV0Stripped == IV->stripPointerCasts();
1429 })) {
1430 return CastInst::CreatePointerCast(IV0Stripped, PN.getType());
1431 }
1432 }
1433
1434 if (foldDeadPhiWeb(PN))
1435 return nullptr;
1436
1437 // Optimization when the phi only has one use
1438 if (PN.hasOneUse()) {
1439 if (foldIntegerTypedPHI(PN))
1440 return nullptr;
1441
1442 // If this phi has a single use, and if that use just computes a value for
1443 // the next iteration of a loop, delete the phi. This occurs with unused
1444 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
1445 // common case here is good because the only other things that catch this
1446 // are induction variable analysis (sometimes) and ADCE, which is only run
1447 // late.
1448 Instruction *PHIUser = cast<Instruction>(PN.user_back());
1449 if (PHIUser->hasOneUse() &&
1450 (isa<BinaryOperator>(PHIUser) || isa<UnaryOperator>(PHIUser) ||
1451 isa<GetElementPtrInst>(PHIUser)) &&
1452 PHIUser->user_back() == &PN) {
1454 }
1455 }
1456
1457 // When a PHI is used only to be compared with zero, it is safe to replace
1458 // an incoming value proved as known nonzero with any non-zero constant.
1459 // For example, in the code below, the incoming value %v can be replaced
1460 // with any non-zero constant based on the fact that the PHI is only used to
1461 // be compared with zero and %v is a known non-zero value:
1462 // %v = select %cond, 1, 2
1463 // %p = phi [%v, BB] ...
1464 // icmp eq, %p, 0
1465 // FIXME: To be simple, handle only integer type for now.
1466 // This handles a small number of uses to keep the complexity down, and an
1467 // icmp(or(phi)) can equally be replaced with any non-zero constant as the
1468 // "or" will only add bits.
1469 if (!PN.hasNUsesOrMore(3)) {
1470 SmallVector<Instruction *> DropPoisonFlags;
1471 bool AllUsesOfPhiEndsInCmp = all_of(PN.users(), [&](User *U) {
1472 auto *CmpInst = dyn_cast<ICmpInst>(U);
1473 if (!CmpInst) {
1474 // This is always correct as OR only add bits and we are checking
1475 // against 0.
1476 if (U->hasOneUse() && match(U, m_c_Or(m_Specific(&PN), m_Value()))) {
1477 DropPoisonFlags.push_back(cast<Instruction>(U));
1478 CmpInst = dyn_cast<ICmpInst>(U->user_back());
1479 }
1480 }
1481 if (!CmpInst || !isa<IntegerType>(PN.getType()) ||
1482 !CmpInst->isEquality() || !match(CmpInst->getOperand(1), m_Zero())) {
1483 return false;
1484 }
1485 return true;
1486 });
1487 // All uses of PHI results in a compare with zero.
1488 if (AllUsesOfPhiEndsInCmp) {
1489 ConstantInt *NonZeroConst = nullptr;
1490 bool MadeChange = false;
1491 for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
1493 Value *VA = PN.getIncomingValue(I);
1494 if (isKnownNonZero(VA, getSimplifyQuery().getWithInstruction(CtxI))) {
1495 if (!NonZeroConst)
1496 NonZeroConst = getAnyNonZeroConstInt(PN);
1497 if (NonZeroConst != VA) {
1498 replaceOperand(PN, I, NonZeroConst);
1499 // The "disjoint" flag may no longer hold after the transform.
1500 for (Instruction *I : DropPoisonFlags)
1501 I->dropPoisonGeneratingFlags();
1502 MadeChange = true;
1503 }
1504 }
1505 }
1506 if (MadeChange)
1507 return &PN;
1508 }
1509 }
1510
1511 // We sometimes end up with phi cycles that non-obviously end up being the
1512 // same value, for example:
1513 // z = some value; x = phi (y, z); y = phi (x, z)
1514 // where the phi nodes don't necessarily need to be in the same block. Do a
1515 // quick check to see if the PHI node only contains a single non-phi value, if
1516 // so, scan to see if the phi cycle is actually equal to that value. If the
1517 // phi has no non-phi values then allow the "NonPhiInVal" to be set later if
1518 // one of the phis itself does not have a single input.
1519 {
1520 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
1521 // Scan for the first non-phi operand.
1522 while (InValNo != NumIncomingVals &&
1523 isa<PHINode>(PN.getIncomingValue(InValNo)))
1524 ++InValNo;
1525
1526 Value *NonPhiInVal =
1527 InValNo != NumIncomingVals ? PN.getIncomingValue(InValNo) : nullptr;
1528
1529 // Scan the rest of the operands to see if there are any conflicts, if so
1530 // there is no need to recursively scan other phis.
1531 if (NonPhiInVal)
1532 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1533 Value *OpVal = PN.getIncomingValue(InValNo);
1534 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1535 break;
1536 }
1537
1538 // If we scanned over all operands, then we have one unique value plus
1539 // phi values. Scan PHI nodes to see if they all merge in each other or
1540 // the value.
1541 if (InValNo == NumIncomingVals) {
1542 SmallPtrSet<PHINode *, 16> ValueEqualPHIs;
1543 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
1544 return replaceInstUsesWith(PN, NonPhiInVal);
1545 }
1546 }
1547
1548 // If there are multiple PHIs, sort their operands so that they all list
1549 // the blocks in the same order. This will help identical PHIs be eliminated
1550 // by other passes. Other passes shouldn't depend on this for correctness
1551 // however.
1552 auto Res = PredOrder.try_emplace(PN.getParent());
1553 if (!Res.second) {
1554 const auto &Preds = Res.first->second;
1555 for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) {
1556 BasicBlock *BBA = PN.getIncomingBlock(I);
1557 BasicBlock *BBB = Preds[I];
1558 if (BBA != BBB) {
1559 Value *VA = PN.getIncomingValue(I);
1560 unsigned J = PN.getBasicBlockIndex(BBB);
1561 Value *VB = PN.getIncomingValue(J);
1562 PN.setIncomingBlock(I, BBB);
1563 PN.setIncomingValue(I, VB);
1564 PN.setIncomingBlock(J, BBA);
1565 PN.setIncomingValue(J, VA);
1566 // NOTE: Instcombine normally would want us to "return &PN" if we
1567 // modified any of the operands of an instruction. However, since we
1568 // aren't adding or removing uses (just rearranging them) we don't do
1569 // this in this case.
1570 }
1571 }
1572 } else {
1573 // Remember the block order of the first encountered phi node.
1574 append_range(Res.first->second, PN.blocks());
1575 }
1576
1577 // Is there an identical PHI node in this basic block?
1578 for (PHINode &IdenticalPN : PN.getParent()->phis()) {
1579 // Ignore the PHI node itself.
1580 if (&IdenticalPN == &PN)
1581 continue;
1582 // Note that even though we've just canonicalized this PHI, due to the
1583 // worklist visitation order, there are no guarantess that *every* PHI
1584 // has been canonicalized, so we can't just compare operands ranges.
1585 if (!PN.isIdenticalToWhenDefined(&IdenticalPN))
1586 continue;
1587 // Just use that PHI instead then.
1588 ++NumPHICSEs;
1589 return replaceInstUsesWith(PN, &IdenticalPN);
1590 }
1591
1592 // If this is an integer PHI and we know that it has an illegal type, see if
1593 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1594 // PHI into the various pieces being extracted. This sort of thing is
1595 // introduced when SROA promotes an aggregate to a single large integer type.
1596 if (PN.getType()->isIntegerTy() &&
1597 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
1598 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1599 return Res;
1600
1601 // Ultimately, try to replace this Phi with a dominating condition.
1602 if (auto *V = simplifyUsingControlFlow(*this, PN, DT))
1603 return replaceInstUsesWith(PN, V);
1604
1605 if (Value *Res = foldDependentIVs(PN, Builder))
1606 return replaceInstUsesWith(PN, Res);
1607
1608 return nullptr;
1609}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Rewrite undef for PHI
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static ConstantInt * getAnyNonZeroConstInt(PHINode &PN)
Return an existing non-zero constant if this phi node has one, otherwise return constant 1.
static Value * foldDependentIVs(PHINode &PN, IRBuilderBase &Builder)
static bool isSafeAndProfitableToSinkLoad(LoadInst *L)
Return true if we know that it is safe to sink the load out of the block that defines it.
static Value * simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN, const DominatorTree &DT)
static bool PHIsEqualValue(PHINode *PN, Value *&NonPhiInVal, SmallPtrSetImpl< PHINode * > &ValueEqualPHIs)
Return true if this phi node is always equal to NonPhiInVal.
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
if(PassOpts->AAPipeline)
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallPtrSet 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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
The Input class is used to parse a yaml document into in-memory structs and vectors.
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
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...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * CreatePointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, AddrSpaceCast or a PtrToInt cast instruction.
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
static LLVM_ABI CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt or BitCast cast instruction.
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
static LLVM_ABI CmpInst * Create(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate and the two operands.
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
OtherOps getOpcode() const
Get the opcode casted to the right type.
Definition InstrTypes.h:823
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static DebugLoc getDropped()
Definition DebugLoc.h:155
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
DomTreeNodeBase * getIDom() const
NodeT * getBlock() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static ExtractValueInst * Create(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Represents flags for the getelementptr instruction/expression.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Type * getSourceElementType() const
LLVM_ABI GEPNoWrapFlags getNoWrapFlags() const
Get the nowrap flags for the GEP instruction.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
Value * CreateNot(Value *V, const Twine &Name="")
Definition IRBuilder.h:1850
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:196
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Instruction * foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN)
If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)], turn this into a phi[a,...
Instruction * foldPHIArgBinOpIntoPHI(PHINode &PN)
If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the adds all have a single user,...
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitPHINode(PHINode &PN)
Instruction * foldPHIArgOpIntoPHI(PHINode &PN)
Try to rotate an operation below a PHI node, using PHI nodes for its operands.
const InstCombineCLOptions & CLOpts
Instruction * foldPHIArgZextsIntoPHI(PHINode &PN)
TODO: This function could handle other cast types, but then it might require special-casing a cast fr...
Instruction * foldPHIArgLoadIntoPHI(PHINode &PN)
bool foldIntegerTypedPHI(PHINode &PN)
If an integer typed PHI has only one use which is an IntToPtr operation, replace the PHI with an exis...
bool foldDeadPhiWeb(PHINode &PN)
If the phi is within a phi web, which is formed by the def-use chain of phis and all the phis in the ...
Instruction * foldPHIArgIntToPtrToPHI(PHINode &PN)
Instruction * SliceUpIllegalIntegerPHI(PHINode &PN)
This is an integer PHI and we know that it has an illegal type: see if it is only used by trunc or tr...
Instruction * foldPHIArgGEPIntoPHI(PHINode &PN)
void PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN)
Helper function for FoldPHIArgXIntoPHI() to set debug location for the folded operation.
Instruction * foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN)
If we have something like phi [extractvalue(a,0), extractvalue(b,0)], turn this into a phi[a,...
The core instruction combiner logic.
SimplifyQuery SQ
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.
const DataLayout & DL
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
DominatorTree & DT
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
Instruction * user_back()
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
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.
LLVM_ABI void applyMergedLocation(DebugLoc LocA, DebugLoc LocB)
Merge 2 debug locations and apply it to the Instruction.
Invoke instruction.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
bool isSimple() const
Align getAlign() const
Return the alignment of the access that is being performed.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
op_range incoming_values()
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
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...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
op_iterator op_begin()
Definition User.h:259
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
op_iterator op_end()
Definition User.h:261
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:159
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:151
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:708
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_GEP(const OperandTypes &...Ops)
Matches GetElementPtrInst.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:360
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1781
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
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI Constant * getLosslessUnsignedTrunc(Constant *C, Type *DestTy, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
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 isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
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:3126
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3911
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static bool isEqual(const LoweredPHIRecord &LHS, const LoweredPHIRecord &RHS)
static unsigned getHashValue(const LoweredPHIRecord &Val)
An information struct used to provide DenseMap with the various necessary components for a given valu...