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/Support/CommandLine.h"
21 #include "llvm/Transforms/InstCombine/InstCombiner.h"
22 #include "llvm/Transforms/Utils/Local.h"
23
24 using namespace llvm;
25 using namespace llvm::PatternMatch;
26
27 #define DEBUG_TYPE "instcombine"
28
29 static cl::opt<unsigned>
30 MaxNumPhis("instcombine-max-num-phis", cl::init(512),
31 cl::desc("Maximum number phis to handle in intptr/ptrint folding"));
32
33 STATISTIC(NumPHIsOfInsertValues,
34 "Number of phi-of-insertvalue turned into insertvalue-of-phis");
35 STATISTIC(NumPHIsOfExtractValues,
36 "Number of phi-of-extractvalue turned into extractvalue-of-phi");
37 STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
38
39 /// The PHI arguments will be folded into a single operation with a PHI node
40 /// as input. The debug location of the single operation will be the merged
41 /// locations of the original PHI node arguments.
PHIArgMergedDebugLoc(Instruction * Inst,PHINode & PN)42 void InstCombinerImpl::PHIArgMergedDebugLoc(Instruction *Inst, PHINode &PN) {
43 auto *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
44 Inst->setDebugLoc(FirstInst->getDebugLoc());
45 // We do not expect a CallInst here, otherwise, N-way merging of DebugLoc
46 // will be inefficient.
47 assert(!isa<CallInst>(Inst));
48
49 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
50 auto *I = cast<Instruction>(PN.getIncomingValue(i));
51 Inst->applyMergedLocation(Inst->getDebugLoc(), I->getDebugLoc());
52 }
53 }
54
55 // Replace Integer typed PHI PN if the PHI's value is used as a pointer value.
56 // If there is an existing pointer typed PHI that produces the same value as PN,
57 // replace PN and the IntToPtr operation with it. Otherwise, synthesize a new
58 // PHI node:
59 //
60 // Case-1:
61 // bb1:
62 // int_init = PtrToInt(ptr_init)
63 // br label %bb2
64 // bb2:
65 // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
66 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
67 // ptr_val2 = IntToPtr(int_val)
68 // ...
69 // use(ptr_val2)
70 // ptr_val_inc = ...
71 // inc_val_inc = PtrToInt(ptr_val_inc)
72 //
73 // ==>
74 // bb1:
75 // br label %bb2
76 // bb2:
77 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
78 // ...
79 // use(ptr_val)
80 // ptr_val_inc = ...
81 //
82 // Case-2:
83 // bb1:
84 // int_ptr = BitCast(ptr_ptr)
85 // int_init = Load(int_ptr)
86 // br label %bb2
87 // bb2:
88 // int_val = PHI([int_init, %bb1], [int_val_inc, %bb2]
89 // ptr_val2 = IntToPtr(int_val)
90 // ...
91 // use(ptr_val2)
92 // ptr_val_inc = ...
93 // inc_val_inc = PtrToInt(ptr_val_inc)
94 // ==>
95 // bb1:
96 // ptr_init = Load(ptr_ptr)
97 // br label %bb2
98 // bb2:
99 // ptr_val = PHI([ptr_init, %bb1], [ptr_val_inc, %bb2]
100 // ...
101 // use(ptr_val)
102 // ptr_val_inc = ...
103 // ...
104 //
foldIntegerTypedPHI(PHINode & PN)105 Instruction *InstCombinerImpl::foldIntegerTypedPHI(PHINode &PN) {
106 if (!PN.getType()->isIntegerTy())
107 return nullptr;
108 if (!PN.hasOneUse())
109 return nullptr;
110
111 auto *IntToPtr = dyn_cast<IntToPtrInst>(PN.user_back());
112 if (!IntToPtr)
113 return nullptr;
114
115 // Check if the pointer is actually used as pointer:
116 auto HasPointerUse = [](Instruction *IIP) {
117 for (User *U : IIP->users()) {
118 Value *Ptr = nullptr;
119 if (LoadInst *LoadI = dyn_cast<LoadInst>(U)) {
120 Ptr = LoadI->getPointerOperand();
121 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
122 Ptr = SI->getPointerOperand();
123 } else if (GetElementPtrInst *GI = dyn_cast<GetElementPtrInst>(U)) {
124 Ptr = GI->getPointerOperand();
125 }
126
127 if (Ptr && Ptr == IIP)
128 return true;
129 }
130 return false;
131 };
132
133 if (!HasPointerUse(IntToPtr))
134 return nullptr;
135
136 if (DL.getPointerSizeInBits(IntToPtr->getAddressSpace()) !=
137 DL.getTypeSizeInBits(IntToPtr->getOperand(0)->getType()))
138 return nullptr;
139
140 SmallVector<Value *, 4> AvailablePtrVals;
141 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
142 Value *Arg = PN.getIncomingValue(i);
143
144 // First look backward:
145 if (auto *PI = dyn_cast<PtrToIntInst>(Arg)) {
146 AvailablePtrVals.emplace_back(PI->getOperand(0));
147 continue;
148 }
149
150 // Next look forward:
151 Value *ArgIntToPtr = nullptr;
152 for (User *U : Arg->users()) {
153 if (isa<IntToPtrInst>(U) && U->getType() == IntToPtr->getType() &&
154 (DT.dominates(cast<Instruction>(U), PN.getIncomingBlock(i)) ||
155 cast<Instruction>(U)->getParent() == PN.getIncomingBlock(i))) {
156 ArgIntToPtr = U;
157 break;
158 }
159 }
160
161 if (ArgIntToPtr) {
162 AvailablePtrVals.emplace_back(ArgIntToPtr);
163 continue;
164 }
165
166 // If Arg is defined by a PHI, allow it. This will also create
167 // more opportunities iteratively.
168 if (isa<PHINode>(Arg)) {
169 AvailablePtrVals.emplace_back(Arg);
170 continue;
171 }
172
173 // For a single use integer load:
174 auto *LoadI = dyn_cast<LoadInst>(Arg);
175 if (!LoadI)
176 return nullptr;
177
178 if (!LoadI->hasOneUse())
179 return nullptr;
180
181 // Push the integer typed Load instruction into the available
182 // value set, and fix it up later when the pointer typed PHI
183 // is synthesized.
184 AvailablePtrVals.emplace_back(LoadI);
185 }
186
187 // Now search for a matching PHI
188 auto *BB = PN.getParent();
189 assert(AvailablePtrVals.size() == PN.getNumIncomingValues() &&
190 "Not enough available ptr typed incoming values");
191 PHINode *MatchingPtrPHI = nullptr;
192 unsigned NumPhis = 0;
193 for (auto II = BB->begin(); II != BB->end(); II++, NumPhis++) {
194 // FIXME: consider handling this in AggressiveInstCombine
195 PHINode *PtrPHI = dyn_cast<PHINode>(II);
196 if (!PtrPHI)
197 break;
198 if (NumPhis > MaxNumPhis)
199 return nullptr;
200 if (PtrPHI == &PN || PtrPHI->getType() != IntToPtr->getType())
201 continue;
202 MatchingPtrPHI = PtrPHI;
203 for (unsigned i = 0; i != PtrPHI->getNumIncomingValues(); ++i) {
204 if (AvailablePtrVals[i] !=
205 PtrPHI->getIncomingValueForBlock(PN.getIncomingBlock(i))) {
206 MatchingPtrPHI = nullptr;
207 break;
208 }
209 }
210
211 if (MatchingPtrPHI)
212 break;
213 }
214
215 if (MatchingPtrPHI) {
216 assert(MatchingPtrPHI->getType() == IntToPtr->getType() &&
217 "Phi's Type does not match with IntToPtr");
218 // The PtrToCast + IntToPtr will be simplified later
219 return CastInst::CreateBitOrPointerCast(MatchingPtrPHI,
220 IntToPtr->getOperand(0)->getType());
221 }
222
223 // If it requires a conversion for every PHI operand, do not do it.
224 if (all_of(AvailablePtrVals, [&](Value *V) {
225 return (V->getType() != IntToPtr->getType()) || isa<IntToPtrInst>(V);
226 }))
227 return nullptr;
228
229 // If any of the operand that requires casting is a terminator
230 // instruction, do not do it. Similarly, do not do the transform if the value
231 // is PHI in a block with no insertion point, for example, a catchswitch
232 // block, since we will not be able to insert a cast after the PHI.
233 if (any_of(AvailablePtrVals, [&](Value *V) {
234 if (V->getType() == IntToPtr->getType())
235 return false;
236 auto *Inst = dyn_cast<Instruction>(V);
237 if (!Inst)
238 return false;
239 if (Inst->isTerminator())
240 return true;
241 auto *BB = Inst->getParent();
242 if (isa<PHINode>(Inst) && BB->getFirstInsertionPt() == BB->end())
243 return true;
244 return false;
245 }))
246 return nullptr;
247
248 PHINode *NewPtrPHI = PHINode::Create(
249 IntToPtr->getType(), PN.getNumIncomingValues(), PN.getName() + ".ptr");
250
251 InsertNewInstBefore(NewPtrPHI, PN);
252 SmallDenseMap<Value *, Instruction *> Casts;
253 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
254 auto *IncomingBB = PN.getIncomingBlock(i);
255 auto *IncomingVal = AvailablePtrVals[i];
256
257 if (IncomingVal->getType() == IntToPtr->getType()) {
258 NewPtrPHI->addIncoming(IncomingVal, IncomingBB);
259 continue;
260 }
261
262 #ifndef NDEBUG
263 LoadInst *LoadI = dyn_cast<LoadInst>(IncomingVal);
264 assert((isa<PHINode>(IncomingVal) ||
265 IncomingVal->getType()->isPointerTy() ||
266 (LoadI && LoadI->hasOneUse())) &&
267 "Can not replace LoadInst with multiple uses");
268 #endif
269 // Need to insert a BitCast.
270 // For an integer Load instruction with a single use, the load + IntToPtr
271 // cast will be simplified into a pointer load:
272 // %v = load i64, i64* %a.ip, align 8
273 // %v.cast = inttoptr i64 %v to float **
274 // ==>
275 // %v.ptrp = bitcast i64 * %a.ip to float **
276 // %v.cast = load float *, float ** %v.ptrp, align 8
277 Instruction *&CI = Casts[IncomingVal];
278 if (!CI) {
279 CI = CastInst::CreateBitOrPointerCast(IncomingVal, IntToPtr->getType(),
280 IncomingVal->getName() + ".ptr");
281 if (auto *IncomingI = dyn_cast<Instruction>(IncomingVal)) {
282 BasicBlock::iterator InsertPos(IncomingI);
283 InsertPos++;
284 BasicBlock *BB = IncomingI->getParent();
285 if (isa<PHINode>(IncomingI))
286 InsertPos = BB->getFirstInsertionPt();
287 assert(InsertPos != BB->end() && "should have checked above");
288 InsertNewInstBefore(CI, *InsertPos);
289 } else {
290 auto *InsertBB = &IncomingBB->getParent()->getEntryBlock();
291 InsertNewInstBefore(CI, *InsertBB->getFirstInsertionPt());
292 }
293 }
294 NewPtrPHI->addIncoming(CI, IncomingBB);
295 }
296
297 // The PtrToCast + IntToPtr will be simplified later
298 return CastInst::CreateBitOrPointerCast(NewPtrPHI,
299 IntToPtr->getOperand(0)->getType());
300 }
301
302 /// If we have something like phi [insertvalue(a,b,0), insertvalue(c,d,0)],
303 /// turn this into a phi[a,c] and phi[b,d] and a single insertvalue.
304 Instruction *
foldPHIArgInsertValueInstructionIntoPHI(PHINode & PN)305 InstCombinerImpl::foldPHIArgInsertValueInstructionIntoPHI(PHINode &PN) {
306 auto *FirstIVI = cast<InsertValueInst>(PN.getIncomingValue(0));
307
308 // Scan to see if all operands are `insertvalue`'s with the same indicies,
309 // and all have a single use.
310 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
311 auto *I = dyn_cast<InsertValueInst>(PN.getIncomingValue(i));
312 if (!I || !I->hasOneUser() || I->getIndices() != FirstIVI->getIndices())
313 return nullptr;
314 }
315
316 // For each operand of an `insertvalue`
317 std::array<PHINode *, 2> NewOperands;
318 for (int OpIdx : {0, 1}) {
319 auto *&NewOperand = NewOperands[OpIdx];
320 // Create a new PHI node to receive the values the operand has in each
321 // incoming basic block.
322 NewOperand = PHINode::Create(
323 FirstIVI->getOperand(OpIdx)->getType(), PN.getNumIncomingValues(),
324 FirstIVI->getOperand(OpIdx)->getName() + ".pn");
325 // And populate each operand's PHI with said values.
326 for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
327 NewOperand->addIncoming(
328 cast<InsertValueInst>(std::get<1>(Incoming))->getOperand(OpIdx),
329 std::get<0>(Incoming));
330 InsertNewInstBefore(NewOperand, PN);
331 }
332
333 // And finally, create `insertvalue` over the newly-formed PHI nodes.
334 auto *NewIVI = InsertValueInst::Create(NewOperands[0], NewOperands[1],
335 FirstIVI->getIndices(), PN.getName());
336
337 PHIArgMergedDebugLoc(NewIVI, PN);
338 ++NumPHIsOfInsertValues;
339 return NewIVI;
340 }
341
342 /// If we have something like phi [extractvalue(a,0), extractvalue(b,0)],
343 /// turn this into a phi[a,b] and a single extractvalue.
344 Instruction *
foldPHIArgExtractValueInstructionIntoPHI(PHINode & PN)345 InstCombinerImpl::foldPHIArgExtractValueInstructionIntoPHI(PHINode &PN) {
346 auto *FirstEVI = cast<ExtractValueInst>(PN.getIncomingValue(0));
347
348 // Scan to see if all operands are `extractvalue`'s with the same indicies,
349 // and all have a single use.
350 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
351 auto *I = dyn_cast<ExtractValueInst>(PN.getIncomingValue(i));
352 if (!I || !I->hasOneUser() || I->getIndices() != FirstEVI->getIndices() ||
353 I->getAggregateOperand()->getType() !=
354 FirstEVI->getAggregateOperand()->getType())
355 return nullptr;
356 }
357
358 // Create a new PHI node to receive the values the aggregate operand has
359 // in each incoming basic block.
360 auto *NewAggregateOperand = PHINode::Create(
361 FirstEVI->getAggregateOperand()->getType(), PN.getNumIncomingValues(),
362 FirstEVI->getAggregateOperand()->getName() + ".pn");
363 // And populate the PHI with said values.
364 for (auto Incoming : zip(PN.blocks(), PN.incoming_values()))
365 NewAggregateOperand->addIncoming(
366 cast<ExtractValueInst>(std::get<1>(Incoming))->getAggregateOperand(),
367 std::get<0>(Incoming));
368 InsertNewInstBefore(NewAggregateOperand, PN);
369
370 // And finally, create `extractvalue` over the newly-formed PHI nodes.
371 auto *NewEVI = ExtractValueInst::Create(NewAggregateOperand,
372 FirstEVI->getIndices(), PN.getName());
373
374 PHIArgMergedDebugLoc(NewEVI, PN);
375 ++NumPHIsOfExtractValues;
376 return NewEVI;
377 }
378
379 /// If we have something like phi [add (a,b), add(a,c)] and if a/b/c and the
380 /// adds all have a single user, turn this into a phi and a single binop.
foldPHIArgBinOpIntoPHI(PHINode & PN)381 Instruction *InstCombinerImpl::foldPHIArgBinOpIntoPHI(PHINode &PN) {
382 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
383 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
384 unsigned Opc = FirstInst->getOpcode();
385 Value *LHSVal = FirstInst->getOperand(0);
386 Value *RHSVal = FirstInst->getOperand(1);
387
388 Type *LHSType = LHSVal->getType();
389 Type *RHSType = RHSVal->getType();
390
391 // Scan to see if all operands are the same opcode, and all have one user.
392 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
393 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
394 if (!I || I->getOpcode() != Opc || !I->hasOneUser() ||
395 // Verify type of the LHS matches so we don't fold cmp's of different
396 // types.
397 I->getOperand(0)->getType() != LHSType ||
398 I->getOperand(1)->getType() != RHSType)
399 return nullptr;
400
401 // If they are CmpInst instructions, check their predicates
402 if (CmpInst *CI = dyn_cast<CmpInst>(I))
403 if (CI->getPredicate() != cast<CmpInst>(FirstInst)->getPredicate())
404 return nullptr;
405
406 // Keep track of which operand needs a phi node.
407 if (I->getOperand(0) != LHSVal) LHSVal = nullptr;
408 if (I->getOperand(1) != RHSVal) RHSVal = nullptr;
409 }
410
411 // If both LHS and RHS would need a PHI, don't do this transformation,
412 // because it would increase the number of PHIs entering the block,
413 // which leads to higher register pressure. This is especially
414 // bad when the PHIs are in the header of a loop.
415 if (!LHSVal && !RHSVal)
416 return nullptr;
417
418 // Otherwise, this is safe to transform!
419
420 Value *InLHS = FirstInst->getOperand(0);
421 Value *InRHS = FirstInst->getOperand(1);
422 PHINode *NewLHS = nullptr, *NewRHS = nullptr;
423 if (!LHSVal) {
424 NewLHS = PHINode::Create(LHSType, PN.getNumIncomingValues(),
425 FirstInst->getOperand(0)->getName() + ".pn");
426 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
427 InsertNewInstBefore(NewLHS, PN);
428 LHSVal = NewLHS;
429 }
430
431 if (!RHSVal) {
432 NewRHS = PHINode::Create(RHSType, PN.getNumIncomingValues(),
433 FirstInst->getOperand(1)->getName() + ".pn");
434 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
435 InsertNewInstBefore(NewRHS, PN);
436 RHSVal = NewRHS;
437 }
438
439 // Add all operands to the new PHIs.
440 if (NewLHS || NewRHS) {
441 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
442 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
443 if (NewLHS) {
444 Value *NewInLHS = InInst->getOperand(0);
445 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
446 }
447 if (NewRHS) {
448 Value *NewInRHS = InInst->getOperand(1);
449 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
450 }
451 }
452 }
453
454 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst)) {
455 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
456 LHSVal, RHSVal);
457 PHIArgMergedDebugLoc(NewCI, PN);
458 return NewCI;
459 }
460
461 BinaryOperator *BinOp = cast<BinaryOperator>(FirstInst);
462 BinaryOperator *NewBinOp =
463 BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
464
465 NewBinOp->copyIRFlags(PN.getIncomingValue(0));
466
467 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
468 NewBinOp->andIRFlags(PN.getIncomingValue(i));
469
470 PHIArgMergedDebugLoc(NewBinOp, PN);
471 return NewBinOp;
472 }
473
foldPHIArgGEPIntoPHI(PHINode & PN)474 Instruction *InstCombinerImpl::foldPHIArgGEPIntoPHI(PHINode &PN) {
475 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
476
477 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
478 FirstInst->op_end());
479 // This is true if all GEP bases are allocas and if all indices into them are
480 // constants.
481 bool AllBasePointersAreAllocas = true;
482
483 // We don't want to replace this phi if the replacement would require
484 // more than one phi, which leads to higher register pressure. This is
485 // especially bad when the PHIs are in the header of a loop.
486 bool NeededPhi = false;
487
488 bool AllInBounds = true;
489
490 // Scan to see if all operands are the same opcode, and all have one user.
491 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
492 GetElementPtrInst *GEP =
493 dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
494 if (!GEP || !GEP->hasOneUser() || GEP->getType() != FirstInst->getType() ||
495 GEP->getNumOperands() != FirstInst->getNumOperands())
496 return nullptr;
497
498 AllInBounds &= GEP->isInBounds();
499
500 // Keep track of whether or not all GEPs are of alloca pointers.
501 if (AllBasePointersAreAllocas &&
502 (!isa<AllocaInst>(GEP->getOperand(0)) ||
503 !GEP->hasAllConstantIndices()))
504 AllBasePointersAreAllocas = false;
505
506 // Compare the operand lists.
507 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
508 if (FirstInst->getOperand(op) == GEP->getOperand(op))
509 continue;
510
511 // Don't merge two GEPs when two operands differ (introducing phi nodes)
512 // if one of the PHIs has a constant for the index. The index may be
513 // substantially cheaper to compute for the constants, so making it a
514 // variable index could pessimize the path. This also handles the case
515 // for struct indices, which must always be constant.
516 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
517 isa<ConstantInt>(GEP->getOperand(op)))
518 return nullptr;
519
520 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
521 return nullptr;
522
523 // If we already needed a PHI for an earlier operand, and another operand
524 // also requires a PHI, we'd be introducing more PHIs than we're
525 // eliminating, which increases register pressure on entry to the PHI's
526 // block.
527 if (NeededPhi)
528 return nullptr;
529
530 FixedOperands[op] = nullptr; // Needs a PHI.
531 NeededPhi = true;
532 }
533 }
534
535 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
536 // bother doing this transformation. At best, this will just save a bit of
537 // offset calculation, but all the predecessors will have to materialize the
538 // stack address into a register anyway. We'd actually rather *clone* the
539 // load up into the predecessors so that we have a load of a gep of an alloca,
540 // which can usually all be folded into the load.
541 if (AllBasePointersAreAllocas)
542 return nullptr;
543
544 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
545 // that is variable.
546 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
547
548 bool HasAnyPHIs = false;
549 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
550 if (FixedOperands[i]) continue; // operand doesn't need a phi.
551 Value *FirstOp = FirstInst->getOperand(i);
552 PHINode *NewPN = PHINode::Create(FirstOp->getType(), e,
553 FirstOp->getName()+".pn");
554 InsertNewInstBefore(NewPN, PN);
555
556 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
557 OperandPhis[i] = NewPN;
558 FixedOperands[i] = NewPN;
559 HasAnyPHIs = true;
560 }
561
562
563 // Add all operands to the new PHIs.
564 if (HasAnyPHIs) {
565 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
566 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
567 BasicBlock *InBB = PN.getIncomingBlock(i);
568
569 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
570 if (PHINode *OpPhi = OperandPhis[op])
571 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
572 }
573 }
574
575 Value *Base = FixedOperands[0];
576 GetElementPtrInst *NewGEP =
577 GetElementPtrInst::Create(FirstInst->getSourceElementType(), Base,
578 makeArrayRef(FixedOperands).slice(1));
579 if (AllInBounds) NewGEP->setIsInBounds();
580 PHIArgMergedDebugLoc(NewGEP, PN);
581 return NewGEP;
582 }
583
584 /// Return true if we know that it is safe to sink the load out of the block
585 /// that defines it. This means that it must be obvious the value of the load is
586 /// not changed from the point of the load to the end of the block it is in.
587 ///
588 /// Finally, it is safe, but not profitable, to sink a load targeting a
589 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
590 /// to a register.
isSafeAndProfitableToSinkLoad(LoadInst * L)591 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
592 BasicBlock::iterator BBI = L->getIterator(), E = L->getParent()->end();
593
594 for (++BBI; BBI != E; ++BBI)
595 if (BBI->mayWriteToMemory())
596 return false;
597
598 // Check for non-address taken alloca. If not address-taken already, it isn't
599 // profitable to do this xform.
600 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
601 bool isAddressTaken = false;
602 for (User *U : AI->users()) {
603 if (isa<LoadInst>(U)) continue;
604 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
605 // If storing TO the alloca, then the address isn't taken.
606 if (SI->getOperand(1) == AI) continue;
607 }
608 isAddressTaken = true;
609 break;
610 }
611
612 if (!isAddressTaken && AI->isStaticAlloca())
613 return false;
614 }
615
616 // If this load is a load from a GEP with a constant offset from an alloca,
617 // then we don't want to sink it. In its present form, it will be
618 // load [constant stack offset]. Sinking it will cause us to have to
619 // materialize the stack addresses in each predecessor in a register only to
620 // do a shared load from register in the successor.
621 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
622 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
623 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
624 return false;
625
626 return true;
627 }
628
foldPHIArgLoadIntoPHI(PHINode & PN)629 Instruction *InstCombinerImpl::foldPHIArgLoadIntoPHI(PHINode &PN) {
630 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
631
632 // FIXME: This is overconservative; this transform is allowed in some cases
633 // for atomic operations.
634 if (FirstLI->isAtomic())
635 return nullptr;
636
637 // When processing loads, we need to propagate two bits of information to the
638 // sunk load: whether it is volatile, and what its alignment is. We currently
639 // don't sink loads when some have their alignment specified and some don't.
640 // visitLoadInst will propagate an alignment onto the load when TD is around,
641 // and if TD isn't around, we can't handle the mixed case.
642 bool isVolatile = FirstLI->isVolatile();
643 Align LoadAlignment = FirstLI->getAlign();
644 unsigned LoadAddrSpace = FirstLI->getPointerAddressSpace();
645
646 // We can't sink the load if the loaded value could be modified between the
647 // load and the PHI.
648 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
649 !isSafeAndProfitableToSinkLoad(FirstLI))
650 return nullptr;
651
652 // If the PHI is of volatile loads and the load block has multiple
653 // successors, sinking it would remove a load of the volatile value from
654 // the path through the other successor.
655 if (isVolatile &&
656 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
657 return nullptr;
658
659 // Check to see if all arguments are the same operation.
660 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
661 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
662 if (!LI || !LI->hasOneUser())
663 return nullptr;
664
665 // We can't sink the load if the loaded value could be modified between
666 // the load and the PHI.
667 if (LI->isVolatile() != isVolatile ||
668 LI->getParent() != PN.getIncomingBlock(i) ||
669 LI->getPointerAddressSpace() != LoadAddrSpace ||
670 !isSafeAndProfitableToSinkLoad(LI))
671 return nullptr;
672
673 LoadAlignment = std::min(LoadAlignment, Align(LI->getAlign()));
674
675 // If the PHI is of volatile loads and the load block has multiple
676 // successors, sinking it would remove a load of the volatile value from
677 // the path through the other successor.
678 if (isVolatile &&
679 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
680 return nullptr;
681 }
682
683 // Okay, they are all the same operation. Create a new PHI node of the
684 // correct type, and PHI together all of the LHS's of the instructions.
685 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
686 PN.getNumIncomingValues(),
687 PN.getName()+".in");
688
689 Value *InVal = FirstLI->getOperand(0);
690 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
691 LoadInst *NewLI =
692 new LoadInst(FirstLI->getType(), NewPN, "", isVolatile, LoadAlignment);
693
694 unsigned KnownIDs[] = {
695 LLVMContext::MD_tbaa,
696 LLVMContext::MD_range,
697 LLVMContext::MD_invariant_load,
698 LLVMContext::MD_alias_scope,
699 LLVMContext::MD_noalias,
700 LLVMContext::MD_nonnull,
701 LLVMContext::MD_align,
702 LLVMContext::MD_dereferenceable,
703 LLVMContext::MD_dereferenceable_or_null,
704 LLVMContext::MD_access_group,
705 };
706
707 for (unsigned ID : KnownIDs)
708 NewLI->setMetadata(ID, FirstLI->getMetadata(ID));
709
710 // Add all operands to the new PHI and combine TBAA metadata.
711 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
712 LoadInst *LI = cast<LoadInst>(PN.getIncomingValue(i));
713 combineMetadata(NewLI, LI, KnownIDs, true);
714 Value *NewInVal = LI->getOperand(0);
715 if (NewInVal != InVal)
716 InVal = nullptr;
717 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
718 }
719
720 if (InVal) {
721 // The new PHI unions all of the same values together. This is really
722 // common, so we handle it intelligently here for compile-time speed.
723 NewLI->setOperand(0, InVal);
724 delete NewPN;
725 } else {
726 InsertNewInstBefore(NewPN, PN);
727 }
728
729 // If this was a volatile load that we are merging, make sure to loop through
730 // and mark all the input loads as non-volatile. If we don't do this, we will
731 // insert a new volatile load and the old ones will not be deletable.
732 if (isVolatile)
733 for (Value *IncValue : PN.incoming_values())
734 cast<LoadInst>(IncValue)->setVolatile(false);
735
736 PHIArgMergedDebugLoc(NewLI, PN);
737 return NewLI;
738 }
739
740 /// TODO: This function could handle other cast types, but then it might
741 /// require special-casing a cast from the 'i1' type. See the comment in
742 /// FoldPHIArgOpIntoPHI() about pessimizing illegal integer types.
foldPHIArgZextsIntoPHI(PHINode & Phi)743 Instruction *InstCombinerImpl::foldPHIArgZextsIntoPHI(PHINode &Phi) {
744 // We cannot create a new instruction after the PHI if the terminator is an
745 // EHPad because there is no valid insertion point.
746 if (Instruction *TI = Phi.getParent()->getTerminator())
747 if (TI->isEHPad())
748 return nullptr;
749
750 // Early exit for the common case of a phi with two operands. These are
751 // handled elsewhere. See the comment below where we check the count of zexts
752 // and constants for more details.
753 unsigned NumIncomingValues = Phi.getNumIncomingValues();
754 if (NumIncomingValues < 3)
755 return nullptr;
756
757 // Find the narrower type specified by the first zext.
758 Type *NarrowType = nullptr;
759 for (Value *V : Phi.incoming_values()) {
760 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
761 NarrowType = Zext->getSrcTy();
762 break;
763 }
764 }
765 if (!NarrowType)
766 return nullptr;
767
768 // Walk the phi operands checking that we only have zexts or constants that
769 // we can shrink for free. Store the new operands for the new phi.
770 SmallVector<Value *, 4> NewIncoming;
771 unsigned NumZexts = 0;
772 unsigned NumConsts = 0;
773 for (Value *V : Phi.incoming_values()) {
774 if (auto *Zext = dyn_cast<ZExtInst>(V)) {
775 // All zexts must be identical and have one user.
776 if (Zext->getSrcTy() != NarrowType || !Zext->hasOneUser())
777 return nullptr;
778 NewIncoming.push_back(Zext->getOperand(0));
779 NumZexts++;
780 } else if (auto *C = dyn_cast<Constant>(V)) {
781 // Make sure that constants can fit in the new type.
782 Constant *Trunc = ConstantExpr::getTrunc(C, NarrowType);
783 if (ConstantExpr::getZExt(Trunc, C->getType()) != C)
784 return nullptr;
785 NewIncoming.push_back(Trunc);
786 NumConsts++;
787 } else {
788 // If it's not a cast or a constant, bail out.
789 return nullptr;
790 }
791 }
792
793 // The more common cases of a phi with no constant operands or just one
794 // variable operand are handled by FoldPHIArgOpIntoPHI() and foldOpIntoPhi()
795 // respectively. foldOpIntoPhi() wants to do the opposite transform that is
796 // performed here. It tries to replicate a cast in the phi operand's basic
797 // block to expose other folding opportunities. Thus, InstCombine will
798 // infinite loop without this check.
799 if (NumConsts == 0 || NumZexts < 2)
800 return nullptr;
801
802 // All incoming values are zexts or constants that are safe to truncate.
803 // Create a new phi node of the narrow type, phi together all of the new
804 // operands, and zext the result back to the original type.
805 PHINode *NewPhi = PHINode::Create(NarrowType, NumIncomingValues,
806 Phi.getName() + ".shrunk");
807 for (unsigned i = 0; i != NumIncomingValues; ++i)
808 NewPhi->addIncoming(NewIncoming[i], Phi.getIncomingBlock(i));
809
810 InsertNewInstBefore(NewPhi, Phi);
811 return CastInst::CreateZExtOrBitCast(NewPhi, Phi.getType());
812 }
813
814 /// If all operands to a PHI node are the same "unary" operator and they all are
815 /// only used by the PHI, PHI together their inputs, and do the operation once,
816 /// to the result of the PHI.
foldPHIArgOpIntoPHI(PHINode & PN)817 Instruction *InstCombinerImpl::foldPHIArgOpIntoPHI(PHINode &PN) {
818 // We cannot create a new instruction after the PHI if the terminator is an
819 // EHPad because there is no valid insertion point.
820 if (Instruction *TI = PN.getParent()->getTerminator())
821 if (TI->isEHPad())
822 return nullptr;
823
824 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
825
826 if (isa<GetElementPtrInst>(FirstInst))
827 return foldPHIArgGEPIntoPHI(PN);
828 if (isa<LoadInst>(FirstInst))
829 return foldPHIArgLoadIntoPHI(PN);
830 if (isa<InsertValueInst>(FirstInst))
831 return foldPHIArgInsertValueInstructionIntoPHI(PN);
832 if (isa<ExtractValueInst>(FirstInst))
833 return foldPHIArgExtractValueInstructionIntoPHI(PN);
834
835 // Scan the instruction, looking for input operations that can be folded away.
836 // If all input operands to the phi are the same instruction (e.g. a cast from
837 // the same type or "+42") we can pull the operation through the PHI, reducing
838 // code size and simplifying code.
839 Constant *ConstantOp = nullptr;
840 Type *CastSrcTy = nullptr;
841
842 if (isa<CastInst>(FirstInst)) {
843 CastSrcTy = FirstInst->getOperand(0)->getType();
844
845 // Be careful about transforming integer PHIs. We don't want to pessimize
846 // the code by turning an i32 into an i1293.
847 if (PN.getType()->isIntegerTy() && CastSrcTy->isIntegerTy()) {
848 if (!shouldChangeType(PN.getType(), CastSrcTy))
849 return nullptr;
850 }
851 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
852 // Can fold binop, compare or shift here if the RHS is a constant,
853 // otherwise call FoldPHIArgBinOpIntoPHI.
854 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
855 if (!ConstantOp)
856 return foldPHIArgBinOpIntoPHI(PN);
857 } else {
858 return nullptr; // Cannot fold this operation.
859 }
860
861 // Check to see if all arguments are the same operation.
862 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
863 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
864 if (!I || !I->hasOneUser() || !I->isSameOperationAs(FirstInst))
865 return nullptr;
866 if (CastSrcTy) {
867 if (I->getOperand(0)->getType() != CastSrcTy)
868 return nullptr; // Cast operation must match.
869 } else if (I->getOperand(1) != ConstantOp) {
870 return nullptr;
871 }
872 }
873
874 // Okay, they are all the same operation. Create a new PHI node of the
875 // correct type, and PHI together all of the LHS's of the instructions.
876 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
877 PN.getNumIncomingValues(),
878 PN.getName()+".in");
879
880 Value *InVal = FirstInst->getOperand(0);
881 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
882
883 // Add all operands to the new PHI.
884 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
885 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
886 if (NewInVal != InVal)
887 InVal = nullptr;
888 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
889 }
890
891 Value *PhiVal;
892 if (InVal) {
893 // The new PHI unions all of the same values together. This is really
894 // common, so we handle it intelligently here for compile-time speed.
895 PhiVal = InVal;
896 delete NewPN;
897 } else {
898 InsertNewInstBefore(NewPN, PN);
899 PhiVal = NewPN;
900 }
901
902 // Insert and return the new operation.
903 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst)) {
904 CastInst *NewCI = CastInst::Create(FirstCI->getOpcode(), PhiVal,
905 PN.getType());
906 PHIArgMergedDebugLoc(NewCI, PN);
907 return NewCI;
908 }
909
910 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst)) {
911 BinOp = BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
912 BinOp->copyIRFlags(PN.getIncomingValue(0));
913
914 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i)
915 BinOp->andIRFlags(PN.getIncomingValue(i));
916
917 PHIArgMergedDebugLoc(BinOp, PN);
918 return BinOp;
919 }
920
921 CmpInst *CIOp = cast<CmpInst>(FirstInst);
922 CmpInst *NewCI = CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
923 PhiVal, ConstantOp);
924 PHIArgMergedDebugLoc(NewCI, PN);
925 return NewCI;
926 }
927
928 /// Return true if this PHI node is only used by a PHI node cycle that is dead.
DeadPHICycle(PHINode * PN,SmallPtrSetImpl<PHINode * > & PotentiallyDeadPHIs)929 static bool DeadPHICycle(PHINode *PN,
930 SmallPtrSetImpl<PHINode*> &PotentiallyDeadPHIs) {
931 if (PN->use_empty()) return true;
932 if (!PN->hasOneUse()) return false;
933
934 // Remember this node, and if we find the cycle, return.
935 if (!PotentiallyDeadPHIs.insert(PN).second)
936 return true;
937
938 // Don't scan crazily complex things.
939 if (PotentiallyDeadPHIs.size() == 16)
940 return false;
941
942 if (PHINode *PU = dyn_cast<PHINode>(PN->user_back()))
943 return DeadPHICycle(PU, PotentiallyDeadPHIs);
944
945 return false;
946 }
947
948 /// Return true if this phi node is always equal to NonPhiInVal.
949 /// This happens with mutually cyclic phi nodes like:
950 /// z = some value; x = phi (y, z); y = phi (x, z)
PHIsEqualValue(PHINode * PN,Value * NonPhiInVal,SmallPtrSetImpl<PHINode * > & ValueEqualPHIs)951 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
952 SmallPtrSetImpl<PHINode*> &ValueEqualPHIs) {
953 // See if we already saw this PHI node.
954 if (!ValueEqualPHIs.insert(PN).second)
955 return true;
956
957 // Don't scan crazily complex things.
958 if (ValueEqualPHIs.size() == 16)
959 return false;
960
961 // Scan the operands to see if they are either phi nodes or are equal to
962 // the value.
963 for (Value *Op : PN->incoming_values()) {
964 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
965 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
966 return false;
967 } else if (Op != NonPhiInVal)
968 return false;
969 }
970
971 return true;
972 }
973
974 /// Return an existing non-zero constant if this phi node has one, otherwise
975 /// return constant 1.
GetAnyNonZeroConstInt(PHINode & PN)976 static ConstantInt *GetAnyNonZeroConstInt(PHINode &PN) {
977 assert(isa<IntegerType>(PN.getType()) && "Expect only integer type phi");
978 for (Value *V : PN.operands())
979 if (auto *ConstVA = dyn_cast<ConstantInt>(V))
980 if (!ConstVA->isZero())
981 return ConstVA;
982 return ConstantInt::get(cast<IntegerType>(PN.getType()), 1);
983 }
984
985 namespace {
986 struct PHIUsageRecord {
987 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
988 unsigned Shift; // The amount shifted.
989 Instruction *Inst; // The trunc instruction.
990
PHIUsageRecord__anonc3db26eb0411::PHIUsageRecord991 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
992 : PHIId(pn), Shift(Sh), Inst(User) {}
993
operator <__anonc3db26eb0411::PHIUsageRecord994 bool operator<(const PHIUsageRecord &RHS) const {
995 if (PHIId < RHS.PHIId) return true;
996 if (PHIId > RHS.PHIId) return false;
997 if (Shift < RHS.Shift) return true;
998 if (Shift > RHS.Shift) return false;
999 return Inst->getType()->getPrimitiveSizeInBits() <
1000 RHS.Inst->getType()->getPrimitiveSizeInBits();
1001 }
1002 };
1003
1004 struct LoweredPHIRecord {
1005 PHINode *PN; // The PHI that was lowered.
1006 unsigned Shift; // The amount shifted.
1007 unsigned Width; // The width extracted.
1008
LoweredPHIRecord__anonc3db26eb0411::LoweredPHIRecord1009 LoweredPHIRecord(PHINode *pn, unsigned Sh, Type *Ty)
1010 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
1011
1012 // Ctor form used by DenseMap.
LoweredPHIRecord__anonc3db26eb0411::LoweredPHIRecord1013 LoweredPHIRecord(PHINode *pn, unsigned Sh)
1014 : PN(pn), Shift(Sh), Width(0) {}
1015 };
1016 } // namespace
1017
1018 namespace llvm {
1019 template<>
1020 struct DenseMapInfo<LoweredPHIRecord> {
getEmptyKeyllvm::DenseMapInfo1021 static inline LoweredPHIRecord getEmptyKey() {
1022 return LoweredPHIRecord(nullptr, 0);
1023 }
getTombstoneKeyllvm::DenseMapInfo1024 static inline LoweredPHIRecord getTombstoneKey() {
1025 return LoweredPHIRecord(nullptr, 1);
1026 }
getHashValuellvm::DenseMapInfo1027 static unsigned getHashValue(const LoweredPHIRecord &Val) {
1028 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
1029 (Val.Width>>3);
1030 }
isEqualllvm::DenseMapInfo1031 static bool isEqual(const LoweredPHIRecord &LHS,
1032 const LoweredPHIRecord &RHS) {
1033 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
1034 LHS.Width == RHS.Width;
1035 }
1036 };
1037 } // namespace llvm
1038
1039
1040 /// This is an integer PHI and we know that it has an illegal type: see if it is
1041 /// only used by trunc or trunc(lshr) operations. If so, we split the PHI into
1042 /// the various pieces being extracted. This sort of thing is introduced when
1043 /// SROA promotes an aggregate to large integer values.
1044 ///
1045 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
1046 /// inttoptr. We should produce new PHIs in the right type.
1047 ///
SliceUpIllegalIntegerPHI(PHINode & FirstPhi)1048 Instruction *InstCombinerImpl::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
1049 // PHIUsers - Keep track of all of the truncated values extracted from a set
1050 // of PHIs, along with their offset. These are the things we want to rewrite.
1051 SmallVector<PHIUsageRecord, 16> PHIUsers;
1052
1053 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
1054 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
1055 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
1056 // check the uses of (to ensure they are all extracts).
1057 SmallVector<PHINode*, 8> PHIsToSlice;
1058 SmallPtrSet<PHINode*, 8> PHIsInspected;
1059
1060 PHIsToSlice.push_back(&FirstPhi);
1061 PHIsInspected.insert(&FirstPhi);
1062
1063 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
1064 PHINode *PN = PHIsToSlice[PHIId];
1065
1066 // Scan the input list of the PHI. If any input is an invoke, and if the
1067 // input is defined in the predecessor, then we won't be split the critical
1068 // edge which is required to insert a truncate. Because of this, we have to
1069 // bail out.
1070 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1071 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
1072 if (!II) continue;
1073 if (II->getParent() != PN->getIncomingBlock(i))
1074 continue;
1075
1076 // If we have a phi, and if it's directly in the predecessor, then we have
1077 // a critical edge where we need to put the truncate. Since we can't
1078 // split the edge in instcombine, we have to bail out.
1079 return nullptr;
1080 }
1081
1082 for (User *U : PN->users()) {
1083 Instruction *UserI = cast<Instruction>(U);
1084
1085 // If the user is a PHI, inspect its uses recursively.
1086 if (PHINode *UserPN = dyn_cast<PHINode>(UserI)) {
1087 if (PHIsInspected.insert(UserPN).second)
1088 PHIsToSlice.push_back(UserPN);
1089 continue;
1090 }
1091
1092 // Truncates are always ok.
1093 if (isa<TruncInst>(UserI)) {
1094 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, UserI));
1095 continue;
1096 }
1097
1098 // Otherwise it must be a lshr which can only be used by one trunc.
1099 if (UserI->getOpcode() != Instruction::LShr ||
1100 !UserI->hasOneUse() || !isa<TruncInst>(UserI->user_back()) ||
1101 !isa<ConstantInt>(UserI->getOperand(1)))
1102 return nullptr;
1103
1104 // Bail on out of range shifts.
1105 unsigned SizeInBits = UserI->getType()->getScalarSizeInBits();
1106 if (cast<ConstantInt>(UserI->getOperand(1))->getValue().uge(SizeInBits))
1107 return nullptr;
1108
1109 unsigned Shift = cast<ConstantInt>(UserI->getOperand(1))->getZExtValue();
1110 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, UserI->user_back()));
1111 }
1112 }
1113
1114 // If we have no users, they must be all self uses, just nuke the PHI.
1115 if (PHIUsers.empty())
1116 return replaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
1117
1118 // If this phi node is transformable, create new PHIs for all the pieces
1119 // extracted out of it. First, sort the users by their offset and size.
1120 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
1121
1122 LLVM_DEBUG(dbgs() << "SLICING UP PHI: " << FirstPhi << '\n';
1123 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i) dbgs()
1124 << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] << '\n';);
1125
1126 // PredValues - This is a temporary used when rewriting PHI nodes. It is
1127 // hoisted out here to avoid construction/destruction thrashing.
1128 DenseMap<BasicBlock*, Value*> PredValues;
1129
1130 // ExtractedVals - Each new PHI we introduce is saved here so we don't
1131 // introduce redundant PHIs.
1132 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
1133
1134 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
1135 unsigned PHIId = PHIUsers[UserI].PHIId;
1136 PHINode *PN = PHIsToSlice[PHIId];
1137 unsigned Offset = PHIUsers[UserI].Shift;
1138 Type *Ty = PHIUsers[UserI].Inst->getType();
1139
1140 PHINode *EltPHI;
1141
1142 // If we've already lowered a user like this, reuse the previously lowered
1143 // value.
1144 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == nullptr) {
1145
1146 // Otherwise, Create the new PHI node for this user.
1147 EltPHI = PHINode::Create(Ty, PN->getNumIncomingValues(),
1148 PN->getName()+".off"+Twine(Offset), PN);
1149 assert(EltPHI->getType() != PN->getType() &&
1150 "Truncate didn't shrink phi?");
1151
1152 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1153 BasicBlock *Pred = PN->getIncomingBlock(i);
1154 Value *&PredVal = PredValues[Pred];
1155
1156 // If we already have a value for this predecessor, reuse it.
1157 if (PredVal) {
1158 EltPHI->addIncoming(PredVal, Pred);
1159 continue;
1160 }
1161
1162 // Handle the PHI self-reuse case.
1163 Value *InVal = PN->getIncomingValue(i);
1164 if (InVal == PN) {
1165 PredVal = EltPHI;
1166 EltPHI->addIncoming(PredVal, Pred);
1167 continue;
1168 }
1169
1170 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
1171 // If the incoming value was a PHI, and if it was one of the PHIs we
1172 // already rewrote it, just use the lowered value.
1173 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
1174 PredVal = Res;
1175 EltPHI->addIncoming(PredVal, Pred);
1176 continue;
1177 }
1178 }
1179
1180 // Otherwise, do an extract in the predecessor.
1181 Builder.SetInsertPoint(Pred->getTerminator());
1182 Value *Res = InVal;
1183 if (Offset)
1184 Res = Builder.CreateLShr(Res, ConstantInt::get(InVal->getType(),
1185 Offset), "extract");
1186 Res = Builder.CreateTrunc(Res, Ty, "extract.t");
1187 PredVal = Res;
1188 EltPHI->addIncoming(Res, Pred);
1189
1190 // If the incoming value was a PHI, and if it was one of the PHIs we are
1191 // rewriting, we will ultimately delete the code we inserted. This
1192 // means we need to revisit that PHI to make sure we extract out the
1193 // needed piece.
1194 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
1195 if (PHIsInspected.count(OldInVal)) {
1196 unsigned RefPHIId =
1197 find(PHIsToSlice, OldInVal) - PHIsToSlice.begin();
1198 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
1199 cast<Instruction>(Res)));
1200 ++UserE;
1201 }
1202 }
1203 PredValues.clear();
1204
1205 LLVM_DEBUG(dbgs() << " Made element PHI for offset " << Offset << ": "
1206 << *EltPHI << '\n');
1207 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
1208 }
1209
1210 // Replace the use of this piece with the PHI node.
1211 replaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
1212 }
1213
1214 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
1215 // with undefs.
1216 Value *Undef = UndefValue::get(FirstPhi.getType());
1217 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
1218 replaceInstUsesWith(*PHIsToSlice[i], Undef);
1219 return replaceInstUsesWith(FirstPhi, Undef);
1220 }
1221
SimplifyUsingControlFlow(InstCombiner & Self,PHINode & PN,const DominatorTree & DT)1222 static Value *SimplifyUsingControlFlow(InstCombiner &Self, PHINode &PN,
1223 const DominatorTree &DT) {
1224 // Simplify the following patterns:
1225 // if (cond)
1226 // / \
1227 // ... ...
1228 // \ /
1229 // phi [true] [false]
1230 if (!PN.getType()->isIntegerTy(1))
1231 return nullptr;
1232
1233 if (PN.getNumOperands() != 2)
1234 return nullptr;
1235
1236 // Make sure all inputs are constants.
1237 if (!all_of(PN.operands(), [](Value *V) { return isa<ConstantInt>(V); }))
1238 return nullptr;
1239
1240 BasicBlock *BB = PN.getParent();
1241 // Do not bother with unreachable instructions.
1242 if (!DT.isReachableFromEntry(BB))
1243 return nullptr;
1244
1245 // Same inputs.
1246 if (PN.getOperand(0) == PN.getOperand(1))
1247 return PN.getOperand(0);
1248
1249 BasicBlock *TruePred = nullptr, *FalsePred = nullptr;
1250 for (auto *Pred : predecessors(BB)) {
1251 auto *Input = cast<ConstantInt>(PN.getIncomingValueForBlock(Pred));
1252 if (Input->isAllOnesValue())
1253 TruePred = Pred;
1254 else
1255 FalsePred = Pred;
1256 }
1257 assert(TruePred && FalsePred && "Must be!");
1258
1259 // Check which edge of the dominator dominates the true input. If it is the
1260 // false edge, we should invert the condition.
1261 auto *IDom = DT.getNode(BB)->getIDom()->getBlock();
1262 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
1263 if (!BI || BI->isUnconditional())
1264 return nullptr;
1265
1266 // Check that edges outgoing from the idom's terminators dominate respective
1267 // inputs of the Phi.
1268 BasicBlockEdge TrueOutEdge(IDom, BI->getSuccessor(0));
1269 BasicBlockEdge FalseOutEdge(IDom, BI->getSuccessor(1));
1270
1271 BasicBlockEdge TrueIncEdge(TruePred, BB);
1272 BasicBlockEdge FalseIncEdge(FalsePred, BB);
1273
1274 auto *Cond = BI->getCondition();
1275 if (DT.dominates(TrueOutEdge, TrueIncEdge) &&
1276 DT.dominates(FalseOutEdge, FalseIncEdge))
1277 // This Phi is actually equivalent to branching condition of IDom.
1278 return Cond;
1279 else if (DT.dominates(TrueOutEdge, FalseIncEdge) &&
1280 DT.dominates(FalseOutEdge, TrueIncEdge)) {
1281 // This Phi is actually opposite to branching condition of IDom. We invert
1282 // the condition that will potentially open up some opportunities for
1283 // sinking.
1284 auto InsertPt = BB->getFirstInsertionPt();
1285 if (InsertPt != BB->end()) {
1286 Self.Builder.SetInsertPoint(&*InsertPt);
1287 return Self.Builder.CreateNot(Cond);
1288 }
1289 }
1290
1291 return nullptr;
1292 }
1293
1294 // PHINode simplification
1295 //
visitPHINode(PHINode & PN)1296 Instruction *InstCombinerImpl::visitPHINode(PHINode &PN) {
1297 if (Value *V = SimplifyInstruction(&PN, SQ.getWithInstruction(&PN)))
1298 return replaceInstUsesWith(PN, V);
1299
1300 if (Instruction *Result = foldPHIArgZextsIntoPHI(PN))
1301 return Result;
1302
1303 // If all PHI operands are the same operation, pull them through the PHI,
1304 // reducing code size.
1305 if (isa<Instruction>(PN.getIncomingValue(0)) &&
1306 isa<Instruction>(PN.getIncomingValue(1)) &&
1307 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
1308 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
1309 PN.getIncomingValue(0)->hasOneUser())
1310 if (Instruction *Result = foldPHIArgOpIntoPHI(PN))
1311 return Result;
1312
1313 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
1314 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
1315 // PHI)... break the cycle.
1316 if (PN.hasOneUse()) {
1317 if (Instruction *Result = foldIntegerTypedPHI(PN))
1318 return Result;
1319
1320 Instruction *PHIUser = cast<Instruction>(PN.user_back());
1321 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
1322 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
1323 PotentiallyDeadPHIs.insert(&PN);
1324 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
1325 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1326 }
1327
1328 // If this phi has a single use, and if that use just computes a value for
1329 // the next iteration of a loop, delete the phi. This occurs with unused
1330 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
1331 // common case here is good because the only other things that catch this
1332 // are induction variable analysis (sometimes) and ADCE, which is only run
1333 // late.
1334 if (PHIUser->hasOneUse() &&
1335 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
1336 PHIUser->user_back() == &PN) {
1337 return replaceInstUsesWith(PN, UndefValue::get(PN.getType()));
1338 }
1339 // When a PHI is used only to be compared with zero, it is safe to replace
1340 // an incoming value proved as known nonzero with any non-zero constant.
1341 // For example, in the code below, the incoming value %v can be replaced
1342 // with any non-zero constant based on the fact that the PHI is only used to
1343 // be compared with zero and %v is a known non-zero value:
1344 // %v = select %cond, 1, 2
1345 // %p = phi [%v, BB] ...
1346 // icmp eq, %p, 0
1347 auto *CmpInst = dyn_cast<ICmpInst>(PHIUser);
1348 // FIXME: To be simple, handle only integer type for now.
1349 if (CmpInst && isa<IntegerType>(PN.getType()) && CmpInst->isEquality() &&
1350 match(CmpInst->getOperand(1), m_Zero())) {
1351 ConstantInt *NonZeroConst = nullptr;
1352 bool MadeChange = false;
1353 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
1354 Instruction *CtxI = PN.getIncomingBlock(i)->getTerminator();
1355 Value *VA = PN.getIncomingValue(i);
1356 if (isKnownNonZero(VA, DL, 0, &AC, CtxI, &DT)) {
1357 if (!NonZeroConst)
1358 NonZeroConst = GetAnyNonZeroConstInt(PN);
1359
1360 if (NonZeroConst != VA) {
1361 replaceOperand(PN, i, NonZeroConst);
1362 MadeChange = true;
1363 }
1364 }
1365 }
1366 if (MadeChange)
1367 return &PN;
1368 }
1369 }
1370
1371 // We sometimes end up with phi cycles that non-obviously end up being the
1372 // same value, for example:
1373 // z = some value; x = phi (y, z); y = phi (x, z)
1374 // where the phi nodes don't necessarily need to be in the same block. Do a
1375 // quick check to see if the PHI node only contains a single non-phi value, if
1376 // so, scan to see if the phi cycle is actually equal to that value.
1377 {
1378 unsigned InValNo = 0, NumIncomingVals = PN.getNumIncomingValues();
1379 // Scan for the first non-phi operand.
1380 while (InValNo != NumIncomingVals &&
1381 isa<PHINode>(PN.getIncomingValue(InValNo)))
1382 ++InValNo;
1383
1384 if (InValNo != NumIncomingVals) {
1385 Value *NonPhiInVal = PN.getIncomingValue(InValNo);
1386
1387 // Scan the rest of the operands to see if there are any conflicts, if so
1388 // there is no need to recursively scan other phis.
1389 for (++InValNo; InValNo != NumIncomingVals; ++InValNo) {
1390 Value *OpVal = PN.getIncomingValue(InValNo);
1391 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
1392 break;
1393 }
1394
1395 // If we scanned over all operands, then we have one unique value plus
1396 // phi values. Scan PHI nodes to see if they all merge in each other or
1397 // the value.
1398 if (InValNo == NumIncomingVals) {
1399 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
1400 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
1401 return replaceInstUsesWith(PN, NonPhiInVal);
1402 }
1403 }
1404 }
1405
1406 // If there are multiple PHIs, sort their operands so that they all list
1407 // the blocks in the same order. This will help identical PHIs be eliminated
1408 // by other passes. Other passes shouldn't depend on this for correctness
1409 // however.
1410 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
1411 if (&PN != FirstPN)
1412 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
1413 BasicBlock *BBA = PN.getIncomingBlock(i);
1414 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
1415 if (BBA != BBB) {
1416 Value *VA = PN.getIncomingValue(i);
1417 unsigned j = PN.getBasicBlockIndex(BBB);
1418 Value *VB = PN.getIncomingValue(j);
1419 PN.setIncomingBlock(i, BBB);
1420 PN.setIncomingValue(i, VB);
1421 PN.setIncomingBlock(j, BBA);
1422 PN.setIncomingValue(j, VA);
1423 // NOTE: Instcombine normally would want us to "return &PN" if we
1424 // modified any of the operands of an instruction. However, since we
1425 // aren't adding or removing uses (just rearranging them) we don't do
1426 // this in this case.
1427 }
1428 }
1429
1430 // Is there an identical PHI node in this basic block?
1431 for (PHINode &IdenticalPN : PN.getParent()->phis()) {
1432 // Ignore the PHI node itself.
1433 if (&IdenticalPN == &PN)
1434 continue;
1435 // Note that even though we've just canonicalized this PHI, due to the
1436 // worklist visitation order, there are no guarantess that *every* PHI
1437 // has been canonicalized, so we can't just compare operands ranges.
1438 if (!PN.isIdenticalToWhenDefined(&IdenticalPN))
1439 continue;
1440 // Just use that PHI instead then.
1441 ++NumPHICSEs;
1442 return replaceInstUsesWith(PN, &IdenticalPN);
1443 }
1444
1445 // If this is an integer PHI and we know that it has an illegal type, see if
1446 // it is only used by trunc or trunc(lshr) operations. If so, we split the
1447 // PHI into the various pieces being extracted. This sort of thing is
1448 // introduced when SROA promotes an aggregate to a single large integer type.
1449 if (PN.getType()->isIntegerTy() &&
1450 !DL.isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
1451 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
1452 return Res;
1453
1454 // Ultimately, try to replace this Phi with a dominating condition.
1455 if (auto *V = SimplifyUsingControlFlow(*this, PN, DT))
1456 return replaceInstUsesWith(PN, V);
1457
1458 return nullptr;
1459 }
1460