[PowerPC] Add a DAGToDAG peephole to remove unnecessary zero-exts
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
38
39 #define DEBUG_TYPE "ppc-codegen"
40
41 // FIXME: Remove this once the bug has been fixed!
42 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
43 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
44
45 namespace llvm {
46   void initializePPCDAGToDAGISelPass(PassRegistry&);
47 }
48
49 namespace {
50   //===--------------------------------------------------------------------===//
51   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
52   /// instructions for SelectionDAG operations.
53   ///
54   class PPCDAGToDAGISel : public SelectionDAGISel {
55     const PPCTargetMachine &TM;
56     const PPCTargetLowering *PPCLowering;
57     const PPCSubtarget *PPCSubTarget;
58     unsigned GlobalBaseReg;
59   public:
60     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
61         : SelectionDAGISel(tm), TM(tm),
62           PPCLowering(TM.getSubtargetImpl()->getTargetLowering()),
63           PPCSubTarget(TM.getSubtargetImpl()) {
64       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
65     }
66
67     bool runOnMachineFunction(MachineFunction &MF) override {
68       // Make sure we re-emit a set of the global base reg if necessary
69       GlobalBaseReg = 0;
70       PPCLowering = TM.getSubtargetImpl()->getTargetLowering();
71       PPCSubTarget = TM.getSubtargetImpl();
72       SelectionDAGISel::runOnMachineFunction(MF);
73
74       if (!PPCSubTarget->isSVR4ABI())
75         InsertVRSaveCode(MF);
76
77       return true;
78     }
79
80     void PostprocessISelDAG() override;
81
82     /// getI32Imm - Return a target constant with the specified value, of type
83     /// i32.
84     inline SDValue getI32Imm(unsigned Imm) {
85       return CurDAG->getTargetConstant(Imm, MVT::i32);
86     }
87
88     /// getI64Imm - Return a target constant with the specified value, of type
89     /// i64.
90     inline SDValue getI64Imm(uint64_t Imm) {
91       return CurDAG->getTargetConstant(Imm, MVT::i64);
92     }
93
94     /// getSmallIPtrImm - Return a target constant of pointer type.
95     inline SDValue getSmallIPtrImm(unsigned Imm) {
96       return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
97     }
98
99     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
100     /// with any number of 0s on either side.  The 1s are allowed to wrap from
101     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
102     /// 0x0F0F0000 is not, since all 1s are not contiguous.
103     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
104
105
106     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
107     /// rotate and mask opcode and mask operation.
108     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
109                                 unsigned &SH, unsigned &MB, unsigned &ME);
110
111     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
112     /// base register.  Return the virtual register that holds this value.
113     SDNode *getGlobalBaseReg();
114
115     SDNode *getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
116
117     // Select - Convert the specified operand from a target-independent to a
118     // target-specific node if it hasn't already been changed.
119     SDNode *Select(SDNode *N) override;
120
121     SDNode *SelectBitfieldInsert(SDNode *N);
122
123     /// SelectCC - Select a comparison of the specified values with the
124     /// specified condition code, returning the CR# of the expression.
125     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
126
127     /// SelectAddrImm - Returns true if the address N can be represented by
128     /// a base register plus a signed 16-bit displacement [r+imm].
129     bool SelectAddrImm(SDValue N, SDValue &Disp,
130                        SDValue &Base) {
131       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
132     }
133
134     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
135     /// immediate field.  Note that the operand at this point is already the
136     /// result of a prior SelectAddressRegImm call.
137     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
138       if (N.getOpcode() == ISD::TargetConstant ||
139           N.getOpcode() == ISD::TargetGlobalAddress) {
140         Out = N;
141         return true;
142       }
143
144       return false;
145     }
146
147     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
148     /// represented as an indexed [r+r] operation.  Returns false if it can
149     /// be represented by [r+imm], which are preferred.
150     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
151       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
152     }
153
154     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
155     /// represented as an indexed [r+r] operation.
156     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
157       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
158     }
159
160     /// SelectAddrImmX4 - Returns true if the address N can be represented by
161     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
162     /// Suitable for use by STD and friends.
163     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
164       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
165     }
166
167     // Select an address into a single register.
168     bool SelectAddr(SDValue N, SDValue &Base) {
169       Base = N;
170       return true;
171     }
172
173     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
174     /// inline asm expressions.  It is always correct to compute the value into
175     /// a register.  The case of adding a (possibly relocatable) constant to a
176     /// register can be improved, but it is wrong to substitute Reg+Reg for
177     /// Reg in an asm, because the load or store opcode would have to change.
178     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
179                                       char ConstraintCode,
180                                       std::vector<SDValue> &OutOps) override {
181       // We need to make sure that this one operand does not end up in r0
182       // (because we might end up lowering this as 0(%op)).
183       const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
184       const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
185       SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
186       SDValue NewOp =
187         SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
188                                        SDLoc(Op), Op.getValueType(),
189                                        Op, RC), 0);
190
191       OutOps.push_back(NewOp);
192       return false;
193     }
194
195     void InsertVRSaveCode(MachineFunction &MF);
196
197     const char *getPassName() const override {
198       return "PowerPC DAG->DAG Pattern Instruction Selection";
199     }
200
201 // Include the pieces autogenerated from the target description.
202 #include "PPCGenDAGISel.inc"
203
204 private:
205     SDNode *SelectSETCC(SDNode *N);
206
207     void PeepholePPC64();
208     void PeepholePPC64ZExt();
209     void PeepholeCROps();
210
211     bool AllUsersSelectZero(SDNode *N);
212     void SwapAllSelectUsers(SDNode *N);
213   };
214 }
215
216 /// InsertVRSaveCode - Once the entire function has been instruction selected,
217 /// all virtual registers are created and all machine instructions are built,
218 /// check to see if we need to save/restore VRSAVE.  If so, do it.
219 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
220   // Check to see if this function uses vector registers, which means we have to
221   // save and restore the VRSAVE register and update it with the regs we use.
222   //
223   // In this case, there will be virtual registers of vector type created
224   // by the scheduler.  Detect them now.
225   bool HasVectorVReg = false;
226   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
227     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
228     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
229       HasVectorVReg = true;
230       break;
231     }
232   }
233   if (!HasVectorVReg) return;  // nothing to do.
234
235   // If we have a vector register, we want to emit code into the entry and exit
236   // blocks to save and restore the VRSAVE register.  We do this here (instead
237   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
238   //
239   // 1. This (trivially) reduces the load on the register allocator, by not
240   //    having to represent the live range of the VRSAVE register.
241   // 2. This (more significantly) allows us to create a temporary virtual
242   //    register to hold the saved VRSAVE value, allowing this temporary to be
243   //    register allocated, instead of forcing it to be spilled to the stack.
244
245   // Create two vregs - one to hold the VRSAVE register that is live-in to the
246   // function and one for the value after having bits or'd into it.
247   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
248   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
249
250   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
251   MachineBasicBlock &EntryBB = *Fn.begin();
252   DebugLoc dl;
253   // Emit the following code into the entry block:
254   // InVRSAVE = MFVRSAVE
255   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
256   // MTVRSAVE UpdatedVRSAVE
257   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
258   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
259   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
260           UpdatedVRSAVE).addReg(InVRSAVE);
261   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
262
263   // Find all return blocks, outputting a restore in each epilog.
264   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
265     if (!BB->empty() && BB->back().isReturn()) {
266       IP = BB->end(); --IP;
267
268       // Skip over all terminator instructions, which are part of the return
269       // sequence.
270       MachineBasicBlock::iterator I2 = IP;
271       while (I2 != BB->begin() && (--I2)->isTerminator())
272         IP = I2;
273
274       // Emit: MTVRSAVE InVRSave
275       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
276     }
277   }
278 }
279
280
281 /// getGlobalBaseReg - Output the instructions required to put the
282 /// base address to use for accessing globals into a register.
283 ///
284 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
285   if (!GlobalBaseReg) {
286     const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
287     // Insert the set of GlobalBaseReg into the first MBB of the function
288     MachineBasicBlock &FirstMBB = MF->front();
289     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
290     const Module *M = MF->getFunction()->getParent();
291     DebugLoc dl;
292
293     if (PPCLowering->getPointerTy() == MVT::i32) {
294       if (PPCSubTarget->isTargetELF()) {
295         GlobalBaseReg = PPC::R30;
296         if (M->getPICLevel() == PICLevel::Small) {
297           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
298           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
299         } else {
300           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
301           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
302           unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
303           BuildMI(FirstMBB, MBBI, dl,
304                   TII.get(PPC::UpdateGBR)).addReg(GlobalBaseReg)
305                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
306           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
307         }
308       } else {
309         GlobalBaseReg =
310           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
311         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
312         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
313       }
314     } else {
315       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
316       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
317       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
318     }
319   }
320   return CurDAG->getRegister(GlobalBaseReg,
321                              PPCLowering->getPointerTy()).getNode();
322 }
323
324 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
325 /// or 64-bit immediate, and if the value can be accurately represented as a
326 /// sign extension from a 16-bit value.  If so, this returns true and the
327 /// immediate.
328 static bool isIntS16Immediate(SDNode *N, short &Imm) {
329   if (N->getOpcode() != ISD::Constant)
330     return false;
331
332   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
333   if (N->getValueType(0) == MVT::i32)
334     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
335   else
336     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
337 }
338
339 static bool isIntS16Immediate(SDValue Op, short &Imm) {
340   return isIntS16Immediate(Op.getNode(), Imm);
341 }
342
343
344 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
345 /// operand. If so Imm will receive the 32-bit value.
346 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
347   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
348     Imm = cast<ConstantSDNode>(N)->getZExtValue();
349     return true;
350   }
351   return false;
352 }
353
354 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
355 /// operand.  If so Imm will receive the 64-bit value.
356 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
357   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
358     Imm = cast<ConstantSDNode>(N)->getZExtValue();
359     return true;
360   }
361   return false;
362 }
363
364 // isInt32Immediate - This method tests to see if a constant operand.
365 // If so Imm will receive the 32 bit value.
366 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
367   return isInt32Immediate(N.getNode(), Imm);
368 }
369
370
371 // isOpcWithIntImmediate - This method tests to see if the node is a specific
372 // opcode and that it has a immediate integer right operand.
373 // If so Imm will receive the 32 bit value.
374 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
375   return N->getOpcode() == Opc
376          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
377 }
378
379 SDNode *PPCDAGToDAGISel::getFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
380   SDLoc dl(SN);
381   int FI = cast<FrameIndexSDNode>(N)->getIndex();
382   SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
383   unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
384   if (SN->hasOneUse())
385     return CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
386                                 getSmallIPtrImm(Offset));
387   return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
388                                 getSmallIPtrImm(Offset));
389 }
390
391 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
392   if (!Val)
393     return false;
394
395   if (isShiftedMask_32(Val)) {
396     // look for the first non-zero bit
397     MB = countLeadingZeros(Val);
398     // look for the first zero bit after the run of ones
399     ME = countLeadingZeros((Val - 1) ^ Val);
400     return true;
401   } else {
402     Val = ~Val; // invert mask
403     if (isShiftedMask_32(Val)) {
404       // effectively look for the first zero bit
405       ME = countLeadingZeros(Val) - 1;
406       // effectively look for the first one bit after the run of zeros
407       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
408       return true;
409     }
410   }
411   // no run present
412   return false;
413 }
414
415 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
416                                       bool isShiftMask, unsigned &SH,
417                                       unsigned &MB, unsigned &ME) {
418   // Don't even go down this path for i64, since different logic will be
419   // necessary for rldicl/rldicr/rldimi.
420   if (N->getValueType(0) != MVT::i32)
421     return false;
422
423   unsigned Shift  = 32;
424   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
425   unsigned Opcode = N->getOpcode();
426   if (N->getNumOperands() != 2 ||
427       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
428     return false;
429
430   if (Opcode == ISD::SHL) {
431     // apply shift left to mask if it comes first
432     if (isShiftMask) Mask = Mask << Shift;
433     // determine which bits are made indeterminant by shift
434     Indeterminant = ~(0xFFFFFFFFu << Shift);
435   } else if (Opcode == ISD::SRL) {
436     // apply shift right to mask if it comes first
437     if (isShiftMask) Mask = Mask >> Shift;
438     // determine which bits are made indeterminant by shift
439     Indeterminant = ~(0xFFFFFFFFu >> Shift);
440     // adjust for the left rotate
441     Shift = 32 - Shift;
442   } else if (Opcode == ISD::ROTL) {
443     Indeterminant = 0;
444   } else {
445     return false;
446   }
447
448   // if the mask doesn't intersect any Indeterminant bits
449   if (Mask && !(Mask & Indeterminant)) {
450     SH = Shift & 31;
451     // make sure the mask is still a mask (wrap arounds may not be)
452     return isRunOfOnes(Mask, MB, ME);
453   }
454   return false;
455 }
456
457 /// SelectBitfieldInsert - turn an or of two masked values into
458 /// the rotate left word immediate then mask insert (rlwimi) instruction.
459 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
460   SDValue Op0 = N->getOperand(0);
461   SDValue Op1 = N->getOperand(1);
462   SDLoc dl(N);
463
464   APInt LKZ, LKO, RKZ, RKO;
465   CurDAG->computeKnownBits(Op0, LKZ, LKO);
466   CurDAG->computeKnownBits(Op1, RKZ, RKO);
467
468   unsigned TargetMask = LKZ.getZExtValue();
469   unsigned InsertMask = RKZ.getZExtValue();
470
471   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
472     unsigned Op0Opc = Op0.getOpcode();
473     unsigned Op1Opc = Op1.getOpcode();
474     unsigned Value, SH = 0;
475     TargetMask = ~TargetMask;
476     InsertMask = ~InsertMask;
477
478     // If the LHS has a foldable shift and the RHS does not, then swap it to the
479     // RHS so that we can fold the shift into the insert.
480     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
481       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
482           Op0.getOperand(0).getOpcode() == ISD::SRL) {
483         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
484             Op1.getOperand(0).getOpcode() != ISD::SRL) {
485           std::swap(Op0, Op1);
486           std::swap(Op0Opc, Op1Opc);
487           std::swap(TargetMask, InsertMask);
488         }
489       }
490     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
491       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
492           Op1.getOperand(0).getOpcode() != ISD::SRL) {
493         std::swap(Op0, Op1);
494         std::swap(Op0Opc, Op1Opc);
495         std::swap(TargetMask, InsertMask);
496       }
497     }
498
499     unsigned MB, ME;
500     if (isRunOfOnes(InsertMask, MB, ME)) {
501       SDValue Tmp1, Tmp2;
502
503       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
504           isInt32Immediate(Op1.getOperand(1), Value)) {
505         Op1 = Op1.getOperand(0);
506         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
507       }
508       if (Op1Opc == ISD::AND) {
509        // The AND mask might not be a constant, and we need to make sure that
510        // if we're going to fold the masking with the insert, all bits not
511        // know to be zero in the mask are known to be one.
512         APInt MKZ, MKO;
513         CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
514         bool CanFoldMask = InsertMask == MKO.getZExtValue();
515
516         unsigned SHOpc = Op1.getOperand(0).getOpcode();
517         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
518             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
519           // Note that Value must be in range here (less than 32) because
520           // otherwise there would not be any bits set in InsertMask.
521           Op1 = Op1.getOperand(0).getOperand(0);
522           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
523         }
524       }
525
526       SH &= 31;
527       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
528                           getI32Imm(ME) };
529       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
530     }
531   }
532   return nullptr;
533 }
534
535 /// SelectCC - Select a comparison of the specified values with the specified
536 /// condition code, returning the CR# of the expression.
537 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
538                                     ISD::CondCode CC, SDLoc dl) {
539   // Always select the LHS.
540   unsigned Opc;
541
542   if (LHS.getValueType() == MVT::i32) {
543     unsigned Imm;
544     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
545       if (isInt32Immediate(RHS, Imm)) {
546         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
547         if (isUInt<16>(Imm))
548           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
549                                                 getI32Imm(Imm & 0xFFFF)), 0);
550         // If this is a 16-bit signed immediate, fold it.
551         if (isInt<16>((int)Imm))
552           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
553                                                 getI32Imm(Imm & 0xFFFF)), 0);
554
555         // For non-equality comparisons, the default code would materialize the
556         // constant, then compare against it, like this:
557         //   lis r2, 4660
558         //   ori r2, r2, 22136
559         //   cmpw cr0, r3, r2
560         // Since we are just comparing for equality, we can emit this instead:
561         //   xoris r0,r3,0x1234
562         //   cmplwi cr0,r0,0x5678
563         //   beq cr0,L6
564         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
565                                            getI32Imm(Imm >> 16)), 0);
566         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
567                                               getI32Imm(Imm & 0xFFFF)), 0);
568       }
569       Opc = PPC::CMPLW;
570     } else if (ISD::isUnsignedIntSetCC(CC)) {
571       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
572         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
573                                               getI32Imm(Imm & 0xFFFF)), 0);
574       Opc = PPC::CMPLW;
575     } else {
576       short SImm;
577       if (isIntS16Immediate(RHS, SImm))
578         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
579                                               getI32Imm((int)SImm & 0xFFFF)),
580                          0);
581       Opc = PPC::CMPW;
582     }
583   } else if (LHS.getValueType() == MVT::i64) {
584     uint64_t Imm;
585     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
586       if (isInt64Immediate(RHS.getNode(), Imm)) {
587         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
588         if (isUInt<16>(Imm))
589           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
590                                                 getI32Imm(Imm & 0xFFFF)), 0);
591         // If this is a 16-bit signed immediate, fold it.
592         if (isInt<16>(Imm))
593           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
594                                                 getI32Imm(Imm & 0xFFFF)), 0);
595
596         // For non-equality comparisons, the default code would materialize the
597         // constant, then compare against it, like this:
598         //   lis r2, 4660
599         //   ori r2, r2, 22136
600         //   cmpd cr0, r3, r2
601         // Since we are just comparing for equality, we can emit this instead:
602         //   xoris r0,r3,0x1234
603         //   cmpldi cr0,r0,0x5678
604         //   beq cr0,L6
605         if (isUInt<32>(Imm)) {
606           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
607                                              getI64Imm(Imm >> 16)), 0);
608           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
609                                                 getI64Imm(Imm & 0xFFFF)), 0);
610         }
611       }
612       Opc = PPC::CMPLD;
613     } else if (ISD::isUnsignedIntSetCC(CC)) {
614       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
615         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
616                                               getI64Imm(Imm & 0xFFFF)), 0);
617       Opc = PPC::CMPLD;
618     } else {
619       short SImm;
620       if (isIntS16Immediate(RHS, SImm))
621         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
622                                               getI64Imm(SImm & 0xFFFF)),
623                          0);
624       Opc = PPC::CMPD;
625     }
626   } else if (LHS.getValueType() == MVT::f32) {
627     Opc = PPC::FCMPUS;
628   } else {
629     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
630     Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
631   }
632   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
633 }
634
635 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
636   switch (CC) {
637   case ISD::SETUEQ:
638   case ISD::SETONE:
639   case ISD::SETOLE:
640   case ISD::SETOGE:
641     llvm_unreachable("Should be lowered by legalize!");
642   default: llvm_unreachable("Unknown condition!");
643   case ISD::SETOEQ:
644   case ISD::SETEQ:  return PPC::PRED_EQ;
645   case ISD::SETUNE:
646   case ISD::SETNE:  return PPC::PRED_NE;
647   case ISD::SETOLT:
648   case ISD::SETLT:  return PPC::PRED_LT;
649   case ISD::SETULE:
650   case ISD::SETLE:  return PPC::PRED_LE;
651   case ISD::SETOGT:
652   case ISD::SETGT:  return PPC::PRED_GT;
653   case ISD::SETUGE:
654   case ISD::SETGE:  return PPC::PRED_GE;
655   case ISD::SETO:   return PPC::PRED_NU;
656   case ISD::SETUO:  return PPC::PRED_UN;
657     // These two are invalid for floating point.  Assume we have int.
658   case ISD::SETULT: return PPC::PRED_LT;
659   case ISD::SETUGT: return PPC::PRED_GT;
660   }
661 }
662
663 /// getCRIdxForSetCC - Return the index of the condition register field
664 /// associated with the SetCC condition, and whether or not the field is
665 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
666 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
667   Invert = false;
668   switch (CC) {
669   default: llvm_unreachable("Unknown condition!");
670   case ISD::SETOLT:
671   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
672   case ISD::SETOGT:
673   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
674   case ISD::SETOEQ:
675   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
676   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
677   case ISD::SETUGE:
678   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
679   case ISD::SETULE:
680   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
681   case ISD::SETUNE:
682   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
683   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
684   case ISD::SETUEQ:
685   case ISD::SETOGE:
686   case ISD::SETOLE:
687   case ISD::SETONE:
688     llvm_unreachable("Invalid branch code: should be expanded by legalize");
689   // These are invalid for floating point.  Assume integer.
690   case ISD::SETULT: return 0;
691   case ISD::SETUGT: return 1;
692   }
693 }
694
695 // getVCmpInst: return the vector compare instruction for the specified
696 // vector type and condition code. Since this is for altivec specific code,
697 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
698 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
699                                 bool HasVSX, bool &Swap, bool &Negate) {
700   Swap = false;
701   Negate = false;
702
703   if (VecVT.isFloatingPoint()) {
704     /* Handle some cases by swapping input operands.  */
705     switch (CC) {
706       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
707       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
708       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
709       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
710       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
711       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
712       default: break;
713     }
714     /* Handle some cases by negating the result.  */
715     switch (CC) {
716       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
717       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
718       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
719       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
720       default: break;
721     }
722     /* We have instructions implementing the remaining cases.  */
723     switch (CC) {
724       case ISD::SETEQ:
725       case ISD::SETOEQ:
726         if (VecVT == MVT::v4f32)
727           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
728         else if (VecVT == MVT::v2f64)
729           return PPC::XVCMPEQDP;
730         break;
731       case ISD::SETGT:
732       case ISD::SETOGT:
733         if (VecVT == MVT::v4f32)
734           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
735         else if (VecVT == MVT::v2f64)
736           return PPC::XVCMPGTDP;
737         break;
738       case ISD::SETGE:
739       case ISD::SETOGE:
740         if (VecVT == MVT::v4f32)
741           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
742         else if (VecVT == MVT::v2f64)
743           return PPC::XVCMPGEDP;
744         break;
745       default:
746         break;
747     }
748     llvm_unreachable("Invalid floating-point vector compare condition");
749   } else {
750     /* Handle some cases by swapping input operands.  */
751     switch (CC) {
752       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
753       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
754       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
755       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
756       default: break;
757     }
758     /* Handle some cases by negating the result.  */
759     switch (CC) {
760       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
761       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
762       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
763       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
764       default: break;
765     }
766     /* We have instructions implementing the remaining cases.  */
767     switch (CC) {
768       case ISD::SETEQ:
769       case ISD::SETUEQ:
770         if (VecVT == MVT::v16i8)
771           return PPC::VCMPEQUB;
772         else if (VecVT == MVT::v8i16)
773           return PPC::VCMPEQUH;
774         else if (VecVT == MVT::v4i32)
775           return PPC::VCMPEQUW;
776         break;
777       case ISD::SETGT:
778         if (VecVT == MVT::v16i8)
779           return PPC::VCMPGTSB;
780         else if (VecVT == MVT::v8i16)
781           return PPC::VCMPGTSH;
782         else if (VecVT == MVT::v4i32)
783           return PPC::VCMPGTSW;
784         break;
785       case ISD::SETUGT:
786         if (VecVT == MVT::v16i8)
787           return PPC::VCMPGTUB;
788         else if (VecVT == MVT::v8i16)
789           return PPC::VCMPGTUH;
790         else if (VecVT == MVT::v4i32)
791           return PPC::VCMPGTUW;
792         break;
793       default:
794         break;
795     }
796     llvm_unreachable("Invalid integer vector compare condition");
797   }
798 }
799
800 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
801   SDLoc dl(N);
802   unsigned Imm;
803   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
804   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
805   bool isPPC64 = (PtrVT == MVT::i64);
806
807   if (!PPCSubTarget->useCRBits() &&
808       isInt32Immediate(N->getOperand(1), Imm)) {
809     // We can codegen setcc op, imm very efficiently compared to a brcond.
810     // Check for those cases here.
811     // setcc op, 0
812     if (Imm == 0) {
813       SDValue Op = N->getOperand(0);
814       switch (CC) {
815       default: break;
816       case ISD::SETEQ: {
817         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
818         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
819         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
820       }
821       case ISD::SETNE: {
822         if (isPPC64) break;
823         SDValue AD =
824           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
825                                          Op, getI32Imm(~0U)), 0);
826         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
827                                     AD.getValue(1));
828       }
829       case ISD::SETLT: {
830         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
831         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
832       }
833       case ISD::SETGT: {
834         SDValue T =
835           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
836         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
837         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
838         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
839       }
840       }
841     } else if (Imm == ~0U) {        // setcc op, -1
842       SDValue Op = N->getOperand(0);
843       switch (CC) {
844       default: break;
845       case ISD::SETEQ:
846         if (isPPC64) break;
847         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
848                                             Op, getI32Imm(1)), 0);
849         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
850                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
851                                                              MVT::i32,
852                                                              getI32Imm(0)), 0),
853                                       Op.getValue(1));
854       case ISD::SETNE: {
855         if (isPPC64) break;
856         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
857         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
858                                             Op, getI32Imm(~0U));
859         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
860                                     Op, SDValue(AD, 1));
861       }
862       case ISD::SETLT: {
863         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
864                                                     getI32Imm(1)), 0);
865         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
866                                                     Op), 0);
867         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
868         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
869       }
870       case ISD::SETGT: {
871         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
872         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
873                      0);
874         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
875                                     getI32Imm(1));
876       }
877       }
878     }
879   }
880
881   SDValue LHS = N->getOperand(0);
882   SDValue RHS = N->getOperand(1);
883
884   // Altivec Vector compare instructions do not set any CR register by default and
885   // vector compare operations return the same type as the operands.
886   if (LHS.getValueType().isVector()) {
887     EVT VecVT = LHS.getValueType();
888     bool Swap, Negate;
889     unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
890                                         PPCSubTarget->hasVSX(), Swap, Negate);
891     if (Swap)
892       std::swap(LHS, RHS);
893
894     if (Negate) {
895       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
896       return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
897                                                               PPC::VNOR,
898                                   VecVT, VCmp, VCmp);
899     }
900
901     return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
902   }
903
904   if (PPCSubTarget->useCRBits())
905     return nullptr;
906
907   bool Inv;
908   unsigned Idx = getCRIdxForSetCC(CC, Inv);
909   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
910   SDValue IntCR;
911
912   // Force the ccreg into CR7.
913   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
914
915   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
916   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
917                                InFlag).getValue(1);
918
919   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
920                                          CCReg), 0);
921
922   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
923                       getI32Imm(31), getI32Imm(31) };
924   if (!Inv)
925     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
926
927   // Get the specified bit.
928   SDValue Tmp =
929     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
930   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
931 }
932
933
934 // Select - Convert the specified operand from a target-independent to a
935 // target-specific node if it hasn't already been changed.
936 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
937   SDLoc dl(N);
938   if (N->isMachineOpcode()) {
939     N->setNodeId(-1);
940     return nullptr;   // Already selected.
941   }
942
943   // In case any misguided DAG-level optimizations form an ADD with a
944   // TargetConstant operand, crash here instead of miscompiling (by selecting
945   // an r+r add instead of some kind of r+i add).
946   if (N->getOpcode() == ISD::ADD &&
947       N->getOperand(1).getOpcode() == ISD::TargetConstant)
948     llvm_unreachable("Invalid ADD with TargetConstant operand");
949
950   switch (N->getOpcode()) {
951   default: break;
952
953   case ISD::Constant: {
954     if (N->getValueType(0) == MVT::i64) {
955       // Get 64 bit value.
956       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
957       // Assume no remaining bits.
958       unsigned Remainder = 0;
959       // Assume no shift required.
960       unsigned Shift = 0;
961
962       // If it can't be represented as a 32 bit value.
963       if (!isInt<32>(Imm)) {
964         Shift = countTrailingZeros<uint64_t>(Imm);
965         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
966
967         // If the shifted value fits 32 bits.
968         if (isInt<32>(ImmSh)) {
969           // Go with the shifted value.
970           Imm = ImmSh;
971         } else {
972           // Still stuck with a 64 bit value.
973           Remainder = Imm;
974           Shift = 32;
975           Imm >>= 32;
976         }
977       }
978
979       // Intermediate operand.
980       SDNode *Result;
981
982       // Handle first 32 bits.
983       unsigned Lo = Imm & 0xFFFF;
984       unsigned Hi = (Imm >> 16) & 0xFFFF;
985
986       // Simple value.
987       if (isInt<16>(Imm)) {
988        // Just the Lo bits.
989         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
990       } else if (Lo) {
991         // Handle the Hi bits.
992         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
993         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
994         // And Lo bits.
995         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
996                                         SDValue(Result, 0), getI32Imm(Lo));
997       } else {
998        // Just the Hi bits.
999         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
1000       }
1001
1002       // If no shift, we're done.
1003       if (!Shift) return Result;
1004
1005       // Shift for next step if the upper 32-bits were not zero.
1006       if (Imm) {
1007         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
1008                                         SDValue(Result, 0),
1009                                         getI32Imm(Shift),
1010                                         getI32Imm(63 - Shift));
1011       }
1012
1013       // Add in the last bits as required.
1014       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1015         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
1016                                         SDValue(Result, 0), getI32Imm(Hi));
1017       }
1018       if ((Lo = Remainder & 0xFFFF)) {
1019         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
1020                                         SDValue(Result, 0), getI32Imm(Lo));
1021       }
1022
1023       return Result;
1024     }
1025     break;
1026   }
1027
1028   case ISD::SETCC: {
1029     SDNode *SN = SelectSETCC(N);
1030     if (SN)
1031       return SN;
1032     break;
1033   }
1034   case PPCISD::GlobalBaseReg:
1035     return getGlobalBaseReg();
1036
1037   case ISD::FrameIndex:
1038     return getFrameIndex(N, N);
1039
1040   case PPCISD::MFOCRF: {
1041     SDValue InFlag = N->getOperand(1);
1042     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
1043                                   N->getOperand(0), InFlag);
1044   }
1045
1046   case PPCISD::READ_TIME_BASE: {
1047     return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
1048                                   MVT::Other, N->getOperand(0));
1049   }
1050
1051   case PPCISD::SRA_ADDZE: {
1052     SDValue N0 = N->getOperand(0);
1053     SDValue ShiftAmt =
1054       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
1055                                   getConstantIntValue(), N->getValueType(0));
1056     if (N->getValueType(0) == MVT::i64) {
1057       SDNode *Op =
1058         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
1059                                N0, ShiftAmt);
1060       return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
1061                                   SDValue(Op, 0), SDValue(Op, 1));
1062     } else {
1063       assert(N->getValueType(0) == MVT::i32 &&
1064              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
1065       SDNode *Op =
1066         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1067                                N0, ShiftAmt);
1068       return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1069                                   SDValue(Op, 0), SDValue(Op, 1));
1070     }
1071   }
1072
1073   case ISD::LOAD: {
1074     // Handle preincrement loads.
1075     LoadSDNode *LD = cast<LoadSDNode>(N);
1076     EVT LoadedVT = LD->getMemoryVT();
1077
1078     // Normal loads are handled by code generated from the .td file.
1079     if (LD->getAddressingMode() != ISD::PRE_INC)
1080       break;
1081
1082     SDValue Offset = LD->getOffset();
1083     if (Offset.getOpcode() == ISD::TargetConstant ||
1084         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1085
1086       unsigned Opcode;
1087       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1088       if (LD->getValueType(0) != MVT::i64) {
1089         // Handle PPC32 integer and normal FP loads.
1090         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1091         switch (LoadedVT.getSimpleVT().SimpleTy) {
1092           default: llvm_unreachable("Invalid PPC load type!");
1093           case MVT::f64: Opcode = PPC::LFDU; break;
1094           case MVT::f32: Opcode = PPC::LFSU; break;
1095           case MVT::i32: Opcode = PPC::LWZU; break;
1096           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1097           case MVT::i1:
1098           case MVT::i8:  Opcode = PPC::LBZU; break;
1099         }
1100       } else {
1101         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1102         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1103         switch (LoadedVT.getSimpleVT().SimpleTy) {
1104           default: llvm_unreachable("Invalid PPC load type!");
1105           case MVT::i64: Opcode = PPC::LDU; break;
1106           case MVT::i32: Opcode = PPC::LWZU8; break;
1107           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1108           case MVT::i1:
1109           case MVT::i8:  Opcode = PPC::LBZU8; break;
1110         }
1111       }
1112
1113       SDValue Chain = LD->getChain();
1114       SDValue Base = LD->getBasePtr();
1115       SDValue Ops[] = { Offset, Base, Chain };
1116       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1117                                     PPCLowering->getPointerTy(),
1118                                     MVT::Other, Ops);
1119     } else {
1120       unsigned Opcode;
1121       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1122       if (LD->getValueType(0) != MVT::i64) {
1123         // Handle PPC32 integer and normal FP loads.
1124         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1125         switch (LoadedVT.getSimpleVT().SimpleTy) {
1126           default: llvm_unreachable("Invalid PPC load type!");
1127           case MVT::f64: Opcode = PPC::LFDUX; break;
1128           case MVT::f32: Opcode = PPC::LFSUX; break;
1129           case MVT::i32: Opcode = PPC::LWZUX; break;
1130           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1131           case MVT::i1:
1132           case MVT::i8:  Opcode = PPC::LBZUX; break;
1133         }
1134       } else {
1135         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1136         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1137                "Invalid sext update load");
1138         switch (LoadedVT.getSimpleVT().SimpleTy) {
1139           default: llvm_unreachable("Invalid PPC load type!");
1140           case MVT::i64: Opcode = PPC::LDUX; break;
1141           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1142           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1143           case MVT::i1:
1144           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1145         }
1146       }
1147
1148       SDValue Chain = LD->getChain();
1149       SDValue Base = LD->getBasePtr();
1150       SDValue Ops[] = { Base, Offset, Chain };
1151       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1152                                     PPCLowering->getPointerTy(),
1153                                     MVT::Other, Ops);
1154     }
1155   }
1156
1157   case ISD::AND: {
1158     unsigned Imm, Imm2, SH, MB, ME;
1159     uint64_t Imm64;
1160
1161     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1162     // with a mask, emit rlwinm
1163     if (isInt32Immediate(N->getOperand(1), Imm) &&
1164         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1165       SDValue Val = N->getOperand(0).getOperand(0);
1166       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1167       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1168     }
1169     // If this is just a masked value where the input is not handled above, and
1170     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1171     if (isInt32Immediate(N->getOperand(1), Imm) &&
1172         isRunOfOnes(Imm, MB, ME) &&
1173         N->getOperand(0).getOpcode() != ISD::ROTL) {
1174       SDValue Val = N->getOperand(0);
1175       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1176       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1177     }
1178     // If this is a 64-bit zero-extension mask, emit rldicl.
1179     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1180         isMask_64(Imm64)) {
1181       SDValue Val = N->getOperand(0);
1182       MB = 64 - CountTrailingOnes_64(Imm64);
1183       SH = 0;
1184
1185       // If the operand is a logical right shift, we can fold it into this
1186       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
1187       // for n <= mb. The right shift is really a left rotate followed by a
1188       // mask, and this mask is a more-restrictive sub-mask of the mask implied
1189       // by the shift.
1190       if (Val.getOpcode() == ISD::SRL &&
1191           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
1192         assert(Imm < 64 && "Illegal shift amount");
1193         Val = Val.getOperand(0);
1194         SH = 64 - Imm;
1195       }
1196
1197       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
1198       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
1199     }
1200     // AND X, 0 -> 0, not "rlwinm 32".
1201     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1202       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1203       return nullptr;
1204     }
1205     // ISD::OR doesn't get all the bitfield insertion fun.
1206     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1207     if (isInt32Immediate(N->getOperand(1), Imm) &&
1208         N->getOperand(0).getOpcode() == ISD::OR &&
1209         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1210       unsigned MB, ME;
1211       Imm = ~(Imm^Imm2);
1212       if (isRunOfOnes(Imm, MB, ME)) {
1213         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1214                             N->getOperand(0).getOperand(1),
1215                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1216         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1217       }
1218     }
1219
1220     // Other cases are autogenerated.
1221     break;
1222   }
1223   case ISD::OR: {
1224     if (N->getValueType(0) == MVT::i32)
1225       if (SDNode *I = SelectBitfieldInsert(N))
1226         return I;
1227
1228     short Imm;
1229     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
1230         isIntS16Immediate(N->getOperand(1), Imm)) {
1231       APInt LHSKnownZero, LHSKnownOne;
1232       CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
1233
1234       // If this is equivalent to an add, then we can fold it with the
1235       // FrameIndex calculation.
1236       if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL)
1237         return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
1238     }
1239
1240     // Other cases are autogenerated.
1241     break;
1242   }
1243   case ISD::ADD: {
1244     short Imm;
1245     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
1246         isIntS16Immediate(N->getOperand(1), Imm))
1247       return getFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
1248
1249     break;
1250   }
1251   case ISD::SHL: {
1252     unsigned Imm, SH, MB, ME;
1253     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1254         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1255       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1256                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1257       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1258     }
1259
1260     // Other cases are autogenerated.
1261     break;
1262   }
1263   case ISD::SRL: {
1264     unsigned Imm, SH, MB, ME;
1265     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1266         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1267       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1268                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1269       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1270     }
1271
1272     // Other cases are autogenerated.
1273     break;
1274   }
1275   // FIXME: Remove this once the ANDI glue bug is fixed:
1276   case PPCISD::ANDIo_1_EQ_BIT:
1277   case PPCISD::ANDIo_1_GT_BIT: {
1278     if (!ANDIGlueBug)
1279       break;
1280
1281     EVT InVT = N->getOperand(0).getValueType();
1282     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
1283            "Invalid input type for ANDIo_1_EQ_BIT");
1284
1285     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
1286     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
1287                                         N->getOperand(0),
1288                                         CurDAG->getTargetConstant(1, InVT)), 0);
1289     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
1290     SDValue SRIdxVal =
1291       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
1292                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
1293
1294     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
1295                                 CR0Reg, SRIdxVal,
1296                                 SDValue(AndI.getNode(), 1) /* glue */);
1297   }
1298   case ISD::SELECT_CC: {
1299     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1300     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1301     bool isPPC64 = (PtrVT == MVT::i64);
1302
1303     // If this is a select of i1 operands, we'll pattern match it.
1304     if (PPCSubTarget->useCRBits() &&
1305         N->getOperand(0).getValueType() == MVT::i1)
1306       break;
1307
1308     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1309     if (!isPPC64)
1310       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1311         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1312           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1313             if (N1C->isNullValue() && N3C->isNullValue() &&
1314                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1315                 // FIXME: Implement this optzn for PPC64.
1316                 N->getValueType(0) == MVT::i32) {
1317               SDNode *Tmp =
1318                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1319                                        N->getOperand(0), getI32Imm(~0U));
1320               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1321                                           SDValue(Tmp, 0), N->getOperand(0),
1322                                           SDValue(Tmp, 1));
1323             }
1324
1325     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1326
1327     if (N->getValueType(0) == MVT::i1) {
1328       // An i1 select is: (c & t) | (!c & f).
1329       bool Inv;
1330       unsigned Idx = getCRIdxForSetCC(CC, Inv);
1331
1332       unsigned SRI;
1333       switch (Idx) {
1334       default: llvm_unreachable("Invalid CC index");
1335       case 0: SRI = PPC::sub_lt; break;
1336       case 1: SRI = PPC::sub_gt; break;
1337       case 2: SRI = PPC::sub_eq; break;
1338       case 3: SRI = PPC::sub_un; break;
1339       }
1340
1341       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
1342
1343       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
1344                                               CCBit, CCBit), 0);
1345       SDValue C =    Inv ? NotCCBit : CCBit,
1346               NotC = Inv ? CCBit    : NotCCBit;
1347
1348       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1349                                            C, N->getOperand(2)), 0);
1350       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1351                                               NotC, N->getOperand(3)), 0);
1352
1353       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
1354     }
1355
1356     unsigned BROpc = getPredicateForSetCC(CC);
1357
1358     unsigned SelectCCOp;
1359     if (N->getValueType(0) == MVT::i32)
1360       SelectCCOp = PPC::SELECT_CC_I4;
1361     else if (N->getValueType(0) == MVT::i64)
1362       SelectCCOp = PPC::SELECT_CC_I8;
1363     else if (N->getValueType(0) == MVT::f32)
1364       SelectCCOp = PPC::SELECT_CC_F4;
1365     else if (N->getValueType(0) == MVT::f64)
1366       if (PPCSubTarget->hasVSX())
1367         SelectCCOp = PPC::SELECT_CC_VSFRC;
1368       else
1369         SelectCCOp = PPC::SELECT_CC_F8;
1370     else if (N->getValueType(0) == MVT::v2f64 ||
1371              N->getValueType(0) == MVT::v2i64)
1372       SelectCCOp = PPC::SELECT_CC_VSRC;
1373     else
1374       SelectCCOp = PPC::SELECT_CC_VRRC;
1375
1376     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1377                         getI32Imm(BROpc) };
1378     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
1379   }
1380   case ISD::VSELECT:
1381     if (PPCSubTarget->hasVSX()) {
1382       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
1383       return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
1384     }
1385
1386     break;
1387   case ISD::VECTOR_SHUFFLE:
1388     if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
1389                                   N->getValueType(0) == MVT::v2i64)) {
1390       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
1391       
1392       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
1393               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
1394       unsigned DM[2];
1395
1396       for (int i = 0; i < 2; ++i)
1397         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
1398           DM[i] = 0;
1399         else
1400           DM[i] = 1;
1401
1402       // For little endian, we must swap the input operands and adjust
1403       // the mask elements (reverse and invert them).
1404       if (PPCSubTarget->isLittleEndian()) {
1405         std::swap(Op1, Op2);
1406         unsigned tmp = DM[0];
1407         DM[0] = 1 - DM[1];
1408         DM[1] = 1 - tmp;
1409       }
1410
1411       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
1412
1413       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
1414           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
1415           isa<LoadSDNode>(Op1.getOperand(0))) {
1416         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
1417         SDValue Base, Offset;
1418
1419         if (LD->isUnindexed() &&
1420             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
1421           SDValue Chain = LD->getChain();
1422           SDValue Ops[] = { Base, Offset, Chain };
1423           return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
1424                                       N->getValueType(0), Ops);
1425         }
1426       }
1427
1428       SDValue Ops[] = { Op1, Op2, DMV };
1429       return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
1430     }
1431
1432     break;
1433   case PPCISD::BDNZ:
1434   case PPCISD::BDZ: {
1435     bool IsPPC64 = PPCSubTarget->isPPC64();
1436     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1437     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1438                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1439                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1440                                 MVT::Other, Ops);
1441   }
1442   case PPCISD::COND_BRANCH: {
1443     // Op #0 is the Chain.
1444     // Op #1 is the PPC::PRED_* number.
1445     // Op #2 is the CR#
1446     // Op #3 is the Dest MBB
1447     // Op #4 is the Flag.
1448     // Prevent PPC::PRED_* from being selected into LI.
1449     SDValue Pred =
1450       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1451     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1452       N->getOperand(0), N->getOperand(4) };
1453     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
1454   }
1455   case ISD::BR_CC: {
1456     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1457     unsigned PCC = getPredicateForSetCC(CC);
1458
1459     if (N->getOperand(2).getValueType() == MVT::i1) {
1460       unsigned Opc;
1461       bool Swap;
1462       switch (PCC) {
1463       default: llvm_unreachable("Unexpected Boolean-operand predicate");
1464       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
1465       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
1466       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
1467       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
1468       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
1469       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
1470       }
1471
1472       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
1473                                              N->getOperand(Swap ? 3 : 2),
1474                                              N->getOperand(Swap ? 2 : 3)), 0);
1475       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
1476                                   BitComp, N->getOperand(4), N->getOperand(0));
1477     }
1478
1479     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1480     SDValue Ops[] = { getI32Imm(PCC), CondCode,
1481                         N->getOperand(4), N->getOperand(0) };
1482     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
1483   }
1484   case ISD::BRIND: {
1485     // FIXME: Should custom lower this.
1486     SDValue Chain = N->getOperand(0);
1487     SDValue Target = N->getOperand(1);
1488     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1489     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1490     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1491                                            Chain), 0);
1492     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1493   }
1494   case PPCISD::TOC_ENTRY: {
1495     assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
1496             "Only supported for 64-bit ABI and 32-bit SVR4");
1497     if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
1498       SDValue GA = N->getOperand(0);
1499       return CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
1500                                     N->getOperand(1));
1501     }
1502
1503     // For medium and large code model, we generate two instructions as
1504     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1505     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
1506     CodeModel::Model CModel = TM.getCodeModel();
1507     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1508       break;
1509
1510     // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
1511     // If it is an externally defined symbol, a symbol with common linkage,
1512     // a non-local function address, or a jump table address, or if we are
1513     // generating code for large code model, we generate:
1514     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1515     // Otherwise we generate:
1516     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1517     SDValue GA = N->getOperand(0);
1518     SDValue TOCbase = N->getOperand(1);
1519     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1520                                         TOCbase, GA);
1521
1522     if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
1523         CModel == CodeModel::Large)
1524       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1525                                     SDValue(Tmp, 0));
1526
1527     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1528       const GlobalValue *GValue = G->getGlobal();
1529       if ((GValue->getType()->getElementType()->isFunctionTy() &&
1530            (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
1531           GValue->isDeclaration() || GValue->hasCommonLinkage() ||
1532           GValue->hasAvailableExternallyLinkage())
1533         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1534                                       SDValue(Tmp, 0));
1535     }
1536
1537     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1538                                   SDValue(Tmp, 0), GA);
1539   }
1540   case PPCISD::PPC32_PICGOT: {
1541     // Generate a PIC-safe GOT reference.
1542     assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
1543       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
1544     return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(),  MVT::i32);
1545   }
1546   case PPCISD::VADD_SPLAT: {
1547     // This expands into one of three sequences, depending on whether
1548     // the first operand is odd or even, positive or negative.
1549     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1550            isa<ConstantSDNode>(N->getOperand(1)) &&
1551            "Invalid operand on VADD_SPLAT!");
1552
1553     int Elt     = N->getConstantOperandVal(0);
1554     int EltSize = N->getConstantOperandVal(1);
1555     unsigned Opc1, Opc2, Opc3;
1556     EVT VT;
1557
1558     if (EltSize == 1) {
1559       Opc1 = PPC::VSPLTISB;
1560       Opc2 = PPC::VADDUBM;
1561       Opc3 = PPC::VSUBUBM;
1562       VT = MVT::v16i8;
1563     } else if (EltSize == 2) {
1564       Opc1 = PPC::VSPLTISH;
1565       Opc2 = PPC::VADDUHM;
1566       Opc3 = PPC::VSUBUHM;
1567       VT = MVT::v8i16;
1568     } else {
1569       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1570       Opc1 = PPC::VSPLTISW;
1571       Opc2 = PPC::VADDUWM;
1572       Opc3 = PPC::VSUBUWM;
1573       VT = MVT::v4i32;
1574     }
1575
1576     if ((Elt & 1) == 0) {
1577       // Elt is even, in the range [-32,-18] + [16,30].
1578       //
1579       // Convert: VADD_SPLAT elt, size
1580       // Into:    tmp = VSPLTIS[BHW] elt
1581       //          VADDU[BHW]M tmp, tmp
1582       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1583       SDValue EltVal = getI32Imm(Elt >> 1);
1584       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1585       SDValue TmpVal = SDValue(Tmp, 0);
1586       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1587
1588     } else if (Elt > 0) {
1589       // Elt is odd and positive, in the range [17,31].
1590       //
1591       // Convert: VADD_SPLAT elt, size
1592       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1593       //          tmp2 = VSPLTIS[BHW] -16
1594       //          VSUBU[BHW]M tmp1, tmp2
1595       SDValue EltVal = getI32Imm(Elt - 16);
1596       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1597       EltVal = getI32Imm(-16);
1598       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1599       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1600                                     SDValue(Tmp2, 0));
1601
1602     } else {
1603       // Elt is odd and negative, in the range [-31,-17].
1604       //
1605       // Convert: VADD_SPLAT elt, size
1606       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1607       //          tmp2 = VSPLTIS[BHW] -16
1608       //          VADDU[BHW]M tmp1, tmp2
1609       SDValue EltVal = getI32Imm(Elt + 16);
1610       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1611       EltVal = getI32Imm(-16);
1612       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1613       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1614                                     SDValue(Tmp2, 0));
1615     }
1616   }
1617   }
1618
1619   return SelectCode(N);
1620 }
1621
1622 /// PostprocessISelDAG - Perform some late peephole optimizations
1623 /// on the DAG representation.
1624 void PPCDAGToDAGISel::PostprocessISelDAG() {
1625
1626   // Skip peepholes at -O0.
1627   if (TM.getOptLevel() == CodeGenOpt::None)
1628     return;
1629
1630   PeepholePPC64();
1631   PeepholeCROps();
1632   PeepholePPC64ZExt();
1633 }
1634
1635 // Check if all users of this node will become isel where the second operand
1636 // is the constant zero. If this is so, and if we can negate the condition,
1637 // then we can flip the true and false operands. This will allow the zero to
1638 // be folded with the isel so that we don't need to materialize a register
1639 // containing zero.
1640 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
1641   // If we're not using isel, then this does not matter.
1642   if (!PPCSubTarget->hasISEL())
1643     return false;
1644
1645   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1646        UI != UE; ++UI) {
1647     SDNode *User = *UI;
1648     if (!User->isMachineOpcode())
1649       return false;
1650     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
1651         User->getMachineOpcode() != PPC::SELECT_I8)
1652       return false;
1653
1654     SDNode *Op2 = User->getOperand(2).getNode();
1655     if (!Op2->isMachineOpcode())
1656       return false;
1657
1658     if (Op2->getMachineOpcode() != PPC::LI &&
1659         Op2->getMachineOpcode() != PPC::LI8)
1660       return false;
1661
1662     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
1663     if (!C)
1664       return false;
1665
1666     if (!C->isNullValue())
1667       return false;
1668   }
1669
1670   return true;
1671 }
1672
1673 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
1674   SmallVector<SDNode *, 4> ToReplace;
1675   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1676        UI != UE; ++UI) {
1677     SDNode *User = *UI;
1678     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
1679             User->getMachineOpcode() == PPC::SELECT_I8) &&
1680            "Must have all select users");
1681     ToReplace.push_back(User);
1682   }
1683
1684   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
1685        UE = ToReplace.end(); UI != UE; ++UI) {
1686     SDNode *User = *UI;
1687     SDNode *ResNode =
1688       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
1689                              User->getValueType(0), User->getOperand(0),
1690                              User->getOperand(2),
1691                              User->getOperand(1));
1692
1693       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1694       DEBUG(User->dump(CurDAG));
1695       DEBUG(dbgs() << "\nNew: ");
1696       DEBUG(ResNode->dump(CurDAG));
1697       DEBUG(dbgs() << "\n");
1698
1699       ReplaceUses(User, ResNode);
1700   }
1701 }
1702
1703 void PPCDAGToDAGISel::PeepholeCROps() {
1704   bool IsModified;
1705   do {
1706     IsModified = false;
1707     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1708          E = CurDAG->allnodes_end(); I != E; ++I) {
1709       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1710       if (!MachineNode || MachineNode->use_empty())
1711         continue;
1712       SDNode *ResNode = MachineNode;
1713
1714       bool Op1Set   = false, Op1Unset = false,
1715            Op1Not   = false,
1716            Op2Set   = false, Op2Unset = false,
1717            Op2Not   = false;
1718
1719       unsigned Opcode = MachineNode->getMachineOpcode();
1720       switch (Opcode) {
1721       default: break;
1722       case PPC::CRAND:
1723       case PPC::CRNAND:
1724       case PPC::CROR:
1725       case PPC::CRXOR:
1726       case PPC::CRNOR:
1727       case PPC::CREQV:
1728       case PPC::CRANDC:
1729       case PPC::CRORC: {
1730         SDValue Op = MachineNode->getOperand(1);
1731         if (Op.isMachineOpcode()) {
1732           if (Op.getMachineOpcode() == PPC::CRSET)
1733             Op2Set = true;
1734           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1735             Op2Unset = true;
1736           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1737                    Op.getOperand(0) == Op.getOperand(1))
1738             Op2Not = true;
1739         }
1740         }  // fallthrough
1741       case PPC::BC:
1742       case PPC::BCn:
1743       case PPC::SELECT_I4:
1744       case PPC::SELECT_I8:
1745       case PPC::SELECT_F4:
1746       case PPC::SELECT_F8:
1747       case PPC::SELECT_VRRC:
1748       case PPC::SELECT_VSFRC:
1749       case PPC::SELECT_VSRC: {
1750         SDValue Op = MachineNode->getOperand(0);
1751         if (Op.isMachineOpcode()) {
1752           if (Op.getMachineOpcode() == PPC::CRSET)
1753             Op1Set = true;
1754           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1755             Op1Unset = true;
1756           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1757                    Op.getOperand(0) == Op.getOperand(1))
1758             Op1Not = true;
1759         }
1760         }
1761         break;
1762       }
1763
1764       bool SelectSwap = false;
1765       switch (Opcode) {
1766       default: break;
1767       case PPC::CRAND:
1768         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1769           // x & x = x
1770           ResNode = MachineNode->getOperand(0).getNode();
1771         else if (Op1Set)
1772           // 1 & y = y
1773           ResNode = MachineNode->getOperand(1).getNode();
1774         else if (Op2Set)
1775           // x & 1 = x
1776           ResNode = MachineNode->getOperand(0).getNode();
1777         else if (Op1Unset || Op2Unset)
1778           // x & 0 = 0 & y = 0
1779           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1780                                            MVT::i1);
1781         else if (Op1Not)
1782           // ~x & y = andc(y, x)
1783           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1784                                            MVT::i1, MachineNode->getOperand(1),
1785                                            MachineNode->getOperand(0).
1786                                              getOperand(0));
1787         else if (Op2Not)
1788           // x & ~y = andc(x, y)
1789           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1790                                            MVT::i1, MachineNode->getOperand(0),
1791                                            MachineNode->getOperand(1).
1792                                              getOperand(0));
1793         else if (AllUsersSelectZero(MachineNode))
1794           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1795                                            MVT::i1, MachineNode->getOperand(0),
1796                                            MachineNode->getOperand(1)),
1797           SelectSwap = true;
1798         break;
1799       case PPC::CRNAND:
1800         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1801           // nand(x, x) -> nor(x, x)
1802           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1803                                            MVT::i1, MachineNode->getOperand(0),
1804                                            MachineNode->getOperand(0));
1805         else if (Op1Set)
1806           // nand(1, y) -> nor(y, y)
1807           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1808                                            MVT::i1, MachineNode->getOperand(1),
1809                                            MachineNode->getOperand(1));
1810         else if (Op2Set)
1811           // nand(x, 1) -> nor(x, x)
1812           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1813                                            MVT::i1, MachineNode->getOperand(0),
1814                                            MachineNode->getOperand(0));
1815         else if (Op1Unset || Op2Unset)
1816           // nand(x, 0) = nand(0, y) = 1
1817           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1818                                            MVT::i1);
1819         else if (Op1Not)
1820           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
1821           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1822                                            MVT::i1, MachineNode->getOperand(0).
1823                                                       getOperand(0),
1824                                            MachineNode->getOperand(1));
1825         else if (Op2Not)
1826           // nand(x, ~y) = ~x | y = orc(y, x)
1827           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1828                                            MVT::i1, MachineNode->getOperand(1).
1829                                                       getOperand(0),
1830                                            MachineNode->getOperand(0));
1831         else if (AllUsersSelectZero(MachineNode))
1832           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1833                                            MVT::i1, MachineNode->getOperand(0),
1834                                            MachineNode->getOperand(1)),
1835           SelectSwap = true;
1836         break;
1837       case PPC::CROR:
1838         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1839           // x | x = x
1840           ResNode = MachineNode->getOperand(0).getNode();
1841         else if (Op1Set || Op2Set)
1842           // x | 1 = 1 | y = 1
1843           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1844                                            MVT::i1);
1845         else if (Op1Unset)
1846           // 0 | y = y
1847           ResNode = MachineNode->getOperand(1).getNode();
1848         else if (Op2Unset)
1849           // x | 0 = x
1850           ResNode = MachineNode->getOperand(0).getNode();
1851         else if (Op1Not)
1852           // ~x | y = orc(y, x)
1853           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1854                                            MVT::i1, MachineNode->getOperand(1),
1855                                            MachineNode->getOperand(0).
1856                                              getOperand(0));
1857         else if (Op2Not)
1858           // x | ~y = orc(x, y)
1859           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1860                                            MVT::i1, MachineNode->getOperand(0),
1861                                            MachineNode->getOperand(1).
1862                                              getOperand(0));
1863         else if (AllUsersSelectZero(MachineNode))
1864           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1865                                            MVT::i1, MachineNode->getOperand(0),
1866                                            MachineNode->getOperand(1)),
1867           SelectSwap = true;
1868         break;
1869       case PPC::CRXOR:
1870         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1871           // xor(x, x) = 0
1872           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1873                                            MVT::i1);
1874         else if (Op1Set)
1875           // xor(1, y) -> nor(y, y)
1876           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1877                                            MVT::i1, MachineNode->getOperand(1),
1878                                            MachineNode->getOperand(1));
1879         else if (Op2Set)
1880           // xor(x, 1) -> nor(x, x)
1881           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1882                                            MVT::i1, MachineNode->getOperand(0),
1883                                            MachineNode->getOperand(0));
1884         else if (Op1Unset)
1885           // xor(0, y) = y
1886           ResNode = MachineNode->getOperand(1).getNode();
1887         else if (Op2Unset)
1888           // xor(x, 0) = x
1889           ResNode = MachineNode->getOperand(0).getNode();
1890         else if (Op1Not)
1891           // xor(~x, y) = eqv(x, y)
1892           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1893                                            MVT::i1, MachineNode->getOperand(0).
1894                                                       getOperand(0),
1895                                            MachineNode->getOperand(1));
1896         else if (Op2Not)
1897           // xor(x, ~y) = eqv(x, y)
1898           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1899                                            MVT::i1, MachineNode->getOperand(0),
1900                                            MachineNode->getOperand(1).
1901                                              getOperand(0));
1902         else if (AllUsersSelectZero(MachineNode))
1903           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1904                                            MVT::i1, MachineNode->getOperand(0),
1905                                            MachineNode->getOperand(1)),
1906           SelectSwap = true;
1907         break;
1908       case PPC::CRNOR:
1909         if (Op1Set || Op2Set)
1910           // nor(1, y) -> 0
1911           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1912                                            MVT::i1);
1913         else if (Op1Unset)
1914           // nor(0, y) = ~y -> nor(y, y)
1915           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1916                                            MVT::i1, MachineNode->getOperand(1),
1917                                            MachineNode->getOperand(1));
1918         else if (Op2Unset)
1919           // nor(x, 0) = ~x
1920           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1921                                            MVT::i1, MachineNode->getOperand(0),
1922                                            MachineNode->getOperand(0));
1923         else if (Op1Not)
1924           // nor(~x, y) = andc(x, y)
1925           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1926                                            MVT::i1, MachineNode->getOperand(0).
1927                                                       getOperand(0),
1928                                            MachineNode->getOperand(1));
1929         else if (Op2Not)
1930           // nor(x, ~y) = andc(y, x)
1931           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1932                                            MVT::i1, MachineNode->getOperand(1).
1933                                                       getOperand(0),
1934                                            MachineNode->getOperand(0));
1935         else if (AllUsersSelectZero(MachineNode))
1936           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1937                                            MVT::i1, MachineNode->getOperand(0),
1938                                            MachineNode->getOperand(1)),
1939           SelectSwap = true;
1940         break;
1941       case PPC::CREQV:
1942         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1943           // eqv(x, x) = 1
1944           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1945                                            MVT::i1);
1946         else if (Op1Set)
1947           // eqv(1, y) = y
1948           ResNode = MachineNode->getOperand(1).getNode();
1949         else if (Op2Set)
1950           // eqv(x, 1) = x
1951           ResNode = MachineNode->getOperand(0).getNode();
1952         else if (Op1Unset)
1953           // eqv(0, y) = ~y -> nor(y, y)
1954           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1955                                            MVT::i1, MachineNode->getOperand(1),
1956                                            MachineNode->getOperand(1));
1957         else if (Op2Unset)
1958           // eqv(x, 0) = ~x
1959           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1960                                            MVT::i1, MachineNode->getOperand(0),
1961                                            MachineNode->getOperand(0));
1962         else if (Op1Not)
1963           // eqv(~x, y) = xor(x, y)
1964           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1965                                            MVT::i1, MachineNode->getOperand(0).
1966                                                       getOperand(0),
1967                                            MachineNode->getOperand(1));
1968         else if (Op2Not)
1969           // eqv(x, ~y) = xor(x, y)
1970           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1971                                            MVT::i1, MachineNode->getOperand(0),
1972                                            MachineNode->getOperand(1).
1973                                              getOperand(0));
1974         else if (AllUsersSelectZero(MachineNode))
1975           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1976                                            MVT::i1, MachineNode->getOperand(0),
1977                                            MachineNode->getOperand(1)),
1978           SelectSwap = true;
1979         break;
1980       case PPC::CRANDC:
1981         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1982           // andc(x, x) = 0
1983           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1984                                            MVT::i1);
1985         else if (Op1Set)
1986           // andc(1, y) = ~y
1987           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1988                                            MVT::i1, MachineNode->getOperand(1),
1989                                            MachineNode->getOperand(1));
1990         else if (Op1Unset || Op2Set)
1991           // andc(0, y) = andc(x, 1) = 0
1992           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1993                                            MVT::i1);
1994         else if (Op2Unset)
1995           // andc(x, 0) = x
1996           ResNode = MachineNode->getOperand(0).getNode();
1997         else if (Op1Not)
1998           // andc(~x, y) = ~(x | y) = nor(x, y)
1999           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
2000                                            MVT::i1, MachineNode->getOperand(0).
2001                                                       getOperand(0),
2002                                            MachineNode->getOperand(1));
2003         else if (Op2Not)
2004           // andc(x, ~y) = x & y
2005           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
2006                                            MVT::i1, MachineNode->getOperand(0),
2007                                            MachineNode->getOperand(1).
2008                                              getOperand(0));
2009         else if (AllUsersSelectZero(MachineNode))
2010           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
2011                                            MVT::i1, MachineNode->getOperand(1),
2012                                            MachineNode->getOperand(0)),
2013           SelectSwap = true;
2014         break;
2015       case PPC::CRORC:
2016         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
2017           // orc(x, x) = 1
2018           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
2019                                            MVT::i1);
2020         else if (Op1Set || Op2Unset)
2021           // orc(1, y) = orc(x, 0) = 1
2022           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
2023                                            MVT::i1);
2024         else if (Op2Set)
2025           // orc(x, 1) = x
2026           ResNode = MachineNode->getOperand(0).getNode();
2027         else if (Op1Unset)
2028           // orc(0, y) = ~y
2029           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
2030                                            MVT::i1, MachineNode->getOperand(1),
2031                                            MachineNode->getOperand(1));
2032         else if (Op1Not)
2033           // orc(~x, y) = ~(x & y) = nand(x, y)
2034           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
2035                                            MVT::i1, MachineNode->getOperand(0).
2036                                                       getOperand(0),
2037                                            MachineNode->getOperand(1));
2038         else if (Op2Not)
2039           // orc(x, ~y) = x | y
2040           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
2041                                            MVT::i1, MachineNode->getOperand(0),
2042                                            MachineNode->getOperand(1).
2043                                              getOperand(0));
2044         else if (AllUsersSelectZero(MachineNode))
2045           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
2046                                            MVT::i1, MachineNode->getOperand(1),
2047                                            MachineNode->getOperand(0)),
2048           SelectSwap = true;
2049         break;
2050       case PPC::SELECT_I4:
2051       case PPC::SELECT_I8:
2052       case PPC::SELECT_F4:
2053       case PPC::SELECT_F8:
2054       case PPC::SELECT_VRRC:
2055       case PPC::SELECT_VSFRC:
2056       case PPC::SELECT_VSRC:
2057         if (Op1Set)
2058           ResNode = MachineNode->getOperand(1).getNode();
2059         else if (Op1Unset)
2060           ResNode = MachineNode->getOperand(2).getNode();
2061         else if (Op1Not)
2062           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
2063                                            SDLoc(MachineNode),
2064                                            MachineNode->getValueType(0),
2065                                            MachineNode->getOperand(0).
2066                                              getOperand(0),
2067                                            MachineNode->getOperand(2),
2068                                            MachineNode->getOperand(1));
2069         break;
2070       case PPC::BC:
2071       case PPC::BCn:
2072         if (Op1Not)
2073           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
2074                                                                PPC::BC,
2075                                            SDLoc(MachineNode),
2076                                            MVT::Other,
2077                                            MachineNode->getOperand(0).
2078                                              getOperand(0),
2079                                            MachineNode->getOperand(1),
2080                                            MachineNode->getOperand(2));
2081         // FIXME: Handle Op1Set, Op1Unset here too.
2082         break;
2083       }
2084
2085       // If we're inverting this node because it is used only by selects that
2086       // we'd like to swap, then swap the selects before the node replacement.
2087       if (SelectSwap)
2088         SwapAllSelectUsers(MachineNode);
2089
2090       if (ResNode != MachineNode) {
2091         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
2092         DEBUG(MachineNode->dump(CurDAG));
2093         DEBUG(dbgs() << "\nNew: ");
2094         DEBUG(ResNode->dump(CurDAG));
2095         DEBUG(dbgs() << "\n");
2096
2097         ReplaceUses(MachineNode, ResNode);
2098         IsModified = true;
2099       }
2100     }
2101     if (IsModified)
2102       CurDAG->RemoveDeadNodes();
2103   } while (IsModified);
2104 }
2105
2106 // Gather the set of 32-bit operations that are known to have their
2107 // higher-order 32 bits zero, where ToPromote contains all such operations.
2108 static bool PeepholePPC64ZExtGather(SDValue Op32,
2109                                     SmallPtrSetImpl<SDNode *> &ToPromote) {
2110   if (!Op32.isMachineOpcode())
2111     return false;
2112
2113   // First, check for the "frontier" instructions (those that will clear the
2114   // higher-order 32 bits.
2115
2116   // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
2117   // around. If it does not, then these instructions will clear the
2118   // higher-order bits.
2119   if ((Op32.getMachineOpcode() == PPC::RLWINM ||
2120        Op32.getMachineOpcode() == PPC::RLWNM) &&
2121       Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
2122     ToPromote.insert(Op32.getNode());
2123     return true;
2124   }
2125
2126   // SLW and SRW always clear the higher-order bits.
2127   if (Op32.getMachineOpcode() == PPC::SLW ||
2128       Op32.getMachineOpcode() == PPC::SRW) {
2129     ToPromote.insert(Op32.getNode());
2130     return true;
2131   }
2132
2133   // For LI and LIS, we need the immediate to be positive (so that it is not
2134   // sign extended).
2135   if (Op32.getMachineOpcode() == PPC::LI ||
2136       Op32.getMachineOpcode() == PPC::LIS) {
2137     if (!isUInt<15>(Op32.getConstantOperandVal(0)))
2138       return false;
2139
2140     ToPromote.insert(Op32.getNode());
2141     return true;
2142   }
2143
2144   // Next, check for those instructions we can look through.
2145
2146   // Assuming the mask does not wrap around, then the higher-order bits are
2147   // taken directly from the first operand.
2148   if (Op32.getMachineOpcode() == PPC::RLWIMI &&
2149       Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
2150     SmallPtrSet<SDNode *, 16> ToPromote1;
2151     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
2152       return false;
2153
2154     ToPromote.insert(Op32.getNode());
2155     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
2156     return true;
2157   }
2158
2159   // For OR, the higher-order bits are zero if that is true for both operands.
2160   // For SELECT_I4, the same is true (but the relevant operand numbers are
2161   // shifted by 1).
2162   if (Op32.getMachineOpcode() == PPC::OR ||
2163       Op32.getMachineOpcode() == PPC::SELECT_I4) {
2164     unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
2165     SmallPtrSet<SDNode *, 16> ToPromote1;
2166     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
2167       return false;
2168     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
2169       return false;
2170
2171     ToPromote.insert(Op32.getNode());
2172     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
2173     return true;
2174   }
2175
2176   // For ORI and ORIS, we need the higher-order bits of the first operand to be
2177   // zero, and also for the constant to be positive (so that it is not sign
2178   // extended).
2179   if (Op32.getMachineOpcode() == PPC::ORI ||
2180       Op32.getMachineOpcode() == PPC::ORIS) {
2181     SmallPtrSet<SDNode *, 16> ToPromote1;
2182     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
2183       return false;
2184     if (!isUInt<15>(Op32.getConstantOperandVal(1)))
2185       return false;
2186
2187     ToPromote.insert(Op32.getNode());
2188     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
2189     return true;
2190   }
2191
2192   // The higher-order bits of AND are zero if that is true for at least one of
2193   // the operands.
2194   if (Op32.getMachineOpcode() == PPC::AND) {
2195     SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
2196     bool Op0OK =
2197       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
2198     bool Op1OK =
2199       PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
2200     if (!Op0OK && !Op1OK)
2201       return false;
2202
2203     ToPromote.insert(Op32.getNode());
2204
2205     if (Op0OK)
2206       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
2207
2208     if (Op1OK)
2209       ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
2210
2211     return true;
2212   }
2213
2214   // For ANDI and ANDIS, the higher-order bits are zero if either that is true
2215   // of the first operand, or if the second operand is positive (so that it is
2216   // not sign extended).
2217   if (Op32.getMachineOpcode() == PPC::ANDIo ||
2218       Op32.getMachineOpcode() == PPC::ANDISo) {
2219     SmallPtrSet<SDNode *, 16> ToPromote1;
2220     bool Op0OK =
2221       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
2222     bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
2223     if (!Op0OK && !Op1OK)
2224       return false;
2225
2226     ToPromote.insert(Op32.getNode());
2227
2228     if (Op0OK)
2229       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
2230
2231     return true;
2232   }
2233
2234   return false;
2235 }
2236
2237 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
2238   if (!PPCSubTarget->isPPC64())
2239     return;
2240
2241   // When we zero-extend from i32 to i64, we use a pattern like this:
2242   // def : Pat<(i64 (zext i32:$in)),
2243   //           (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
2244   //                   0, 32)>;
2245   // There are several 32-bit shift/rotate instructions, however, that will
2246   // clear the higher-order bits of their output, rendering the RLDICL
2247   // unnecessary. When that happens, we remove it here, and redefine the
2248   // relevant 32-bit operation to be a 64-bit operation.
2249
2250   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
2251   ++Position;
2252
2253   bool MadeChange = false;
2254   while (Position != CurDAG->allnodes_begin()) {
2255     SDNode *N = --Position;
2256     // Skip dead nodes and any non-machine opcodes.
2257     if (N->use_empty() || !N->isMachineOpcode())
2258       continue;
2259
2260     if (N->getMachineOpcode() != PPC::RLDICL)
2261       continue;
2262
2263     if (N->getConstantOperandVal(1) != 0 ||
2264         N->getConstantOperandVal(2) != 32)
2265       continue;
2266
2267     SDValue ISR = N->getOperand(0);
2268     if (!ISR.isMachineOpcode() ||
2269         ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
2270       continue;
2271
2272     if (!ISR.hasOneUse())
2273       continue;
2274
2275     if (ISR.getConstantOperandVal(2) != PPC::sub_32)
2276       continue;
2277
2278     SDValue IDef = ISR.getOperand(0);
2279     if (!IDef.isMachineOpcode() ||
2280         IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
2281       continue;
2282
2283     // We now know that we're looking at a canonical i32 -> i64 zext. See if we
2284     // can get rid of it.
2285
2286     SDValue Op32 = ISR->getOperand(1);
2287     if (!Op32.isMachineOpcode())
2288       continue;
2289
2290     // There are some 32-bit instructions that always clear the high-order 32
2291     // bits, there are also some instructions (like AND) that we can look
2292     // through.
2293     SmallPtrSet<SDNode *, 16> ToPromote;
2294     if (!PeepholePPC64ZExtGather(Op32, ToPromote))
2295       continue;
2296
2297     // If the ToPromote set contains nodes that have uses outside of the set
2298     // (except for the original INSERT_SUBREG), then abort the transformation.
2299     bool OutsideUse = false;
2300     for (SDNode *PN : ToPromote) {
2301       for (SDNode *UN : PN->uses()) {
2302         if (!ToPromote.count(UN) && UN != ISR.getNode()) {
2303           OutsideUse = true;
2304           break;
2305         }
2306       }
2307
2308       if (OutsideUse)
2309         break;
2310     }
2311     if (OutsideUse)
2312       continue;
2313
2314     MadeChange = true;
2315
2316     // We now know that this zero extension can be removed by promoting to
2317     // nodes in ToPromote to 64-bit operations, where for operations in the
2318     // frontier of the set, we need to insert INSERT_SUBREGs for their
2319     // operands.
2320     for (SDNode *PN : ToPromote) {
2321       unsigned NewOpcode;
2322       switch (PN->getMachineOpcode()) {
2323       default:
2324         llvm_unreachable("Don't know the 64-bit variant of this instruction");
2325       case PPC::RLWINM:    NewOpcode = PPC::RLWINM8; break;
2326       case PPC::RLWNM:     NewOpcode = PPC::RLWNM8; break;
2327       case PPC::SLW:       NewOpcode = PPC::SLW8; break;
2328       case PPC::SRW:       NewOpcode = PPC::SRW8; break;
2329       case PPC::LI:        NewOpcode = PPC::LI8; break;
2330       case PPC::LIS:       NewOpcode = PPC::LIS8; break;
2331       case PPC::RLWIMI:    NewOpcode = PPC::RLWIMI8; break;
2332       case PPC::OR:        NewOpcode = PPC::OR8; break;
2333       case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
2334       case PPC::ORI:       NewOpcode = PPC::ORI8; break;
2335       case PPC::ORIS:      NewOpcode = PPC::ORIS8; break;
2336       case PPC::AND:       NewOpcode = PPC::AND8; break;
2337       case PPC::ANDIo:     NewOpcode = PPC::ANDIo8; break;
2338       case PPC::ANDISo:    NewOpcode = PPC::ANDISo8; break;
2339       }
2340
2341       // Note: During the replacement process, the nodes will be in an
2342       // inconsistent state (some instructions will have operands with values
2343       // of the wrong type). Once done, however, everything should be right
2344       // again.
2345
2346       SmallVector<SDValue, 4> Ops;
2347       for (const SDValue &V : PN->ops()) {
2348         if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
2349             !isa<ConstantSDNode>(V)) {
2350           SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
2351           SDNode *ReplOp =
2352             CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
2353                                    ISR.getNode()->getVTList(), ReplOpOps);
2354           Ops.push_back(SDValue(ReplOp, 0));
2355         } else {
2356           Ops.push_back(V);
2357         }
2358       }
2359
2360       // Because all to-be-promoted nodes only have users that are other
2361       // promoted nodes (or the original INSERT_SUBREG), we can safely replace
2362       // the i32 result value type with i64.
2363
2364       SmallVector<EVT, 2> NewVTs;
2365       SDVTList VTs = PN->getVTList();
2366       for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
2367         if (VTs.VTs[i] == MVT::i32)
2368           NewVTs.push_back(MVT::i64);
2369         else
2370           NewVTs.push_back(VTs.VTs[i]);
2371
2372       DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld:    ");
2373       DEBUG(PN->dump(CurDAG));
2374
2375       CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
2376
2377       DEBUG(dbgs() << "\nNew: ");
2378       DEBUG(PN->dump(CurDAG));
2379       DEBUG(dbgs() << "\n");
2380     }
2381
2382     // Now we replace the original zero extend and its associated INSERT_SUBREG
2383     // with the value feeding the INSERT_SUBREG (which has now been promoted to
2384     // return an i64).
2385
2386     DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld:    ");
2387     DEBUG(N->dump(CurDAG));
2388     DEBUG(dbgs() << "\nNew: ");
2389     DEBUG(Op32.getNode()->dump(CurDAG));
2390     DEBUG(dbgs() << "\n");
2391
2392     ReplaceUses(N, Op32.getNode());
2393   }
2394
2395   if (MadeChange)
2396     CurDAG->RemoveDeadNodes();
2397 }
2398
2399 void PPCDAGToDAGISel::PeepholePPC64() {
2400   // These optimizations are currently supported only for 64-bit SVR4.
2401   if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
2402     return;
2403
2404   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
2405   ++Position;
2406
2407   while (Position != CurDAG->allnodes_begin()) {
2408     SDNode *N = --Position;
2409     // Skip dead nodes and any non-machine opcodes.
2410     if (N->use_empty() || !N->isMachineOpcode())
2411       continue;
2412
2413     unsigned FirstOp;
2414     unsigned StorageOpcode = N->getMachineOpcode();
2415
2416     switch (StorageOpcode) {
2417     default: continue;
2418
2419     case PPC::LBZ:
2420     case PPC::LBZ8:
2421     case PPC::LD:
2422     case PPC::LFD:
2423     case PPC::LFS:
2424     case PPC::LHA:
2425     case PPC::LHA8:
2426     case PPC::LHZ:
2427     case PPC::LHZ8:
2428     case PPC::LWA:
2429     case PPC::LWZ:
2430     case PPC::LWZ8:
2431       FirstOp = 0;
2432       break;
2433
2434     case PPC::STB:
2435     case PPC::STB8:
2436     case PPC::STD:
2437     case PPC::STFD:
2438     case PPC::STFS:
2439     case PPC::STH:
2440     case PPC::STH8:
2441     case PPC::STW:
2442     case PPC::STW8:
2443       FirstOp = 1;
2444       break;
2445     }
2446
2447     // If this is a load or store with a zero offset, we may be able to
2448     // fold an add-immediate into the memory operation.
2449     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
2450         N->getConstantOperandVal(FirstOp) != 0)
2451       continue;
2452
2453     SDValue Base = N->getOperand(FirstOp + 1);
2454     if (!Base.isMachineOpcode())
2455       continue;
2456
2457     unsigned Flags = 0;
2458     bool ReplaceFlags = true;
2459
2460     // When the feeding operation is an add-immediate of some sort,
2461     // determine whether we need to add relocation information to the
2462     // target flags on the immediate operand when we fold it into the
2463     // load instruction.
2464     //
2465     // For something like ADDItocL, the relocation information is
2466     // inferred from the opcode; when we process it in the AsmPrinter,
2467     // we add the necessary relocation there.  A load, though, can receive
2468     // relocation from various flavors of ADDIxxx, so we need to carry
2469     // the relocation information in the target flags.
2470     switch (Base.getMachineOpcode()) {
2471     default: continue;
2472
2473     case PPC::ADDI8:
2474     case PPC::ADDI:
2475       // In some cases (such as TLS) the relocation information
2476       // is already in place on the operand, so copying the operand
2477       // is sufficient.
2478       ReplaceFlags = false;
2479       // For these cases, the immediate may not be divisible by 4, in
2480       // which case the fold is illegal for DS-form instructions.  (The
2481       // other cases provide aligned addresses and are always safe.)
2482       if ((StorageOpcode == PPC::LWA ||
2483            StorageOpcode == PPC::LD  ||
2484            StorageOpcode == PPC::STD) &&
2485           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
2486            Base.getConstantOperandVal(1) % 4 != 0))
2487         continue;
2488       break;
2489     case PPC::ADDIdtprelL:
2490       Flags = PPCII::MO_DTPREL_LO;
2491       break;
2492     case PPC::ADDItlsldL:
2493       Flags = PPCII::MO_TLSLD_LO;
2494       break;
2495     case PPC::ADDItocL:
2496       Flags = PPCII::MO_TOC_LO;
2497       break;
2498     }
2499
2500     // We found an opportunity.  Reverse the operands from the add
2501     // immediate and substitute them into the load or store.  If
2502     // needed, update the target flags for the immediate operand to
2503     // reflect the necessary relocation information.
2504     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2505     DEBUG(Base->dump(CurDAG));
2506     DEBUG(dbgs() << "\nN: ");
2507     DEBUG(N->dump(CurDAG));
2508     DEBUG(dbgs() << "\n");
2509
2510     SDValue ImmOpnd = Base.getOperand(1);
2511
2512     // If the relocation information isn't already present on the
2513     // immediate operand, add it now.
2514     if (ReplaceFlags) {
2515       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
2516         SDLoc dl(GA);
2517         const GlobalValue *GV = GA->getGlobal();
2518         // We can't perform this optimization for data whose alignment
2519         // is insufficient for the instruction encoding.
2520         if (GV->getAlignment() < 4 &&
2521             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
2522              StorageOpcode == PPC::LWA)) {
2523           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
2524           continue;
2525         }
2526         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
2527       } else if (ConstantPoolSDNode *CP =
2528                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
2529         const Constant *C = CP->getConstVal();
2530         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
2531                                                 CP->getAlignment(),
2532                                                 0, Flags);
2533       }
2534     }
2535
2536     if (FirstOp == 1) // Store
2537       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
2538                                        Base.getOperand(0), N->getOperand(3));
2539     else // Load
2540       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
2541                                        N->getOperand(2));
2542
2543     // The add-immediate may now be dead, in which case remove it.
2544     if (Base.getNode()->use_empty())
2545       CurDAG->RemoveDeadNode(Base.getNode());
2546   }
2547 }
2548
2549
2550 /// createPPCISelDag - This pass converts a legalized DAG into a
2551 /// PowerPC-specific DAG, ready for instruction scheduling.
2552 ///
2553 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
2554   return new PPCDAGToDAGISel(TM);
2555 }
2556
2557 static void initializePassOnce(PassRegistry &Registry) {
2558   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
2559   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
2560                               nullptr, false, false);
2561   Registry.registerPass(*PI, true);
2562 }
2563
2564 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
2565   CALL_ONCE_INITIALIZATION(initializePassOnce);
2566 }
2567