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"
15#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/Statistic.h"
17#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/ValueTracking.h"
19#include "llvm/IR/PatternMatch.h"
20#include "llvm/Transforms/InstCombine/InstCombiner.h"
21#include "llvm/Transforms/Utils/Local.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.
38void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
39 auto *FirstInst = cast<Instruction>(Val: PN.getIncomingValue(i: 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(RangeOrContainer: PN.incoming_values())) {
46 auto *I = cast<Instruction>(Val: V);
47 Inst->applyMergedLocation(LocA: Inst->getDebugLoc(), LocB: 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.
54bool InstCombinerImpl::foldDeadPhiWeb(PHINode &PN) {
55 SmallVector<PHINode *, 16> Stack;
56 SmallPtrSet<PHINode *, 16> Visited;
57 Stack.push_back(Elt: &PN);
58 Visited.insert(Ptr: &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>(Val: Use)) {
63 if (!Visited.insert(Ptr: 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(Elt: PhiUse);
69 } else
70 return false;
71 }
72 }
73 for (PHINode *Phi : Visited)
74 replaceInstUsesWith(I&: *Phi, V: PoisonValue::get(T: Phi->getType()));
75 for (PHINode *Phi : Visited)
76 eraseInstFromFunction(I&: *Phi);
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//
130bool InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) {
131 if (!PN.getType()->isIntegerTy())
132 return false;
133 if (!PN.hasOneUse())
134 return false;
135
136 auto *IntToPtr = dyn_cast<IntToPtrInst>(Val: 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>(Val: U)) {
145 Ptr = LoadI->getPointerOperand();
146 } else if (StoreInst *SI = dyn_cast<StoreInst>(Val: U)) {
147 Ptr = SI->getPointerOperand();
148 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(Val: U)) {
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(AS: IntToPtr->getAddressSpace()) !=
162 DL.getTypeSizeInBits(Ty: IntToPtr->getOperand(i_nocapture: 0)->getType()))
163 return false;
164
165 SmallVector<Value *, 4> AvailablePtrVals;
166 for (auto Incoming : zip(t: PN.blocks(), u: PN.incoming_values())) {
167 BasicBlock *BB = std::get<0>(t&: Incoming);
168 Value *Arg = std::get<1>(t&: Incoming);
169
170 // Arg could be a constant, constant expr, etc., which we don't cover here.
171 if (!isa<Instruction>(Val: Arg) && !isa<Argument>(Val: Arg))
172 return false;
173
174 // First look backward:
175 if (auto *PI = dyn_cast<PtrToIntInst>(Val: Arg)) {
176 if (PI->getOperand(i_nocapture: 0)->getType() == IntToPtr->getType()) {
177 AvailablePtrVals.emplace_back(Args: PI->getOperand(i_nocapture: 0));
178 continue;
179 }
180 }
181
182 // Next look forward:
183 Value *ArgIntToPtr = nullptr;
184 for (User *U : Arg->users()) {
185 if (isa<IntToPtrInst>(Val: U) && U->getType() == IntToPtr->getType() &&
186 (DT.dominates(Def: cast<Instruction>(Val: U), BB) ||
187 cast<Instruction>(Val: U)->getParent() == BB)) {
188 ArgIntToPtr = U;
189 break;
190 }
191 }
192
193 if (ArgIntToPtr) {
194 AvailablePtrVals.emplace_back(Args&: 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>(Val: Arg)) {
201 AvailablePtrVals.emplace_back(Args&: Arg);
202 continue;
203 }
204
205 // For a single use integer load:
206 auto *LoadI = dyn_cast<LoadInst>(Val: 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(Args&: 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(Range: zip(t: PN.blocks(), u&: AvailablePtrVals),
232 P: [&](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(I&: *IntToPtr, V: MatchingPtrPHI);
248 eraseInstFromFunction(I&: *IntToPtr);
249 eraseInstFromFunction(I&: PN);
250 return true;
251 }
252
253 // If it requires a conversion for every PHI operand, do not do it.
254 if (all_of(Range&: AvailablePtrVals, P: [&](Value *V) {
255 return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(Val: 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(Range&: AvailablePtrVals, P: [&](Value *V) {
264 if (V->getType() == IntToPtr->getType())
265 return false;
266 auto *Inst = dyn_cast<Instruction>(Val: V);
267 if (!Inst)
268 return false;
269 if (Inst->isTerminator())
270 return true;
271 auto *BB = Inst->getParent();
272 if (isa<PHINode>(Val: Inst) && !BB->hasInsertionPt())
273 return true;
274 return false;
275 }))
276 return false;
277
278 PHINode *NewPtrPHI = PHINode::Create(
279 Ty: IntToPtr->getType(), NumReservedValues: PN.getNumIncomingValues(), NameStr: PN.getName() + ".ptr");
280
281 InsertNewInstBefore(New: NewPtrPHI, Old: PN.getIterator());
282 SmallDenseMap<Value *, Instruction *> Casts;
283 for (auto Incoming : zip(t: PN.blocks(), u&: AvailablePtrVals)) {
284 auto *IncomingBB = std::get<0>(t&: Incoming);
285 auto *IncomingVal = std::get<1>(t&: Incoming);
286
287 if (IncomingVal->getType() == IntToPtr->getType()) {
288 NewPtrPHI->addIncoming(V: IncomingVal, BB: 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(S: IncomingVal, Ty: IntToPtr->getType(),
310 Name: IncomingVal->getName() + ".ptr");
311 if (auto *IncomingI = dyn_cast<Instruction>(Val: IncomingVal)) {
312 BasicBlock::iterator InsertPos(IncomingI);
313 InsertPos++;
314 BasicBlock *BB = IncomingI->getParent();
315 if (isa<PHINode>(Val: IncomingI))
316 InsertPos = BB->getFirstInsertionPt();
317 assert(InsertPos != BB->end() && "should have checked above");
318 InsertNewInstBefore(New: CI, Old: InsertPos);
319 } else {
320 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
321 InsertNewInstBefore(New: CI, Old: InsertBB->getFirstInsertionPt());
322 }
323 }
324 NewPtrPHI->addIncoming(V: CI, BB: 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(I&: *IntToPtr, V: NewPtrPHI);
330 eraseInstFromFunction(I&: *IntToPtr);
331 eraseInstFromFunction(I&: PN);
332 return true;
333}
334
335// Remove RoundTrip IntToPtr/PtrToInt Cast on PHI-Operand and
336// fold Phi-operand to bitcast.
337Instruction *InstCombinerImpl::foldPHIArgIntToPtrToPHI(PHINode &PN) {
338 // convert ptr2int ( phi[ int2ptr(ptr2int(x))] ) --> ptr2int ( phi [ x ] )
339 // Make sure all uses of phi are ptr2int.
340 if (!all_of(Range: PN.users(), P: IsaPred<PtrToIntInst>))
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(Val: PN.getIncomingValue(i: OpNum))) {
349 replaceOperand(I&: PN, OpNum, V: 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.
360Instruction *
361InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) {
362 auto *FirstIVI = cast<InsertValueInst>(Val: PN.getIncomingValue(i: 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(RangeOrContainer: PN.incoming_values())) {
367 auto *I = dyn_cast<InsertValueInst>(Val: 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 Ty: FirstIVI->getOperand(i_nocapture: OpIdx)->getType(), NumReservedValues: PN.getNumIncomingValues(),
380 NameStr: FirstIVI->getOperand(i_nocapture: OpIdx)->getName() + ".pn");
381 // And populate each operand's PHI with said values.
382 for (auto Incoming : zip(t: PN.blocks(), u: PN.incoming_values()))
383 NewOperand->addIncoming(
384 V: cast<InsertValueInst>(Val&: std::get<1>(t&: Incoming))->getOperand(i_nocapture: OpIdx),
385 BB: std::get<0>(t&: Incoming));
386 InsertNewInstBefore(New: NewOperand, Old: PN.getIterator());
387 }
388
389 // And finally, create `insertvalue` over the newly-formed PHI nodes.
390 auto *NewIVI = InsertValueInst::Create(Agg: NewOperands[0], Val: NewOperands[1],
391 Idxs: FirstIVI->getIndices(), NameStr: PN.getName());
392
393 PHIArgMergedDebugLoc(Inst: 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.
400Instruction *
401InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) {
402 auto *FirstEVI = cast<ExtractValueInst>(Val: PN.getIncomingValue(i: 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(RangeOrContainer: PN.incoming_values())) {
407 auto *I = dyn_cast<ExtractValueInst>(Val: 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 Ty: FirstEVI->getAggregateOperand()->getType(), NumReservedValues: PN.getNumIncomingValues(),
418 NameStr: FirstEVI->getAggregateOperand()->getName() + ".pn");
419 // And populate the PHI with said values.
420 for (auto Incoming : zip(t: PN.blocks(), u: PN.incoming_values()))
421 NewAggregateOperand->addIncoming(
422 V: cast<ExtractValueInst>(Val&: std::get<1>(t&: Incoming))->getAggregateOperand(),
423 BB: std::get<0>(t&: Incoming));
424 InsertNewInstBefore(New: NewAggregateOperand, Old: PN.getIterator());
425
426 // And finally, create `extractvalue` over the newly-formed PHI nodes.
427 auto *NewEVI = ExtractValueInst::Create(Agg: NewAggregateOperand,
428 Idxs: FirstEVI->getIndices(), NameStr: PN.getName());
429
430 PHIArgMergedDebugLoc(Inst: 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.
437Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) {
438 Instruction *FirstInst = cast<Instruction>(Val: PN.getIncomingValue(i: 0));
439 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
440 unsigned Opc = FirstInst->getOpcode();
441 Value *LHSVal = FirstInst->getOperand(i: 0);
442 Value *RHSVal = FirstInst->getOperand(i: 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(RangeOrContainer: PN.incoming_values())) {
449 Instruction *I = dyn_cast<Instruction>(Val: V);
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(i: 0)->getType() != LHSType ||
454 I->getOperand(i: 1)->getType() != RHSType)
455 return nullptr;
456
457 // If they are CmpInst instructions, check their predicates
458 if (CmpInst *CI = dyn_cast<CmpInst>(Val: I))
459 if (CI->getPredicate() != cast<CmpInst>(Val: FirstInst)->getPredicate())
460 return nullptr;
461
462 // Keep track of which operand needs a phi node.
463 if (I->getOperand(i: 0) != LHSVal) LHSVal = nullptr;
464 if (I->getOperand(i: 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(i: 0);
477 Value *InRHS = FirstInst->getOperand(i: 1);
478 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
479 if (!LHSVal) {
480 NewLHS = PHINode::Create(Ty: LHSType, NumReservedValues: PN.getNumIncomingValues(),
481 NameStr: FirstInst->getOperand(i: 0)->getName() + ".pn");
482 NewLHS->addIncoming(V: InLHS, BB: PN.getIncomingBlock(i: 0));
483 InsertNewInstBefore(New: NewLHS, Old: PN.getIterator());
484 LHSVal = NewLHS;
485 }
486
487 if (!RHSVal) {
488 NewRHS = PHINode::Create(Ty: RHSType, NumReservedValues: PN.getNumIncomingValues(),
489 NameStr: FirstInst->getOperand(i: 1)->getName() + ".pn");
490 NewRHS->addIncoming(V: InRHS, BB: PN.getIncomingBlock(i: 0));
491 InsertNewInstBefore(New: NewRHS, Old: 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(RangeOrContainer: zip(t: PN.blocks(), u: PN.incoming_values()))) {
498 BasicBlock *InBB = std::get<0>(t&: Incoming);
499 Value *InVal = std::get<1>(t&: Incoming);
500 Instruction *InInst = cast<Instruction>(Val: InVal);
501 if (NewLHS) {
502 Value *NewInLHS = InInst->getOperand(i: 0);
503 NewLHS->addIncoming(V: NewInLHS, BB: InBB);
504 }
505 if (NewRHS) {
506 Value *NewInRHS = InInst->getOperand(i: 1);
507 NewRHS->addIncoming(V: NewInRHS, BB: InBB);
508 }
509 }
510 }
511
512 if (CmpInst *CIOp = dyn_cast<CmpInst>(Val: FirstInst)) {
513 CmpInst *NewCI = CmpInst::Create(Op: CIOp->getOpcode(), Pred: CIOp->getPredicate(),
514 S1: LHSVal, S2: RHSVal);
515 PHIArgMergedDebugLoc(Inst: NewCI, PN);
516 return NewCI;
517 }
518
519 BinaryOperator *BinOp = cast<BinaryOperator>(Val: FirstInst);
520 BinaryOperator *NewBinOp =
521 BinaryOperator::Create(Op: BinOp->getOpcode(), S1: LHSVal, S2: RHSVal);
522
523 NewBinOp->copyIRFlags(V: PN.getIncomingValue(i: 0));
524
525 for (Value *V : drop_begin(RangeOrContainer: PN.incoming_values()))
526 NewBinOp->andIRFlags(V);
527
528 PHIArgMergedDebugLoc(Inst: NewBinOp, PN);
529 return NewBinOp;
530}
531
532Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
533 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(Val: PN.getIncomingValue(i: 0));
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(RangeOrContainer: PN.incoming_values())) {
551 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: V);
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>(Val: GEP->getOperand(i_nocapture: 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(i_nocapture: Op) == GEP->getOperand(i_nocapture: 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>(Val: FirstInst->getOperand(i_nocapture: Op)) ||
576 isa<Constant>(Val: GEP->getOperand(i_nocapture: Op)))
577 return nullptr;
578
579 if (FirstInst->getOperand(i_nocapture: Op)->getType() !=
580 GEP->getOperand(i_nocapture: 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_nocapture: I);
613 PHINode *NewPN =
614 PHINode::Create(Ty: FirstOp->getType(), NumReservedValues: E, NameStr: FirstOp->getName() + ".pn");
615 InsertNewInstBefore(New: NewPN, Old: PN.getIterator());
616
617 NewPN->addIncoming(V: FirstOp, BB: PN.getIncomingBlock(i: 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(RangeOrContainer: zip(t: PN.blocks(), u: PN.incoming_values()))) {
626 BasicBlock *InBB = std::get<0>(t&: Incoming);
627 Value *InVal = std::get<1>(t&: Incoming);
628 GetElementPtrInst *InGEP = cast<GetElementPtrInst>(Val: InVal);
629
630 for (unsigned Op = 0, E = OperandPhis.size(); Op != E; ++Op)
631 if (PHINode *OpPhi = OperandPhis[Op])
632 OpPhi->addIncoming(V: InGEP->getOperand(i_nocapture: Op), BB: InBB);
633 }
634 }
635
636 Value *Base = FixedOperands[0];
637 GetElementPtrInst *NewGEP =
638 GetElementPtrInst::Create(PointeeType: FirstInst->getSourceElementType(), Ptr: Base,
639 IdxList: ArrayRef(FixedOperands).slice(N: 1), NW);
640 PHIArgMergedDebugLoc(Inst: 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.
651static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
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>(Val&: 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>(Val: L->getOperand(i_nocapture: 0))) {
667 bool IsAddressTaken = false;
668 for (User *U : AI->users()) {
669 if (isa<LoadInst>(Val: U)) continue;
670 if (StoreInst *SI = dyn_cast<StoreInst>(Val: U)) {
671 // If storing TO the alloca, then the address isn't taken.
672 if (SI->getOperand(i_nocapture: 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>(Val: L->getOperand(i_nocapture: 0)))
688 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val: GEP->getOperand(i_nocapture: 0)))
689 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
690 return false;
691
692 return true;
693}
694
695Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) {
696 LoadInst *FirstLI = cast<LoadInst>(Val: PN.getIncomingValue(i: 0));
697
698 if (!canReplaceOperandWithVariable(I: FirstLI, OpIdx: 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(i: 0) ||
714 !isSafeAndProfitableToSinkLoad(L: FirstLI))
715 return nullptr;
716
717 for (auto Incoming : drop_begin(RangeOrContainer: zip(t: PN.blocks(), u: PN.incoming_values()))) {
718 BasicBlock *InBB = std::get<0>(t&: Incoming);
719 Value *InVal = std::get<1>(t&: Incoming);
720 LoadInst *LI = dyn_cast<LoadInst>(Val: 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
728 if (!canReplaceOperandWithVariable(I: LI, OpIdx: 0))
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(L: LI))
734 return nullptr;
735
736 LoadAlignment = std::min(a: LoadAlignment, b: 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(Ty: FirstLI->getOperand(i_nocapture: 0)->getType(),
742 NumReservedValues: PN.getNumIncomingValues(),
743 NameStr: PN.getName()+".in");
744
745 Value *InVal = FirstLI->getOperand(i_nocapture: 0);
746 NewPN->addIncoming(V: InVal, BB: PN.getIncomingBlock(i: 0));
747 LoadInst *NewLI = new LoadInst(FirstLI->getType(), NewPN, "",
748 /*IsVolatile=*/false, LoadAlignment);
749 NewLI->copyMetadata(SrcInst: *FirstLI);
750
751 // Add all operands to the new PHI and combine TBAA metadata.
752 for (auto Incoming : drop_begin(RangeOrContainer: zip(t: PN.blocks(), u: PN.incoming_values()))) {
753 BasicBlock *BB = std::get<0>(t&: Incoming);
754 Value *V = std::get<1>(t&: Incoming);
755 LoadInst *LI = cast<LoadInst>(Val: V);
756 combineMetadataForCSE(K: NewLI, J: LI, DoesKMove: true);
757 Value *NewInVal = LI->getOperand(i_nocapture: 0);
758 if (NewInVal != InVal)
759 InVal = nullptr;
760 NewPN->addIncoming(V: 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(i_nocapture: 0, Val_nocapture: InVal);
767 delete NewPN;
768 } else {
769 InsertNewInstBefore(New: NewPN, Old: PN.getIterator());
770 }
771
772 PHIArgMergedDebugLoc(Inst: 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.
779Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) {
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>(Val: 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>(Val: 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(Elt: Zext->getOperand(i_nocapture: 0));
814 NumZexts++;
815 } else if (auto *C = dyn_cast<Constant>(Val: V)) {
816 // Make sure that constants can fit in the new type.
817 Constant *Trunc = getLosslessUnsignedTrunc(C, DestTy: NarrowType, DL);
818 if (!Trunc)
819 return nullptr;
820 NewIncoming.push_back(Elt: 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(Ty: NarrowType, NumReservedValues: NumIncomingValues,
841 NameStr: Phi.getName() + ".shrunk");
842 for (unsigned I = 0; I != NumIncomingValues; ++I)
843 NewPhi->addIncoming(V: NewIncoming[I], BB: Phi.getIncomingBlock(i: I));
844
845 InsertNewInstBefore(New: NewPhi, Old: Phi.getIterator());
846 auto *CI = CastInst::CreateZExtOrBitCast(S: NewPhi, Ty: 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.
859Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) {
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
865 Instruction *FirstInst = cast<Instruction>(Val: PN.getIncomingValue(i: 0));
866
867 if (isa<GetElementPtrInst>(Val: FirstInst))
868 return foldPHIArgGEPIntoPHI(PN);
869 if (isa<LoadInst>(Val: FirstInst))
870 return foldPHIArgLoadIntoPHI(PN);
871 if (isa<InsertValueInst>(Val: FirstInst))
872 return foldPHIArgInsertValueInstructionIntoPHI(PN);
873 if (isa<ExtractValueInst>(Val: FirstInst))
874 return foldPHIArgExtractValueInstructionIntoPHI(PN);
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>(Val: FirstInst)) {
884 CastSrcTy = FirstInst->getOperand(i: 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(From: PN.getType(), To: CastSrcTy))
890 return nullptr;
891 }
892 } else if (isa<BinaryOperator>(Val: FirstInst) || isa<CmpInst>(Val: FirstInst)) {
893 // Can fold binop, compare or shift here if the RHS is a constant,
894 // otherwise call FoldPHIArgBinOpIntoPHI.
895 ConstantOp = dyn_cast<Constant>(Val: FirstInst->getOperand(i: 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(RangeOrContainer: PN.incoming_values())) {
904 Instruction *I = dyn_cast<Instruction>(Val: V);
905 if (!I || !I->hasOneUser() || !I->isSameOperationAs(I: FirstInst))
906 return nullptr;
907 if (CastSrcTy) {
908 if (I->getOperand(i: 0)->getType() != CastSrcTy)
909 return nullptr; // Cast operation must match.
910 } else if (I->getOperand(i: 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(Ty: FirstInst->getOperand(i: 0)->getType(),
918 NumReservedValues: PN.getNumIncomingValues(),
919 NameStr: PN.getName()+".in");
920
921 Value *InVal = FirstInst->getOperand(i: 0);
922 NewPN->addIncoming(V: InVal, BB: PN.getIncomingBlock(i: 0));
923
924 // Add all operands to the new PHI.
925 for (auto Incoming : drop_begin(RangeOrContainer: zip(t: PN.blocks(), u: PN.incoming_values()))) {
926 BasicBlock *BB = std::get<0>(t&: Incoming);
927 Value *V = std::get<1>(t&: Incoming);
928 Value *NewInVal = cast<Instruction>(Val: V)->getOperand(i: 0);
929 if (NewInVal != InVal)
930 InVal = nullptr;
931 NewPN->addIncoming(V: 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(New: NewPN, Old: PN.getIterator());
942 PhiVal = NewPN;
943 }
944
945 // Insert and return the new operation.
946 if (CastInst *FirstCI = dyn_cast<CastInst>(Val: FirstInst)) {
947 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), S: PhiVal,
948 Ty: PN.getType());
949 PHIArgMergedDebugLoc(Inst: NewCI, PN);
950 return NewCI;
951 }
952
953 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: FirstInst)) {
954 BinOp = BinaryOperator::Create(Op: BinOp->getOpcode(), S1: PhiVal, S2: ConstantOp);
955 BinOp->copyIRFlags(V: PN.getIncomingValue(i: 0));
956
957 for (Value *V : drop_begin(RangeOrContainer: PN.incoming_values()))
958 BinOp->andIRFlags(V);
959
960 PHIArgMergedDebugLoc(Inst: BinOp, PN);
961 return BinOp;
962 }
963
964 CmpInst *CIOp = cast<CmpInst>(Val: FirstInst);
965 CmpInst *NewCI = CmpInst::Create(Op: CIOp->getOpcode(), Pred: CIOp->getPredicate(),
966 S1: PhiVal, S2: ConstantOp);
967 PHIArgMergedDebugLoc(Inst: 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(Ptr: 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>(Val: Op)) {
988 if (!PHIsEqualValue(PN: 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.
1002static ConstantInt *getAnyNonZeroConstInt(PHINode &PN) {
1003 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
1004 for (Value *V : PN.operands())
1005 if (auto *ConstVA = dyn_cast<ConstantInt>(Val: V))
1006 if (!ConstVA->isZero())
1007 return ConstVA;
1008 return ConstantInt::get(Ty: cast<IntegerType>(Val: PN.getType()), V: 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() <
1026 RHS.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(PtrVal: 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///
1062Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
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.
1065 SmallVector<PHIUsageRecord, 16> PHIUsers;
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(Elt: &FirstPhi);
1075 PHIsInspected.insert(Ptr: &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>(Val: U);
1082
1083 // If the user is a PHI, inspect its uses recursively.
1084 if (PHINode *UserPN = dyn_cast<PHINode>(Val: UserI)) {
1085 if (PHIsInspected.insert(Ptr: UserPN).second)
1086 PHIsToSlice.push_back(Elt: UserPN);
1087 continue;
1088 }
1089
1090 // Truncates are always ok.
1091 if (isa<TruncInst>(Val: UserI)) {
1092 PHIUsers.push_back(Elt: 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>(Val: UserI->user_back()) ||
1099 !isa<ConstantInt>(Val: UserI->getOperand(i: 1)))
1100 return nullptr;
1101
1102 // Bail on out of range shifts.
1103 unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
1104 if (cast<ConstantInt>(Val: UserI->getOperand(i: 1))->getValue().uge(RHS: SizeInBits))
1105 return nullptr;
1106
1107 unsigned Shift = cast<ConstantInt>(Val: UserI->getOperand(i: 1))->getZExtValue();
1108 PHIUsers.push_back(Elt: 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(t: PN->blocks(), u: PN->incoming_values())) {
1118 BasicBlock *BB = std::get<0>(t&: Incoming);
1119 Value *V = std::get<1>(t&: Incoming);
1120 InvokeInst *II = dyn_cast<InvokeInst>(Val: V);
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(I&: FirstPhi, V: PoisonValue::get(T: 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(Start: PHIUsers.begin(), End: 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.
1154 DenseMap<BasicBlock*, Value*> PredValues;
1155
1156 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1157 // introduce redundant PHIs.
1158 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
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, NumReservedValues: PN->getNumIncomingValues(),
1174 NameStr: PN->getName() + ".off" + Twine(Offset),
1175 InsertBefore: PN->getIterator());
1176 assert(EltPHI->getType() != PN->getType() &&
1177 "Truncate didn't shrink phi?");
1178
1179 for (auto Incoming : zip(t: PN->blocks(), u: PN->incoming_values())) {
1180 BasicBlock *Pred = std::get<0>(t&: Incoming);
1181 Value *InVal = std::get<1>(t&: 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(V: PredVal, BB: Pred);
1187 continue;
1188 }
1189
1190 // Handle the PHI self-reuse case.
1191 if (InVal == PN) {
1192 PredVal = EltPHI;
1193 EltPHI->addIncoming(V: PredVal, BB: 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(V: PredVal, BB: 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 LHS: Res, RHS: ConstantInt::get(Ty: InVal->getType(), V: Offset), Name: "extract");
1211 Res = Builder.CreateTrunc(V: Res, DestTy: Ty, Name: "extract.t");
1212 PredVal = Res;
1213 EltPHI->addIncoming(V: Res, BB: 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>(Val: InVal))
1220 if (PHIsInspected.count(Ptr: OldInVal)) {
1221 unsigned RefPHIId =
1222 find(Range&: PHIsToSlice, Val: OldInVal) - PHIsToSlice.begin();
1223 PHIUsers.push_back(
1224 Elt: PHIUsageRecord(RefPHIId, Offset, cast<Instruction>(Val: 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(I&: *PHIUsers[UserI].Inst, V: 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(T: FirstPhi.getType());
1242 for (PHINode *PHI : drop_begin(RangeOrContainer&: PHIsToSlice))
1243 replaceInstUsesWith(I&: *PHI, V: Poison);
1244 return replaceInstUsesWith(I&: FirstPhi, V: Poison);
1245}
1246
1247static Value *simplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
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.
1262 if (!all_of(Range: PN.operands(), P: IsaPred<ConstantInt>))
1263 return nullptr;
1264
1265 BasicBlock *BB = PN.getParent();
1266 // Do not bother with unreachable instructions.
1267 if (!DT.isReachableFromEntry(A: 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;
1274 SmallDenseMap<ConstantInt *, BasicBlock *, 8> SuccForValue;
1275 SmallDenseMap<BasicBlock *, unsigned, 8> SuccCount;
1276 auto AddSucc = [&](ConstantInt *C, BasicBlock *Succ) {
1277 SuccForValue[C] = Succ;
1278 ++SuccCount[Succ];
1279 };
1280 if (auto *BI = dyn_cast<CondBrInst>(Val: IDom->getTerminator())) {
1281 Cond = BI->getCondition();
1282 AddSucc(ConstantInt::getTrue(Context), BI->getSuccessor(i: 0));
1283 AddSucc(ConstantInt::getFalse(Context), BI->getSuccessor(i: 1));
1284 } else if (auto *SI = dyn_cast<SwitchInst>(Val: 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(t: PN.incoming_values(), u: PN.blocks())) {
1300 auto *Input = cast<ConstantInt>(Val&: std::get<0>(t&: Pair));
1301 BasicBlock *Pred = std::get<1>(t&: 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(Val: Input);
1307 return It != SuccForValue.end() && SuccCount[It->second] == 1 &&
1308 DT.dominates(BBE1: BasicBlockEdge(IDom, It->second),
1309 BBE2: 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>(Val: ConstantExpr::getNot(C: 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(V: 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
1347static Value *foldDependentIVs(PHINode &PN, IRBuilderBase &Builder) {
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(V: V2, P: m_c_BinOp(L: m_Specific(V: V1), R: m_BinOp(I&: Iv2Next))) ||
1357 match(V: V2, P: m_GEP(Ops: m_Specific(V: V1), Ops: m_BinOp(I&: Iv2Next)))) {
1358 Start = V1;
1359 IvNext = cast<Instruction>(Val: V2);
1360 return true;
1361 }
1362 return false;
1363 };
1364
1365 if (!MatchOuterIV(PN.getIncomingValue(i: 0), PN.getIncomingValue(i: 1)) &&
1366 !MatchOuterIV(PN.getIncomingValue(i: 1), PN.getIncomingValue(i: 0)))
1367 return nullptr;
1368
1369 PHINode *Iv2;
1370 Value *Iv2Start, *Iv2Step;
1371 if (!matchSimpleRecurrence(I: Iv2Next, P&: Iv2, Start&: Iv2Start, Step&: Iv2Step) ||
1372 Iv2->getParent() != BB)
1373 return nullptr;
1374
1375 auto *BO = dyn_cast<BinaryOperator>(Val: IvNext);
1376 Constant *Identity =
1377 BO ? ConstantExpr::getBinOpIdentity(Opcode: BO->getOpcode(), Ty: Iv2Start->getType())
1378 : Constant::getNullValue(Ty: Iv2Start->getType());
1379 if (Iv2Start != Identity)
1380 return nullptr;
1381
1382 Builder.SetInsertPoint(BB->getFirstInsertionPt());
1383 if (!BO) {
1384 auto *GEP = cast<GEPOperator>(Val: IvNext);
1385 return Builder.CreateGEP(Ty: GEP->getSourceElementType(), Ptr: Start, IdxList: Iv2, Name: "",
1386 NW: cast<GEPOperator>(Val: IvNext)->getNoWrapFlags());
1387 }
1388
1389 assert(BO->isCommutative() && "Must be commutative");
1390 Value *Res = Builder.CreateBinOp(Opc: BO->getOpcode(), LHS: Iv2, RHS: Start);
1391 cast<Instruction>(Val: Res)->copyIRFlags(V: BO);
1392 return Res;
1393}
1394
1395// PHINode simplification
1396//
1397Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
1398 if (Value *V = simplifyInstruction(I: &PN, Q: SQ.getWithInstruction(I: &PN)))
1399 return replaceInstUsesWith(I&: PN, V);
1400
1401 if (Instruction *Result = foldPHIArgZextsIntoPHI(Phi&: 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>(Val: PN.getIncomingValue(i: 0));
1410 auto *Inst1 = dyn_cast<Instruction>(Val: PN.getIncomingValue(i: 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(i: 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(Ptr: IV0);
1425 if (IV0 != IV0Stripped &&
1426 all_of(Range: PN.incoming_values(), P: [&CheckedIVs, IV0Stripped](Value *IV) {
1427 return !CheckedIVs.insert(Ptr: IV).second ||
1428 IV0Stripped == IV->stripPointerCasts();
1429 })) {
1430 return CastInst::CreatePointerCast(S: IV0Stripped, Ty: 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>(Val: PN.user_back());
1449 if (PHIUser->hasOneUse() &&
1450 (isa<BinaryOperator>(Val: PHIUser) || isa<UnaryOperator>(Val: PHIUser) ||
1451 isa<GetElementPtrInst>(Val: PHIUser)) &&
1452 PHIUser->user_back() == &PN) {
1453 return replaceInstUsesWith(I&: PN, V: PoisonValue::get(T: PN.getType()));
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(N: 3)) {
1470 SmallVector<Instruction *> DropPoisonFlags;
1471 bool AllUsesOfPhiEndsInCmp = all_of(Range: PN.users(), P: [&](User *U) {
1472 auto *CmpInst = dyn_cast<ICmpInst>(Val: 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(V: U, P: m_c_Or(L: m_Specific(V: &PN), R: m_Value()))) {
1477 DropPoisonFlags.push_back(Elt: cast<Instruction>(Val: U));
1478 CmpInst = dyn_cast<ICmpInst>(Val: U->user_back());
1479 }
1480 }
1481 if (!CmpInst || !isa<IntegerType>(Val: PN.getType()) ||
1482 !CmpInst->isEquality() || !match(V: CmpInst->getOperand(i_nocapture: 1), P: 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) {
1492 Instruction *CtxI = PN.getIncomingBlock(i: I)->getTerminator();
1493 Value *VA = PN.getIncomingValue(i: I);
1494 if (isKnownNonZero(V: VA, Q: getSimplifyQuery().getWithInstruction(I: CtxI))) {
1495 if (!NonZeroConst)
1496 NonZeroConst = getAnyNonZeroConstInt(PN);
1497 if (NonZeroConst != VA) {
1498 replaceOperand(I&: PN, OpNum: I, V: 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>(Val: PN.getIncomingValue(i: InValNo)))
1524 ++InValNo;
1525
1526 Value *NonPhiInVal =
1527 InValNo != NumIncomingVals ? PN.getIncomingValue(i: 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(i: InValNo);
1534 if (OpVal != NonPhiInVal && !isa<PHINode>(Val: 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: &PN, NonPhiInVal, ValueEqualPHIs))
1544 return replaceInstUsesWith(I&: PN, V: 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(Key: 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: I);
1557 BasicBlock *BBB = Preds[I];
1558 if (BBA != BBB) {
1559 Value *VA = PN.getIncomingValue(i: I);
1560 unsigned J = PN.getBasicBlockIndex(BB: BBB);
1561 Value *VB = PN.getIncomingValue(i: J);
1562 PN.setIncomingBlock(i: I, BB: BBB);
1563 PN.setIncomingValue(i: I, V: VB);
1564 PN.setIncomingBlock(i: J, BB: BBA);
1565 PN.setIncomingValue(i: J, V: 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(C&: Res.first->second, R: 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(I: &IdenticalPN))
1586 continue;
1587 // Just use that PHI instead then.
1588 ++NumPHICSEs;
1589 return replaceInstUsesWith(I&: PN, V: &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(Width: PN.getType()->getPrimitiveSizeInBits()))
1598 if (Instruction *Res = SliceUpIllegalIntegerPHI(FirstPhi&: PN))
1599 return Res;
1600
1601 // Ultimately, try to replace this Phi with a dominating condition.
1602 if (auto *V = simplifyUsingControlFlow(Self&: *this, PN, DT))
1603 return replaceInstUsesWith(I&: PN, V);
1604
1605 if (Value *Res = foldDependentIVs(PN, Builder))
1606 return replaceInstUsesWith(I&: PN, V: Res);
1607
1608 return nullptr;
1609}
1610