1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> EnablePPCPCRelTLS(
125     "enable-ppc-pcrel-tls",
126     cl::desc("enable the use of PC relative memops in TLS instructions on PPC"),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
226                         isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230 
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
232       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
233                          isPPC64 ? MVT::i64 : MVT::i32);
234       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
235       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
236                         isPPC64 ? MVT::i64 : MVT::i32);
237     } else {
238       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
239       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
240       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
241       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
242     }
243 
244     // PowerPC does not support direct load/store of condition registers.
245     setOperationAction(ISD::LOAD, MVT::i1, Custom);
246     setOperationAction(ISD::STORE, MVT::i1, Custom);
247 
248     // FIXME: Remove this once the ANDI glue bug is fixed:
249     if (ANDIGlueBug)
250       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
251 
252     for (MVT VT : MVT::integer_valuetypes()) {
253       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
254       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
255       setTruncStoreAction(VT, MVT::i1, Expand);
256     }
257 
258     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
259   }
260 
261   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
262   // PPC (the libcall is not available).
263   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
264   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
265 
266   // We do not currently implement these libm ops for PowerPC.
267   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
268   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
269   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
270   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
271   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
272   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
273 
274   // PowerPC has no SREM/UREM instructions unless we are on P9
275   // On P9 we may use a hardware instruction to compute the remainder.
276   // When the result of both the remainder and the division is required it is
277   // more efficient to compute the remainder from the result of the division
278   // rather than use the remainder instruction. The instructions are legalized
279   // directly because the DivRemPairsPass performs the transformation at the IR
280   // level.
281   if (Subtarget.isISA3_0()) {
282     setOperationAction(ISD::SREM, MVT::i32, Legal);
283     setOperationAction(ISD::UREM, MVT::i32, Legal);
284     setOperationAction(ISD::SREM, MVT::i64, Legal);
285     setOperationAction(ISD::UREM, MVT::i64, Legal);
286   } else {
287     setOperationAction(ISD::SREM, MVT::i32, Expand);
288     setOperationAction(ISD::UREM, MVT::i32, Expand);
289     setOperationAction(ISD::SREM, MVT::i64, Expand);
290     setOperationAction(ISD::UREM, MVT::i64, Expand);
291   }
292 
293   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
294   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
295   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
296   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
297   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
298   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
299   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
300   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
301   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
302 
303   // Handle constrained floating-point operations of scalar.
304   // TODO: Handle SPE specific operation.
305   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
306   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
307   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
308   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
309   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
310   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
311 
312   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
313   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
314   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
315   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
316   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
317   if (Subtarget.hasVSX())
318     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
319 
320   if (Subtarget.hasFSQRT()) {
321     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
322     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
323   }
324 
325   if (Subtarget.hasFPRND()) {
326     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
327     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
328     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
329     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
330 
331     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
332     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
333     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
334     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
335   }
336 
337   // We don't support sin/cos/sqrt/fmod/pow
338   setOperationAction(ISD::FSIN , MVT::f64, Expand);
339   setOperationAction(ISD::FCOS , MVT::f64, Expand);
340   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
341   setOperationAction(ISD::FREM , MVT::f64, Expand);
342   setOperationAction(ISD::FPOW , MVT::f64, Expand);
343   setOperationAction(ISD::FSIN , MVT::f32, Expand);
344   setOperationAction(ISD::FCOS , MVT::f32, Expand);
345   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
346   setOperationAction(ISD::FREM , MVT::f32, Expand);
347   setOperationAction(ISD::FPOW , MVT::f32, Expand);
348   if (Subtarget.hasSPE()) {
349     setOperationAction(ISD::FMA  , MVT::f64, Expand);
350     setOperationAction(ISD::FMA  , MVT::f32, Expand);
351   } else {
352     setOperationAction(ISD::FMA  , MVT::f64, Legal);
353     setOperationAction(ISD::FMA  , MVT::f32, Legal);
354   }
355 
356   if (Subtarget.hasSPE())
357     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
358 
359   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
360 
361   // If we're enabling GP optimizations, use hardware square root
362   if (!Subtarget.hasFSQRT() &&
363       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
364         Subtarget.hasFRE()))
365     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
366 
367   if (!Subtarget.hasFSQRT() &&
368       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
369         Subtarget.hasFRES()))
370     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
371 
372   if (Subtarget.hasFCPSGN()) {
373     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
374     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
375   } else {
376     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
377     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
378   }
379 
380   if (Subtarget.hasFPRND()) {
381     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
382     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
383     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
384     setOperationAction(ISD::FROUND, MVT::f64, Legal);
385 
386     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
387     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
388     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
389     setOperationAction(ISD::FROUND, MVT::f32, Legal);
390   }
391 
392   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
393   // to speed up scalar BSWAP64.
394   // CTPOP or CTTZ were introduced in P8/P9 respectively
395   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
396   if (Subtarget.hasP9Vector())
397     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
398   else
399     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
400   if (Subtarget.isISA3_0()) {
401     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
402     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
403   } else {
404     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
405     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
406   }
407 
408   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
409     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
410     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
411   } else {
412     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
413     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
414   }
415 
416   // PowerPC does not have ROTR
417   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
418   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
419 
420   if (!Subtarget.useCRBits()) {
421     // PowerPC does not have Select
422     setOperationAction(ISD::SELECT, MVT::i32, Expand);
423     setOperationAction(ISD::SELECT, MVT::i64, Expand);
424     setOperationAction(ISD::SELECT, MVT::f32, Expand);
425     setOperationAction(ISD::SELECT, MVT::f64, Expand);
426   }
427 
428   // PowerPC wants to turn select_cc of FP into fsel when possible.
429   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
430   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
431 
432   // PowerPC wants to optimize integer setcc a bit
433   if (!Subtarget.useCRBits())
434     setOperationAction(ISD::SETCC, MVT::i32, Custom);
435 
436   if (Subtarget.hasFPU()) {
437     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
438     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
439     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
440 
441     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
442     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
443     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
444   }
445 
446   // PowerPC does not have BRCOND which requires SetCC
447   if (!Subtarget.useCRBits())
448     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
449 
450   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
451 
452   if (Subtarget.hasSPE()) {
453     // SPE has built-in conversions
454     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
455     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
456     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
457     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
458     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
459     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
460   } else {
461     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
462     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
463     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
464 
465     // PowerPC does not have [U|S]INT_TO_FP
466     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
467     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
468     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
469     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
470   }
471 
472   if (Subtarget.hasDirectMove() && isPPC64) {
473     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
474     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
475     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
476     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
477     if (TM.Options.UnsafeFPMath) {
478       setOperationAction(ISD::LRINT, MVT::f64, Legal);
479       setOperationAction(ISD::LRINT, MVT::f32, Legal);
480       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
481       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
482       setOperationAction(ISD::LROUND, MVT::f64, Legal);
483       setOperationAction(ISD::LROUND, MVT::f32, Legal);
484       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
485       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
486     }
487   } else {
488     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
489     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
490     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
491     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
492   }
493 
494   // We cannot sextinreg(i1).  Expand to shifts.
495   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
496 
497   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
498   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
499   // support continuation, user-level threading, and etc.. As a result, no
500   // other SjLj exception interfaces are implemented and please don't build
501   // your own exception handling based on them.
502   // LLVM/Clang supports zero-cost DWARF exception handling.
503   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
504   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
505 
506   // We want to legalize GlobalAddress and ConstantPool nodes into the
507   // appropriate instructions to materialize the address.
508   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
509   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
510   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
511   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
512   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
513   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
514   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
515   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
516   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
517   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
518 
519   // TRAP is legal.
520   setOperationAction(ISD::TRAP, MVT::Other, Legal);
521 
522   // TRAMPOLINE is custom lowered.
523   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
524   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
525 
526   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
527   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
528 
529   if (Subtarget.is64BitELFABI()) {
530     // VAARG always uses double-word chunks, so promote anything smaller.
531     setOperationAction(ISD::VAARG, MVT::i1, Promote);
532     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
533     setOperationAction(ISD::VAARG, MVT::i8, Promote);
534     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
535     setOperationAction(ISD::VAARG, MVT::i16, Promote);
536     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
537     setOperationAction(ISD::VAARG, MVT::i32, Promote);
538     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
539     setOperationAction(ISD::VAARG, MVT::Other, Expand);
540   } else if (Subtarget.is32BitELFABI()) {
541     // VAARG is custom lowered with the 32-bit SVR4 ABI.
542     setOperationAction(ISD::VAARG, MVT::Other, Custom);
543     setOperationAction(ISD::VAARG, MVT::i64, Custom);
544   } else
545     setOperationAction(ISD::VAARG, MVT::Other, Expand);
546 
547   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
548   if (Subtarget.is32BitELFABI())
549     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
550   else
551     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
552 
553   // Use the default implementation.
554   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
555   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
556   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
557   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
558   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
559   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
560   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
561   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
562   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
563 
564   // We want to custom lower some of our intrinsics.
565   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
566 
567   // To handle counter-based loop conditions.
568   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
569 
570   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
571   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
572   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
573   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
574 
575   // Comparisons that require checking two conditions.
576   if (Subtarget.hasSPE()) {
577     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
578     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
579     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
580     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
581   }
582   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
583   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
584   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
585   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
586   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
587   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
588   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
589   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
590   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
591   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
592   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
593   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
594 
595   if (Subtarget.has64BitSupport()) {
596     // They also have instructions for converting between i64 and fp.
597     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
598     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
599     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
600     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
601     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
602     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
603     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
604     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
605     // This is just the low 32 bits of a (signed) fp->i64 conversion.
606     // We cannot do this with Promote because i64 is not a legal type.
607     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
608     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
609 
610     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
611       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
612       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
613     }
614   } else {
615     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
616     if (Subtarget.hasSPE()) {
617       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
618       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
619     } else {
620       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
621       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
622     }
623   }
624 
625   // With the instructions enabled under FPCVT, we can do everything.
626   if (Subtarget.hasFPCVT()) {
627     if (Subtarget.has64BitSupport()) {
628       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
629       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
630       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
631       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
632       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
633       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
634       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
635       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
636     }
637 
638     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
639     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
640     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
641     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
644     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
645     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
646   }
647 
648   if (Subtarget.use64BitRegs()) {
649     // 64-bit PowerPC implementations can support i64 types directly
650     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
651     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
652     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
653     // 64-bit PowerPC wants to expand i128 shifts itself.
654     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
655     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
656     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
657   } else {
658     // 32-bit PowerPC wants to expand i64 shifts itself.
659     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
660     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
661     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
662   }
663 
664   // PowerPC has better expansions for funnel shifts than the generic
665   // TargetLowering::expandFunnelShift.
666   if (Subtarget.has64BitSupport()) {
667     setOperationAction(ISD::FSHL, MVT::i64, Custom);
668     setOperationAction(ISD::FSHR, MVT::i64, Custom);
669   }
670   setOperationAction(ISD::FSHL, MVT::i32, Custom);
671   setOperationAction(ISD::FSHR, MVT::i32, Custom);
672 
673   if (Subtarget.hasVSX()) {
674     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
675     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
676     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
677     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
678   }
679 
680   if (Subtarget.hasAltivec()) {
681     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
682       setOperationAction(ISD::SADDSAT, VT, Legal);
683       setOperationAction(ISD::SSUBSAT, VT, Legal);
684       setOperationAction(ISD::UADDSAT, VT, Legal);
685       setOperationAction(ISD::USUBSAT, VT, Legal);
686     }
687     // First set operation action for all vector types to expand. Then we
688     // will selectively turn on ones that can be effectively codegen'd.
689     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
690       // add/sub are legal for all supported vector VT's.
691       setOperationAction(ISD::ADD, VT, Legal);
692       setOperationAction(ISD::SUB, VT, Legal);
693 
694       // For v2i64, these are only valid with P8Vector. This is corrected after
695       // the loop.
696       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
697         setOperationAction(ISD::SMAX, VT, Legal);
698         setOperationAction(ISD::SMIN, VT, Legal);
699         setOperationAction(ISD::UMAX, VT, Legal);
700         setOperationAction(ISD::UMIN, VT, Legal);
701       }
702       else {
703         setOperationAction(ISD::SMAX, VT, Expand);
704         setOperationAction(ISD::SMIN, VT, Expand);
705         setOperationAction(ISD::UMAX, VT, Expand);
706         setOperationAction(ISD::UMIN, VT, Expand);
707       }
708 
709       if (Subtarget.hasVSX()) {
710         setOperationAction(ISD::FMAXNUM, VT, Legal);
711         setOperationAction(ISD::FMINNUM, VT, Legal);
712       }
713 
714       // Vector instructions introduced in P8
715       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
716         setOperationAction(ISD::CTPOP, VT, Legal);
717         setOperationAction(ISD::CTLZ, VT, Legal);
718       }
719       else {
720         setOperationAction(ISD::CTPOP, VT, Expand);
721         setOperationAction(ISD::CTLZ, VT, Expand);
722       }
723 
724       // Vector instructions introduced in P9
725       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
726         setOperationAction(ISD::CTTZ, VT, Legal);
727       else
728         setOperationAction(ISD::CTTZ, VT, Expand);
729 
730       // We promote all shuffles to v16i8.
731       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
732       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
733 
734       // We promote all non-typed operations to v4i32.
735       setOperationAction(ISD::AND   , VT, Promote);
736       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
737       setOperationAction(ISD::OR    , VT, Promote);
738       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
739       setOperationAction(ISD::XOR   , VT, Promote);
740       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
741       setOperationAction(ISD::LOAD  , VT, Promote);
742       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
743       setOperationAction(ISD::SELECT, VT, Promote);
744       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
745       setOperationAction(ISD::VSELECT, VT, Legal);
746       setOperationAction(ISD::SELECT_CC, VT, Promote);
747       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
748       setOperationAction(ISD::STORE, VT, Promote);
749       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
750 
751       // No other operations are legal.
752       setOperationAction(ISD::MUL , VT, Expand);
753       setOperationAction(ISD::SDIV, VT, Expand);
754       setOperationAction(ISD::SREM, VT, Expand);
755       setOperationAction(ISD::UDIV, VT, Expand);
756       setOperationAction(ISD::UREM, VT, Expand);
757       setOperationAction(ISD::FDIV, VT, Expand);
758       setOperationAction(ISD::FREM, VT, Expand);
759       setOperationAction(ISD::FNEG, VT, Expand);
760       setOperationAction(ISD::FSQRT, VT, Expand);
761       setOperationAction(ISD::FLOG, VT, Expand);
762       setOperationAction(ISD::FLOG10, VT, Expand);
763       setOperationAction(ISD::FLOG2, VT, Expand);
764       setOperationAction(ISD::FEXP, VT, Expand);
765       setOperationAction(ISD::FEXP2, VT, Expand);
766       setOperationAction(ISD::FSIN, VT, Expand);
767       setOperationAction(ISD::FCOS, VT, Expand);
768       setOperationAction(ISD::FABS, VT, Expand);
769       setOperationAction(ISD::FFLOOR, VT, Expand);
770       setOperationAction(ISD::FCEIL,  VT, Expand);
771       setOperationAction(ISD::FTRUNC, VT, Expand);
772       setOperationAction(ISD::FRINT,  VT, Expand);
773       setOperationAction(ISD::FNEARBYINT, VT, Expand);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
775       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
776       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
777       setOperationAction(ISD::MULHU, VT, Expand);
778       setOperationAction(ISD::MULHS, VT, Expand);
779       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
780       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
781       setOperationAction(ISD::UDIVREM, VT, Expand);
782       setOperationAction(ISD::SDIVREM, VT, Expand);
783       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
784       setOperationAction(ISD::FPOW, VT, Expand);
785       setOperationAction(ISD::BSWAP, VT, Expand);
786       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
787       setOperationAction(ISD::ROTL, VT, Expand);
788       setOperationAction(ISD::ROTR, VT, Expand);
789 
790       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
791         setTruncStoreAction(VT, InnerVT, Expand);
792         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
793         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
794         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
795       }
796     }
797     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
798     if (!Subtarget.hasP8Vector()) {
799       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
800       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
801       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
802       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
803     }
804 
805     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
806       setOperationAction(ISD::ABS, VT, Custom);
807 
808     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
809     // with merges, splats, etc.
810     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
811 
812     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
813     // are cheap, so handle them before they get expanded to scalar.
814     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
815     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
816     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
817     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
818     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
819 
820     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
821     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
822     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
823     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
824     setOperationAction(ISD::SELECT, MVT::v4i32,
825                        Subtarget.useCRBits() ? Legal : Expand);
826     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
827     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
828     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
829     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
830     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
831     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
832     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
833     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
834     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
835     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
836     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
837     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
838     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
839 
840     // Without hasP8Altivec set, v2i64 SMAX isn't available.
841     // But ABS custom lowering requires SMAX support.
842     if (!Subtarget.hasP8Altivec())
843       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
844 
845     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
846     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
847     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
848     if (Subtarget.hasAltivec())
849       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
850         setOperationAction(ISD::ROTL, VT, Legal);
851     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
852     if (Subtarget.hasP8Altivec())
853       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
854 
855     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
856     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
857     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
858     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
859 
860     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
861     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
862 
863     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
864       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
865       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
866     }
867 
868     if (Subtarget.hasP8Altivec())
869       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
870     else
871       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
872 
873     if (Subtarget.isISA3_1()) {
874       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
875       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
876       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
877       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
878       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
879       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
880       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
881       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
882       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
883       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
884       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
885       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
886       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
887     }
888 
889     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
890     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
891 
892     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
893     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
894 
895     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
896     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
897     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
898     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
899 
900     // Altivec does not contain unordered floating-point compare instructions
901     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
902     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
903     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
904     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
905 
906     if (Subtarget.hasVSX()) {
907       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
908       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
909       if (Subtarget.hasP8Vector()) {
910         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
911         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
912       }
913       if (Subtarget.hasDirectMove() && isPPC64) {
914         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
915         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
916         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
917         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
918         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
919         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
920         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
921         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
922       }
923       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
924 
925       // The nearbyint variants are not allowed to raise the inexact exception
926       // so we can only code-gen them with unsafe math.
927       if (TM.Options.UnsafeFPMath) {
928         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
929         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
930       }
931 
932       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
933       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
934       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
935       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
936       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
937       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
938       setOperationAction(ISD::FROUND, MVT::f64, Legal);
939       setOperationAction(ISD::FRINT, MVT::f64, Legal);
940 
941       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
942       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
943       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
944       setOperationAction(ISD::FROUND, MVT::f32, Legal);
945       setOperationAction(ISD::FRINT, MVT::f32, Legal);
946 
947       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
948       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
949 
950       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
951       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
952 
953       // Share the Altivec comparison restrictions.
954       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
955       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
956       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
957       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
958 
959       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
960       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
961 
962       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
963 
964       if (Subtarget.hasP8Vector())
965         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
966 
967       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
968 
969       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
970       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
971       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
972 
973       if (Subtarget.hasP8Altivec()) {
974         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
975         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
976         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
977 
978         // 128 bit shifts can be accomplished via 3 instructions for SHL and
979         // SRL, but not for SRA because of the instructions available:
980         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
981         // doing
982         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
983         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
984         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
985 
986         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
987       }
988       else {
989         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
990         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
991         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
992 
993         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
994 
995         // VSX v2i64 only supports non-arithmetic operations.
996         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
997         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
998       }
999 
1000       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1001 
1002       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1003       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1004       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1005       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1006 
1007       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1008 
1009       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1010       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1011       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1012       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1013       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1014       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1015       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1016       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1017 
1018       // Custom handling for partial vectors of integers converted to
1019       // floating point. We already have optimal handling for v2i32 through
1020       // the DAG combine, so those aren't necessary.
1021       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1022       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1023       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1024       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1025       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1026       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1027       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1028       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1029       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1030       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1031       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1032       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1033       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1034       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1035       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1036       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1037 
1038       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1039       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1040       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1041       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1042       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1043       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1044 
1045       if (Subtarget.hasDirectMove())
1046         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1047       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1048 
1049       // Handle constrained floating-point operations of vector.
1050       // The predictor is `hasVSX` because altivec instruction has
1051       // no exception but VSX vector instruction has.
1052       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1053       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1054       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1055       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1056       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1057       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1058       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1059       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1060       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
1061       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1062       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1063       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1064       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1065 
1066       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1067       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1068       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1069       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1070       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1071       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1072       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1073       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1074       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1075       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1076       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1077       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1078       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1079 
1080       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1081     }
1082 
1083     if (Subtarget.hasP8Altivec()) {
1084       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1085       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1086     }
1087 
1088     if (Subtarget.hasP9Vector()) {
1089       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1090       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1091 
1092       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1093       // SRL, but not for SRA because of the instructions available:
1094       // VS{RL} and VS{RL}O.
1095       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1096       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1097       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1098 
1099       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1100       setOperationAction(ISD::FADD, MVT::f128, Legal);
1101       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1102       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1103       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1104       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1105       // No extending loads to f128 on PPC.
1106       for (MVT FPT : MVT::fp_valuetypes())
1107         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1108       setOperationAction(ISD::FMA, MVT::f128, Legal);
1109       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1110       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1111       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1112       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1113       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1114       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1115 
1116       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1117       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1118       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1119       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1120       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1121       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1122 
1123       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1124       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1125       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1126       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1127       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1128       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1129       // No implementation for these ops for PowerPC.
1130       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1131       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1132       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1133       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1134       setOperationAction(ISD::FREM, MVT::f128, Expand);
1135 
1136       // Handle constrained floating-point operations of fp128
1137       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1138       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1139       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1140       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1141       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1142       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1143       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1144       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1145       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1146       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1147       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1148       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1149       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1150       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1151       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1152       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1153       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1154       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1155       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1156       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1157     }
1158 
1159     if (Subtarget.hasP9Altivec()) {
1160       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1161       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1162 
1163       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1164       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1165       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1166       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1167       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1168       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1169       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1170     }
1171   }
1172 
1173   if (Subtarget.has64BitSupport())
1174     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1175 
1176   if (Subtarget.isISA3_1())
1177     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1178 
1179   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1180 
1181   if (!isPPC64) {
1182     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1183     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1184   }
1185 
1186   setBooleanContents(ZeroOrOneBooleanContent);
1187 
1188   if (Subtarget.hasAltivec()) {
1189     // Altivec instructions set fields to all zeros or all ones.
1190     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1191   }
1192 
1193   if (!isPPC64) {
1194     // These libcalls are not available in 32-bit.
1195     setLibcallName(RTLIB::SHL_I128, nullptr);
1196     setLibcallName(RTLIB::SRL_I128, nullptr);
1197     setLibcallName(RTLIB::SRA_I128, nullptr);
1198   }
1199 
1200   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1201 
1202   // We have target-specific dag combine patterns for the following nodes:
1203   setTargetDAGCombine(ISD::ADD);
1204   setTargetDAGCombine(ISD::SHL);
1205   setTargetDAGCombine(ISD::SRA);
1206   setTargetDAGCombine(ISD::SRL);
1207   setTargetDAGCombine(ISD::MUL);
1208   setTargetDAGCombine(ISD::FMA);
1209   setTargetDAGCombine(ISD::SINT_TO_FP);
1210   setTargetDAGCombine(ISD::BUILD_VECTOR);
1211   if (Subtarget.hasFPCVT())
1212     setTargetDAGCombine(ISD::UINT_TO_FP);
1213   setTargetDAGCombine(ISD::LOAD);
1214   setTargetDAGCombine(ISD::STORE);
1215   setTargetDAGCombine(ISD::BR_CC);
1216   if (Subtarget.useCRBits())
1217     setTargetDAGCombine(ISD::BRCOND);
1218   setTargetDAGCombine(ISD::BSWAP);
1219   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1220   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1221   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1222 
1223   setTargetDAGCombine(ISD::SIGN_EXTEND);
1224   setTargetDAGCombine(ISD::ZERO_EXTEND);
1225   setTargetDAGCombine(ISD::ANY_EXTEND);
1226 
1227   setTargetDAGCombine(ISD::TRUNCATE);
1228   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1229 
1230 
1231   if (Subtarget.useCRBits()) {
1232     setTargetDAGCombine(ISD::TRUNCATE);
1233     setTargetDAGCombine(ISD::SETCC);
1234     setTargetDAGCombine(ISD::SELECT_CC);
1235   }
1236 
1237   // Use reciprocal estimates.
1238   if (TM.Options.UnsafeFPMath) {
1239     setTargetDAGCombine(ISD::FDIV);
1240     setTargetDAGCombine(ISD::FSQRT);
1241   }
1242 
1243   if (Subtarget.hasP9Altivec()) {
1244     setTargetDAGCombine(ISD::ABS);
1245     setTargetDAGCombine(ISD::VSELECT);
1246   }
1247 
1248   setLibcallName(RTLIB::LOG_F128, "logf128");
1249   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1250   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1251   setLibcallName(RTLIB::EXP_F128, "expf128");
1252   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1253   setLibcallName(RTLIB::SIN_F128, "sinf128");
1254   setLibcallName(RTLIB::COS_F128, "cosf128");
1255   setLibcallName(RTLIB::POW_F128, "powf128");
1256   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1257   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1258   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1259   setLibcallName(RTLIB::REM_F128, "fmodf128");
1260 
1261   // With 32 condition bits, we don't need to sink (and duplicate) compares
1262   // aggressively in CodeGenPrep.
1263   if (Subtarget.useCRBits()) {
1264     setHasMultipleConditionRegisters();
1265     setJumpIsExpensive();
1266   }
1267 
1268   setMinFunctionAlignment(Align(4));
1269 
1270   switch (Subtarget.getCPUDirective()) {
1271   default: break;
1272   case PPC::DIR_970:
1273   case PPC::DIR_A2:
1274   case PPC::DIR_E500:
1275   case PPC::DIR_E500mc:
1276   case PPC::DIR_E5500:
1277   case PPC::DIR_PWR4:
1278   case PPC::DIR_PWR5:
1279   case PPC::DIR_PWR5X:
1280   case PPC::DIR_PWR6:
1281   case PPC::DIR_PWR6X:
1282   case PPC::DIR_PWR7:
1283   case PPC::DIR_PWR8:
1284   case PPC::DIR_PWR9:
1285   case PPC::DIR_PWR10:
1286   case PPC::DIR_PWR_FUTURE:
1287     setPrefLoopAlignment(Align(16));
1288     setPrefFunctionAlignment(Align(16));
1289     break;
1290   }
1291 
1292   if (Subtarget.enableMachineScheduler())
1293     setSchedulingPreference(Sched::Source);
1294   else
1295     setSchedulingPreference(Sched::Hybrid);
1296 
1297   computeRegisterProperties(STI.getRegisterInfo());
1298 
1299   // The Freescale cores do better with aggressive inlining of memcpy and
1300   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1301   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1302       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1303     MaxStoresPerMemset = 32;
1304     MaxStoresPerMemsetOptSize = 16;
1305     MaxStoresPerMemcpy = 32;
1306     MaxStoresPerMemcpyOptSize = 8;
1307     MaxStoresPerMemmove = 32;
1308     MaxStoresPerMemmoveOptSize = 8;
1309   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1310     // The A2 also benefits from (very) aggressive inlining of memcpy and
1311     // friends. The overhead of a the function call, even when warm, can be
1312     // over one hundred cycles.
1313     MaxStoresPerMemset = 128;
1314     MaxStoresPerMemcpy = 128;
1315     MaxStoresPerMemmove = 128;
1316     MaxLoadsPerMemcmp = 128;
1317   } else {
1318     MaxLoadsPerMemcmp = 8;
1319     MaxLoadsPerMemcmpOptSize = 4;
1320   }
1321 
1322   // Let the subtarget (CPU) decide if a predictable select is more expensive
1323   // than the corresponding branch. This information is used in CGP to decide
1324   // when to convert selects into branches.
1325   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1326 }
1327 
1328 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1329 /// the desired ByVal argument alignment.
1330 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1331   if (MaxAlign == MaxMaxAlign)
1332     return;
1333   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1334     if (MaxMaxAlign >= 32 &&
1335         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1336       MaxAlign = Align(32);
1337     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1338              MaxAlign < 16)
1339       MaxAlign = Align(16);
1340   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1341     Align EltAlign;
1342     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1343     if (EltAlign > MaxAlign)
1344       MaxAlign = EltAlign;
1345   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1346     for (auto *EltTy : STy->elements()) {
1347       Align EltAlign;
1348       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1349       if (EltAlign > MaxAlign)
1350         MaxAlign = EltAlign;
1351       if (MaxAlign == MaxMaxAlign)
1352         break;
1353     }
1354   }
1355 }
1356 
1357 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1358 /// function arguments in the caller parameter area.
1359 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1360                                                   const DataLayout &DL) const {
1361   // 16byte and wider vectors are passed on 16byte boundary.
1362   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1363   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1364   if (Subtarget.hasAltivec())
1365     getMaxByValAlign(Ty, Alignment, Align(16));
1366   return Alignment.value();
1367 }
1368 
1369 bool PPCTargetLowering::useSoftFloat() const {
1370   return Subtarget.useSoftFloat();
1371 }
1372 
1373 bool PPCTargetLowering::hasSPE() const {
1374   return Subtarget.hasSPE();
1375 }
1376 
1377 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1378   return VT.isScalarInteger();
1379 }
1380 
1381 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1382 /// type is cheaper than a multiply followed by a shift.
1383 /// This is true for words and doublewords on 64-bit PowerPC.
1384 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1385   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1386                               isOperationLegal(ISD::MULHU, Type)))
1387     return true;
1388   return TargetLowering::isMulhCheaperThanMulShift(Type);
1389 }
1390 
1391 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1392   switch ((PPCISD::NodeType)Opcode) {
1393   case PPCISD::FIRST_NUMBER:    break;
1394   case PPCISD::FSEL:            return "PPCISD::FSEL";
1395   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1396   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1397   case PPCISD::FCFID:           return "PPCISD::FCFID";
1398   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1399   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1400   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1401   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1402   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1403   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1404   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1405   case PPCISD::FP_TO_UINT_IN_VSR:
1406                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1407   case PPCISD::FP_TO_SINT_IN_VSR:
1408                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1409   case PPCISD::FRE:             return "PPCISD::FRE";
1410   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1411   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1412   case PPCISD::VPERM:           return "PPCISD::VPERM";
1413   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1414   case PPCISD::XXSPLTI_SP_TO_DP:
1415     return "PPCISD::XXSPLTI_SP_TO_DP";
1416   case PPCISD::XXSPLTI32DX:
1417     return "PPCISD::XXSPLTI32DX";
1418   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1419   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1420   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1421   case PPCISD::CMPB:            return "PPCISD::CMPB";
1422   case PPCISD::Hi:              return "PPCISD::Hi";
1423   case PPCISD::Lo:              return "PPCISD::Lo";
1424   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1425   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1426   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1427   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1428   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1429   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1430   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1431   case PPCISD::SRL:             return "PPCISD::SRL";
1432   case PPCISD::SRA:             return "PPCISD::SRA";
1433   case PPCISD::SHL:             return "PPCISD::SHL";
1434   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1435   case PPCISD::CALL:            return "PPCISD::CALL";
1436   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1437   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1438   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1439   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1440   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1441   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1442   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1443   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1444   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1445   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1446   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1447   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1448   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1449   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1450   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1451   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1452     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1453   case PPCISD::ANDI_rec_1_EQ_BIT:
1454     return "PPCISD::ANDI_rec_1_EQ_BIT";
1455   case PPCISD::ANDI_rec_1_GT_BIT:
1456     return "PPCISD::ANDI_rec_1_GT_BIT";
1457   case PPCISD::VCMP:            return "PPCISD::VCMP";
1458   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1459   case PPCISD::LBRX:            return "PPCISD::LBRX";
1460   case PPCISD::STBRX:           return "PPCISD::STBRX";
1461   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1462   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1463   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1464   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1465   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1466   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1467   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1468   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1469   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1470   case PPCISD::ST_VSR_SCAL_INT:
1471                                 return "PPCISD::ST_VSR_SCAL_INT";
1472   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1473   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1474   case PPCISD::BDZ:             return "PPCISD::BDZ";
1475   case PPCISD::MFFS:            return "PPCISD::MFFS";
1476   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1477   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1478   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1479   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1480   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1481   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1482   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1483   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1484   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1485   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1486   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1487   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1488   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1489   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1490   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1491   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1492   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1493   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1494   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1495   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1496   case PPCISD::SC:              return "PPCISD::SC";
1497   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1498   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1499   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1500   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1501   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1502   case PPCISD::VABSD:           return "PPCISD::VABSD";
1503   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1504   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1505   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1506   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1507   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1508   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1509   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1510   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1511     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1512   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1513   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1514   case PPCISD::STRICT_FCTIDZ:
1515     return "PPCISD::STRICT_FCTIDZ";
1516   case PPCISD::STRICT_FCTIWZ:
1517     return "PPCISD::STRICT_FCTIWZ";
1518   case PPCISD::STRICT_FCTIDUZ:
1519     return "PPCISD::STRICT_FCTIDUZ";
1520   case PPCISD::STRICT_FCTIWUZ:
1521     return "PPCISD::STRICT_FCTIWUZ";
1522   case PPCISD::STRICT_FCFID:
1523     return "PPCISD::STRICT_FCFID";
1524   case PPCISD::STRICT_FCFIDU:
1525     return "PPCISD::STRICT_FCFIDU";
1526   case PPCISD::STRICT_FCFIDS:
1527     return "PPCISD::STRICT_FCFIDS";
1528   case PPCISD::STRICT_FCFIDUS:
1529     return "PPCISD::STRICT_FCFIDUS";
1530   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1531   }
1532   return nullptr;
1533 }
1534 
1535 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1536                                           EVT VT) const {
1537   if (!VT.isVector())
1538     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1539 
1540   return VT.changeVectorElementTypeToInteger();
1541 }
1542 
1543 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1544   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1545   return true;
1546 }
1547 
1548 //===----------------------------------------------------------------------===//
1549 // Node matching predicates, for use by the tblgen matching code.
1550 //===----------------------------------------------------------------------===//
1551 
1552 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1553 static bool isFloatingPointZero(SDValue Op) {
1554   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1555     return CFP->getValueAPF().isZero();
1556   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1557     // Maybe this has already been legalized into the constant pool?
1558     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1559       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1560         return CFP->getValueAPF().isZero();
1561   }
1562   return false;
1563 }
1564 
1565 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1566 /// true if Op is undef or if it matches the specified value.
1567 static bool isConstantOrUndef(int Op, int Val) {
1568   return Op < 0 || Op == Val;
1569 }
1570 
1571 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1572 /// VPKUHUM instruction.
1573 /// The ShuffleKind distinguishes between big-endian operations with
1574 /// two different inputs (0), either-endian operations with two identical
1575 /// inputs (1), and little-endian operations with two different inputs (2).
1576 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1577 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1578                                SelectionDAG &DAG) {
1579   bool IsLE = DAG.getDataLayout().isLittleEndian();
1580   if (ShuffleKind == 0) {
1581     if (IsLE)
1582       return false;
1583     for (unsigned i = 0; i != 16; ++i)
1584       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1585         return false;
1586   } else if (ShuffleKind == 2) {
1587     if (!IsLE)
1588       return false;
1589     for (unsigned i = 0; i != 16; ++i)
1590       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1591         return false;
1592   } else if (ShuffleKind == 1) {
1593     unsigned j = IsLE ? 0 : 1;
1594     for (unsigned i = 0; i != 8; ++i)
1595       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1596           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1597         return false;
1598   }
1599   return true;
1600 }
1601 
1602 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1603 /// VPKUWUM instruction.
1604 /// The ShuffleKind distinguishes between big-endian operations with
1605 /// two different inputs (0), either-endian operations with two identical
1606 /// inputs (1), and little-endian operations with two different inputs (2).
1607 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1608 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1609                                SelectionDAG &DAG) {
1610   bool IsLE = DAG.getDataLayout().isLittleEndian();
1611   if (ShuffleKind == 0) {
1612     if (IsLE)
1613       return false;
1614     for (unsigned i = 0; i != 16; i += 2)
1615       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1616           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1617         return false;
1618   } else if (ShuffleKind == 2) {
1619     if (!IsLE)
1620       return false;
1621     for (unsigned i = 0; i != 16; i += 2)
1622       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1623           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1624         return false;
1625   } else if (ShuffleKind == 1) {
1626     unsigned j = IsLE ? 0 : 2;
1627     for (unsigned i = 0; i != 8; i += 2)
1628       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1629           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1630           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1631           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1632         return false;
1633   }
1634   return true;
1635 }
1636 
1637 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1638 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1639 /// current subtarget.
1640 ///
1641 /// The ShuffleKind distinguishes between big-endian operations with
1642 /// two different inputs (0), either-endian operations with two identical
1643 /// inputs (1), and little-endian operations with two different inputs (2).
1644 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1645 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1646                                SelectionDAG &DAG) {
1647   const PPCSubtarget& Subtarget =
1648       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1649   if (!Subtarget.hasP8Vector())
1650     return false;
1651 
1652   bool IsLE = DAG.getDataLayout().isLittleEndian();
1653   if (ShuffleKind == 0) {
1654     if (IsLE)
1655       return false;
1656     for (unsigned i = 0; i != 16; i += 4)
1657       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1658           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1659           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1660           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1661         return false;
1662   } else if (ShuffleKind == 2) {
1663     if (!IsLE)
1664       return false;
1665     for (unsigned i = 0; i != 16; i += 4)
1666       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1667           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1668           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1669           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1670         return false;
1671   } else if (ShuffleKind == 1) {
1672     unsigned j = IsLE ? 0 : 4;
1673     for (unsigned i = 0; i != 8; i += 4)
1674       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1675           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1676           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1677           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1678           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1679           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1680           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1681           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1682         return false;
1683   }
1684   return true;
1685 }
1686 
1687 /// isVMerge - Common function, used to match vmrg* shuffles.
1688 ///
1689 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1690                      unsigned LHSStart, unsigned RHSStart) {
1691   if (N->getValueType(0) != MVT::v16i8)
1692     return false;
1693   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1694          "Unsupported merge size!");
1695 
1696   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1697     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1698       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1699                              LHSStart+j+i*UnitSize) ||
1700           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1701                              RHSStart+j+i*UnitSize))
1702         return false;
1703     }
1704   return true;
1705 }
1706 
1707 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1708 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1709 /// The ShuffleKind distinguishes between big-endian merges with two
1710 /// different inputs (0), either-endian merges with two identical inputs (1),
1711 /// and little-endian merges with two different inputs (2).  For the latter,
1712 /// the input operands are swapped (see PPCInstrAltivec.td).
1713 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1714                              unsigned ShuffleKind, SelectionDAG &DAG) {
1715   if (DAG.getDataLayout().isLittleEndian()) {
1716     if (ShuffleKind == 1) // unary
1717       return isVMerge(N, UnitSize, 0, 0);
1718     else if (ShuffleKind == 2) // swapped
1719       return isVMerge(N, UnitSize, 0, 16);
1720     else
1721       return false;
1722   } else {
1723     if (ShuffleKind == 1) // unary
1724       return isVMerge(N, UnitSize, 8, 8);
1725     else if (ShuffleKind == 0) // normal
1726       return isVMerge(N, UnitSize, 8, 24);
1727     else
1728       return false;
1729   }
1730 }
1731 
1732 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1733 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1734 /// The ShuffleKind distinguishes between big-endian merges with two
1735 /// different inputs (0), either-endian merges with two identical inputs (1),
1736 /// and little-endian merges with two different inputs (2).  For the latter,
1737 /// the input operands are swapped (see PPCInstrAltivec.td).
1738 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1739                              unsigned ShuffleKind, SelectionDAG &DAG) {
1740   if (DAG.getDataLayout().isLittleEndian()) {
1741     if (ShuffleKind == 1) // unary
1742       return isVMerge(N, UnitSize, 8, 8);
1743     else if (ShuffleKind == 2) // swapped
1744       return isVMerge(N, UnitSize, 8, 24);
1745     else
1746       return false;
1747   } else {
1748     if (ShuffleKind == 1) // unary
1749       return isVMerge(N, UnitSize, 0, 0);
1750     else if (ShuffleKind == 0) // normal
1751       return isVMerge(N, UnitSize, 0, 16);
1752     else
1753       return false;
1754   }
1755 }
1756 
1757 /**
1758  * Common function used to match vmrgew and vmrgow shuffles
1759  *
1760  * The indexOffset determines whether to look for even or odd words in
1761  * the shuffle mask. This is based on the of the endianness of the target
1762  * machine.
1763  *   - Little Endian:
1764  *     - Use offset of 0 to check for odd elements
1765  *     - Use offset of 4 to check for even elements
1766  *   - Big Endian:
1767  *     - Use offset of 0 to check for even elements
1768  *     - Use offset of 4 to check for odd elements
1769  * A detailed description of the vector element ordering for little endian and
1770  * big endian can be found at
1771  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1772  * Targeting your applications - what little endian and big endian IBM XL C/C++
1773  * compiler differences mean to you
1774  *
1775  * The mask to the shuffle vector instruction specifies the indices of the
1776  * elements from the two input vectors to place in the result. The elements are
1777  * numbered in array-access order, starting with the first vector. These vectors
1778  * are always of type v16i8, thus each vector will contain 16 elements of size
1779  * 8. More info on the shuffle vector can be found in the
1780  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1781  * Language Reference.
1782  *
1783  * The RHSStartValue indicates whether the same input vectors are used (unary)
1784  * or two different input vectors are used, based on the following:
1785  *   - If the instruction uses the same vector for both inputs, the range of the
1786  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1787  *     be 0.
1788  *   - If the instruction has two different vectors then the range of the
1789  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1790  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1791  *     to 31 specify elements in the second vector).
1792  *
1793  * \param[in] N The shuffle vector SD Node to analyze
1794  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1795  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1796  * vector to the shuffle_vector instruction
1797  * \return true iff this shuffle vector represents an even or odd word merge
1798  */
1799 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1800                      unsigned RHSStartValue) {
1801   if (N->getValueType(0) != MVT::v16i8)
1802     return false;
1803 
1804   for (unsigned i = 0; i < 2; ++i)
1805     for (unsigned j = 0; j < 4; ++j)
1806       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1807                              i*RHSStartValue+j+IndexOffset) ||
1808           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1809                              i*RHSStartValue+j+IndexOffset+8))
1810         return false;
1811   return true;
1812 }
1813 
1814 /**
1815  * Determine if the specified shuffle mask is suitable for the vmrgew or
1816  * vmrgow instructions.
1817  *
1818  * \param[in] N The shuffle vector SD Node to analyze
1819  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1820  * \param[in] ShuffleKind Identify the type of merge:
1821  *   - 0 = big-endian merge with two different inputs;
1822  *   - 1 = either-endian merge with two identical inputs;
1823  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1824  *     little-endian merges).
1825  * \param[in] DAG The current SelectionDAG
1826  * \return true iff this shuffle mask
1827  */
1828 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1829                               unsigned ShuffleKind, SelectionDAG &DAG) {
1830   if (DAG.getDataLayout().isLittleEndian()) {
1831     unsigned indexOffset = CheckEven ? 4 : 0;
1832     if (ShuffleKind == 1) // Unary
1833       return isVMerge(N, indexOffset, 0);
1834     else if (ShuffleKind == 2) // swapped
1835       return isVMerge(N, indexOffset, 16);
1836     else
1837       return false;
1838   }
1839   else {
1840     unsigned indexOffset = CheckEven ? 0 : 4;
1841     if (ShuffleKind == 1) // Unary
1842       return isVMerge(N, indexOffset, 0);
1843     else if (ShuffleKind == 0) // Normal
1844       return isVMerge(N, indexOffset, 16);
1845     else
1846       return false;
1847   }
1848   return false;
1849 }
1850 
1851 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1852 /// amount, otherwise return -1.
1853 /// The ShuffleKind distinguishes between big-endian operations with two
1854 /// different inputs (0), either-endian operations with two identical inputs
1855 /// (1), and little-endian operations with two different inputs (2).  For the
1856 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1857 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1858                              SelectionDAG &DAG) {
1859   if (N->getValueType(0) != MVT::v16i8)
1860     return -1;
1861 
1862   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1863 
1864   // Find the first non-undef value in the shuffle mask.
1865   unsigned i;
1866   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1867     /*search*/;
1868 
1869   if (i == 16) return -1;  // all undef.
1870 
1871   // Otherwise, check to see if the rest of the elements are consecutively
1872   // numbered from this value.
1873   unsigned ShiftAmt = SVOp->getMaskElt(i);
1874   if (ShiftAmt < i) return -1;
1875 
1876   ShiftAmt -= i;
1877   bool isLE = DAG.getDataLayout().isLittleEndian();
1878 
1879   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1880     // Check the rest of the elements to see if they are consecutive.
1881     for (++i; i != 16; ++i)
1882       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1883         return -1;
1884   } else if (ShuffleKind == 1) {
1885     // Check the rest of the elements to see if they are consecutive.
1886     for (++i; i != 16; ++i)
1887       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1888         return -1;
1889   } else
1890     return -1;
1891 
1892   if (isLE)
1893     ShiftAmt = 16 - ShiftAmt;
1894 
1895   return ShiftAmt;
1896 }
1897 
1898 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1899 /// specifies a splat of a single element that is suitable for input to
1900 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1901 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1902   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1903          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1904 
1905   // The consecutive indices need to specify an element, not part of two
1906   // different elements.  So abandon ship early if this isn't the case.
1907   if (N->getMaskElt(0) % EltSize != 0)
1908     return false;
1909 
1910   // This is a splat operation if each element of the permute is the same, and
1911   // if the value doesn't reference the second vector.
1912   unsigned ElementBase = N->getMaskElt(0);
1913 
1914   // FIXME: Handle UNDEF elements too!
1915   if (ElementBase >= 16)
1916     return false;
1917 
1918   // Check that the indices are consecutive, in the case of a multi-byte element
1919   // splatted with a v16i8 mask.
1920   for (unsigned i = 1; i != EltSize; ++i)
1921     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1922       return false;
1923 
1924   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1925     if (N->getMaskElt(i) < 0) continue;
1926     for (unsigned j = 0; j != EltSize; ++j)
1927       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1928         return false;
1929   }
1930   return true;
1931 }
1932 
1933 /// Check that the mask is shuffling N byte elements. Within each N byte
1934 /// element of the mask, the indices could be either in increasing or
1935 /// decreasing order as long as they are consecutive.
1936 /// \param[in] N the shuffle vector SD Node to analyze
1937 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1938 /// Word/DoubleWord/QuadWord).
1939 /// \param[in] StepLen the delta indices number among the N byte element, if
1940 /// the mask is in increasing/decreasing order then it is 1/-1.
1941 /// \return true iff the mask is shuffling N byte elements.
1942 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1943                                    int StepLen) {
1944   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1945          "Unexpected element width.");
1946   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1947 
1948   unsigned NumOfElem = 16 / Width;
1949   unsigned MaskVal[16]; //  Width is never greater than 16
1950   for (unsigned i = 0; i < NumOfElem; ++i) {
1951     MaskVal[0] = N->getMaskElt(i * Width);
1952     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1953       return false;
1954     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1955       return false;
1956     }
1957 
1958     for (unsigned int j = 1; j < Width; ++j) {
1959       MaskVal[j] = N->getMaskElt(i * Width + j);
1960       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1961         return false;
1962       }
1963     }
1964   }
1965 
1966   return true;
1967 }
1968 
1969 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1970                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1971   if (!isNByteElemShuffleMask(N, 4, 1))
1972     return false;
1973 
1974   // Now we look at mask elements 0,4,8,12
1975   unsigned M0 = N->getMaskElt(0) / 4;
1976   unsigned M1 = N->getMaskElt(4) / 4;
1977   unsigned M2 = N->getMaskElt(8) / 4;
1978   unsigned M3 = N->getMaskElt(12) / 4;
1979   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1980   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1981 
1982   // Below, let H and L be arbitrary elements of the shuffle mask
1983   // where H is in the range [4,7] and L is in the range [0,3].
1984   // H, 1, 2, 3 or L, 5, 6, 7
1985   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1986       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1987     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1988     InsertAtByte = IsLE ? 12 : 0;
1989     Swap = M0 < 4;
1990     return true;
1991   }
1992   // 0, H, 2, 3 or 4, L, 6, 7
1993   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1994       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1995     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1996     InsertAtByte = IsLE ? 8 : 4;
1997     Swap = M1 < 4;
1998     return true;
1999   }
2000   // 0, 1, H, 3 or 4, 5, L, 7
2001   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2002       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2003     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2004     InsertAtByte = IsLE ? 4 : 8;
2005     Swap = M2 < 4;
2006     return true;
2007   }
2008   // 0, 1, 2, H or 4, 5, 6, L
2009   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2010       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2011     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2012     InsertAtByte = IsLE ? 0 : 12;
2013     Swap = M3 < 4;
2014     return true;
2015   }
2016 
2017   // If both vector operands for the shuffle are the same vector, the mask will
2018   // contain only elements from the first one and the second one will be undef.
2019   if (N->getOperand(1).isUndef()) {
2020     ShiftElts = 0;
2021     Swap = true;
2022     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2023     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2024       InsertAtByte = IsLE ? 12 : 0;
2025       return true;
2026     }
2027     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2028       InsertAtByte = IsLE ? 8 : 4;
2029       return true;
2030     }
2031     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2032       InsertAtByte = IsLE ? 4 : 8;
2033       return true;
2034     }
2035     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2036       InsertAtByte = IsLE ? 0 : 12;
2037       return true;
2038     }
2039   }
2040 
2041   return false;
2042 }
2043 
2044 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2045                                bool &Swap, bool IsLE) {
2046   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2047   // Ensure each byte index of the word is consecutive.
2048   if (!isNByteElemShuffleMask(N, 4, 1))
2049     return false;
2050 
2051   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2052   unsigned M0 = N->getMaskElt(0) / 4;
2053   unsigned M1 = N->getMaskElt(4) / 4;
2054   unsigned M2 = N->getMaskElt(8) / 4;
2055   unsigned M3 = N->getMaskElt(12) / 4;
2056 
2057   // If both vector operands for the shuffle are the same vector, the mask will
2058   // contain only elements from the first one and the second one will be undef.
2059   if (N->getOperand(1).isUndef()) {
2060     assert(M0 < 4 && "Indexing into an undef vector?");
2061     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2062       return false;
2063 
2064     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2065     Swap = false;
2066     return true;
2067   }
2068 
2069   // Ensure each word index of the ShuffleVector Mask is consecutive.
2070   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2071     return false;
2072 
2073   if (IsLE) {
2074     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2075       // Input vectors don't need to be swapped if the leading element
2076       // of the result is one of the 3 left elements of the second vector
2077       // (or if there is no shift to be done at all).
2078       Swap = false;
2079       ShiftElts = (8 - M0) % 8;
2080     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2081       // Input vectors need to be swapped if the leading element
2082       // of the result is one of the 3 left elements of the first vector
2083       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2084       Swap = true;
2085       ShiftElts = (4 - M0) % 4;
2086     }
2087 
2088     return true;
2089   } else {                                          // BE
2090     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2091       // Input vectors don't need to be swapped if the leading element
2092       // of the result is one of the 4 elements of the first vector.
2093       Swap = false;
2094       ShiftElts = M0;
2095     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2096       // Input vectors need to be swapped if the leading element
2097       // of the result is one of the 4 elements of the right vector.
2098       Swap = true;
2099       ShiftElts = M0 - 4;
2100     }
2101 
2102     return true;
2103   }
2104 }
2105 
2106 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2107   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2108 
2109   if (!isNByteElemShuffleMask(N, Width, -1))
2110     return false;
2111 
2112   for (int i = 0; i < 16; i += Width)
2113     if (N->getMaskElt(i) != i + Width - 1)
2114       return false;
2115 
2116   return true;
2117 }
2118 
2119 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2120   return isXXBRShuffleMaskHelper(N, 2);
2121 }
2122 
2123 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2124   return isXXBRShuffleMaskHelper(N, 4);
2125 }
2126 
2127 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2128   return isXXBRShuffleMaskHelper(N, 8);
2129 }
2130 
2131 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2132   return isXXBRShuffleMaskHelper(N, 16);
2133 }
2134 
2135 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2136 /// if the inputs to the instruction should be swapped and set \p DM to the
2137 /// value for the immediate.
2138 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2139 /// AND element 0 of the result comes from the first input (LE) or second input
2140 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2141 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2142 /// mask.
2143 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2144                                bool &Swap, bool IsLE) {
2145   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2146 
2147   // Ensure each byte index of the double word is consecutive.
2148   if (!isNByteElemShuffleMask(N, 8, 1))
2149     return false;
2150 
2151   unsigned M0 = N->getMaskElt(0) / 8;
2152   unsigned M1 = N->getMaskElt(8) / 8;
2153   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2154 
2155   // If both vector operands for the shuffle are the same vector, the mask will
2156   // contain only elements from the first one and the second one will be undef.
2157   if (N->getOperand(1).isUndef()) {
2158     if ((M0 | M1) < 2) {
2159       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2160       Swap = false;
2161       return true;
2162     } else
2163       return false;
2164   }
2165 
2166   if (IsLE) {
2167     if (M0 > 1 && M1 < 2) {
2168       Swap = false;
2169     } else if (M0 < 2 && M1 > 1) {
2170       M0 = (M0 + 2) % 4;
2171       M1 = (M1 + 2) % 4;
2172       Swap = true;
2173     } else
2174       return false;
2175 
2176     // Note: if control flow comes here that means Swap is already set above
2177     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2178     return true;
2179   } else { // BE
2180     if (M0 < 2 && M1 > 1) {
2181       Swap = false;
2182     } else if (M0 > 1 && M1 < 2) {
2183       M0 = (M0 + 2) % 4;
2184       M1 = (M1 + 2) % 4;
2185       Swap = true;
2186     } else
2187       return false;
2188 
2189     // Note: if control flow comes here that means Swap is already set above
2190     DM = (M0 << 1) + (M1 & 1);
2191     return true;
2192   }
2193 }
2194 
2195 
2196 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2197 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2198 /// elements are counted from the left of the vector register).
2199 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2200                                          SelectionDAG &DAG) {
2201   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2202   assert(isSplatShuffleMask(SVOp, EltSize));
2203   if (DAG.getDataLayout().isLittleEndian())
2204     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2205   else
2206     return SVOp->getMaskElt(0) / EltSize;
2207 }
2208 
2209 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2210 /// by using a vspltis[bhw] instruction of the specified element size, return
2211 /// the constant being splatted.  The ByteSize field indicates the number of
2212 /// bytes of each element [124] -> [bhw].
2213 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2214   SDValue OpVal(nullptr, 0);
2215 
2216   // If ByteSize of the splat is bigger than the element size of the
2217   // build_vector, then we have a case where we are checking for a splat where
2218   // multiple elements of the buildvector are folded together into a single
2219   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2220   unsigned EltSize = 16/N->getNumOperands();
2221   if (EltSize < ByteSize) {
2222     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2223     SDValue UniquedVals[4];
2224     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2225 
2226     // See if all of the elements in the buildvector agree across.
2227     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2228       if (N->getOperand(i).isUndef()) continue;
2229       // If the element isn't a constant, bail fully out.
2230       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2231 
2232       if (!UniquedVals[i&(Multiple-1)].getNode())
2233         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2234       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2235         return SDValue();  // no match.
2236     }
2237 
2238     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2239     // either constant or undef values that are identical for each chunk.  See
2240     // if these chunks can form into a larger vspltis*.
2241 
2242     // Check to see if all of the leading entries are either 0 or -1.  If
2243     // neither, then this won't fit into the immediate field.
2244     bool LeadingZero = true;
2245     bool LeadingOnes = true;
2246     for (unsigned i = 0; i != Multiple-1; ++i) {
2247       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2248 
2249       LeadingZero &= isNullConstant(UniquedVals[i]);
2250       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2251     }
2252     // Finally, check the least significant entry.
2253     if (LeadingZero) {
2254       if (!UniquedVals[Multiple-1].getNode())
2255         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2256       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2257       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2258         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2259     }
2260     if (LeadingOnes) {
2261       if (!UniquedVals[Multiple-1].getNode())
2262         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2263       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2264       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2265         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2266     }
2267 
2268     return SDValue();
2269   }
2270 
2271   // Check to see if this buildvec has a single non-undef value in its elements.
2272   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2273     if (N->getOperand(i).isUndef()) continue;
2274     if (!OpVal.getNode())
2275       OpVal = N->getOperand(i);
2276     else if (OpVal != N->getOperand(i))
2277       return SDValue();
2278   }
2279 
2280   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2281 
2282   unsigned ValSizeInBytes = EltSize;
2283   uint64_t Value = 0;
2284   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2285     Value = CN->getZExtValue();
2286   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2287     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2288     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2289   }
2290 
2291   // If the splat value is larger than the element value, then we can never do
2292   // this splat.  The only case that we could fit the replicated bits into our
2293   // immediate field for would be zero, and we prefer to use vxor for it.
2294   if (ValSizeInBytes < ByteSize) return SDValue();
2295 
2296   // If the element value is larger than the splat value, check if it consists
2297   // of a repeated bit pattern of size ByteSize.
2298   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2299     return SDValue();
2300 
2301   // Properly sign extend the value.
2302   int MaskVal = SignExtend32(Value, ByteSize * 8);
2303 
2304   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2305   if (MaskVal == 0) return SDValue();
2306 
2307   // Finally, if this value fits in a 5 bit sext field, return it
2308   if (SignExtend32<5>(MaskVal) == MaskVal)
2309     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2310   return SDValue();
2311 }
2312 
2313 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2314 /// amount, otherwise return -1.
2315 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2316   EVT VT = N->getValueType(0);
2317   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2318     return -1;
2319 
2320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2321 
2322   // Find the first non-undef value in the shuffle mask.
2323   unsigned i;
2324   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2325     /*search*/;
2326 
2327   if (i == 4) return -1;  // all undef.
2328 
2329   // Otherwise, check to see if the rest of the elements are consecutively
2330   // numbered from this value.
2331   unsigned ShiftAmt = SVOp->getMaskElt(i);
2332   if (ShiftAmt < i) return -1;
2333   ShiftAmt -= i;
2334 
2335   // Check the rest of the elements to see if they are consecutive.
2336   for (++i; i != 4; ++i)
2337     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2338       return -1;
2339 
2340   return ShiftAmt;
2341 }
2342 
2343 //===----------------------------------------------------------------------===//
2344 //  Addressing Mode Selection
2345 //===----------------------------------------------------------------------===//
2346 
2347 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2348 /// or 64-bit immediate, and if the value can be accurately represented as a
2349 /// sign extension from a 16-bit value.  If so, this returns true and the
2350 /// immediate.
2351 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2352   if (!isa<ConstantSDNode>(N))
2353     return false;
2354 
2355   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2356   if (N->getValueType(0) == MVT::i32)
2357     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2358   else
2359     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2360 }
2361 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2362   return isIntS16Immediate(Op.getNode(), Imm);
2363 }
2364 
2365 
2366 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2367 /// be represented as an indexed [r+r] operation.
2368 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2369                                                SDValue &Index,
2370                                                SelectionDAG &DAG) const {
2371   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2372       UI != E; ++UI) {
2373     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2374       if (Memop->getMemoryVT() == MVT::f64) {
2375           Base = N.getOperand(0);
2376           Index = N.getOperand(1);
2377           return true;
2378       }
2379     }
2380   }
2381   return false;
2382 }
2383 
2384 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2385 /// can be represented as an indexed [r+r] operation.  Returns false if it
2386 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2387 /// non-zero and N can be represented by a base register plus a signed 16-bit
2388 /// displacement, make a more precise judgement by checking (displacement % \p
2389 /// EncodingAlignment).
2390 bool PPCTargetLowering::SelectAddressRegReg(
2391     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2392     MaybeAlign EncodingAlignment) const {
2393   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2394   // a [pc+imm].
2395   if (SelectAddressPCRel(N, Base))
2396     return false;
2397 
2398   int16_t Imm = 0;
2399   if (N.getOpcode() == ISD::ADD) {
2400     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2401     // SPE load/store can only handle 8-bit offsets.
2402     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2403         return true;
2404     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2405         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2406       return false; // r+i
2407     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2408       return false;    // r+i
2409 
2410     Base = N.getOperand(0);
2411     Index = N.getOperand(1);
2412     return true;
2413   } else if (N.getOpcode() == ISD::OR) {
2414     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2415         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2416       return false; // r+i can fold it if we can.
2417 
2418     // If this is an or of disjoint bitfields, we can codegen this as an add
2419     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2420     // disjoint.
2421     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2422 
2423     if (LHSKnown.Zero.getBoolValue()) {
2424       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2425       // If all of the bits are known zero on the LHS or RHS, the add won't
2426       // carry.
2427       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2428         Base = N.getOperand(0);
2429         Index = N.getOperand(1);
2430         return true;
2431       }
2432     }
2433   }
2434 
2435   return false;
2436 }
2437 
2438 // If we happen to be doing an i64 load or store into a stack slot that has
2439 // less than a 4-byte alignment, then the frame-index elimination may need to
2440 // use an indexed load or store instruction (because the offset may not be a
2441 // multiple of 4). The extra register needed to hold the offset comes from the
2442 // register scavenger, and it is possible that the scavenger will need to use
2443 // an emergency spill slot. As a result, we need to make sure that a spill slot
2444 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2445 // stack slot.
2446 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2447   // FIXME: This does not handle the LWA case.
2448   if (VT != MVT::i64)
2449     return;
2450 
2451   // NOTE: We'll exclude negative FIs here, which come from argument
2452   // lowering, because there are no known test cases triggering this problem
2453   // using packed structures (or similar). We can remove this exclusion if
2454   // we find such a test case. The reason why this is so test-case driven is
2455   // because this entire 'fixup' is only to prevent crashes (from the
2456   // register scavenger) on not-really-valid inputs. For example, if we have:
2457   //   %a = alloca i1
2458   //   %b = bitcast i1* %a to i64*
2459   //   store i64* a, i64 b
2460   // then the store should really be marked as 'align 1', but is not. If it
2461   // were marked as 'align 1' then the indexed form would have been
2462   // instruction-selected initially, and the problem this 'fixup' is preventing
2463   // won't happen regardless.
2464   if (FrameIdx < 0)
2465     return;
2466 
2467   MachineFunction &MF = DAG.getMachineFunction();
2468   MachineFrameInfo &MFI = MF.getFrameInfo();
2469 
2470   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2471     return;
2472 
2473   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2474   FuncInfo->setHasNonRISpills();
2475 }
2476 
2477 /// Returns true if the address N can be represented by a base register plus
2478 /// a signed 16-bit displacement [r+imm], and if it is not better
2479 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2480 /// displacements that are multiples of that value.
2481 bool PPCTargetLowering::SelectAddressRegImm(
2482     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2483     MaybeAlign EncodingAlignment) const {
2484   // FIXME dl should come from parent load or store, not from address
2485   SDLoc dl(N);
2486 
2487   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2488   // a [pc+imm].
2489   if (SelectAddressPCRel(N, Base))
2490     return false;
2491 
2492   // If this can be more profitably realized as r+r, fail.
2493   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2494     return false;
2495 
2496   if (N.getOpcode() == ISD::ADD) {
2497     int16_t imm = 0;
2498     if (isIntS16Immediate(N.getOperand(1), imm) &&
2499         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2500       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2501       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2502         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2503         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2504       } else {
2505         Base = N.getOperand(0);
2506       }
2507       return true; // [r+i]
2508     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2509       // Match LOAD (ADD (X, Lo(G))).
2510       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2511              && "Cannot handle constant offsets yet!");
2512       Disp = N.getOperand(1).getOperand(0);  // The global address.
2513       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2514              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2515              Disp.getOpcode() == ISD::TargetConstantPool ||
2516              Disp.getOpcode() == ISD::TargetJumpTable);
2517       Base = N.getOperand(0);
2518       return true;  // [&g+r]
2519     }
2520   } else if (N.getOpcode() == ISD::OR) {
2521     int16_t imm = 0;
2522     if (isIntS16Immediate(N.getOperand(1), imm) &&
2523         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2524       // If this is an or of disjoint bitfields, we can codegen this as an add
2525       // (for better address arithmetic) if the LHS and RHS of the OR are
2526       // provably disjoint.
2527       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2528 
2529       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2530         // If all of the bits are known zero on the LHS or RHS, the add won't
2531         // carry.
2532         if (FrameIndexSDNode *FI =
2533               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2534           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2535           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2536         } else {
2537           Base = N.getOperand(0);
2538         }
2539         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2540         return true;
2541       }
2542     }
2543   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2544     // Loading from a constant address.
2545 
2546     // If this address fits entirely in a 16-bit sext immediate field, codegen
2547     // this as "d, 0"
2548     int16_t Imm;
2549     if (isIntS16Immediate(CN, Imm) &&
2550         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2551       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2552       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2553                              CN->getValueType(0));
2554       return true;
2555     }
2556 
2557     // Handle 32-bit sext immediates with LIS + addr mode.
2558     if ((CN->getValueType(0) == MVT::i32 ||
2559          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2560         (!EncodingAlignment ||
2561          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2562       int Addr = (int)CN->getZExtValue();
2563 
2564       // Otherwise, break this down into an LIS + disp.
2565       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2566 
2567       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2568                                    MVT::i32);
2569       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2570       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2571       return true;
2572     }
2573   }
2574 
2575   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2576   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2577     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2578     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2579   } else
2580     Base = N;
2581   return true;      // [r+0]
2582 }
2583 
2584 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2585 /// represented as an indexed [r+r] operation.
2586 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2587                                                 SDValue &Index,
2588                                                 SelectionDAG &DAG) const {
2589   // Check to see if we can easily represent this as an [r+r] address.  This
2590   // will fail if it thinks that the address is more profitably represented as
2591   // reg+imm, e.g. where imm = 0.
2592   if (SelectAddressRegReg(N, Base, Index, DAG))
2593     return true;
2594 
2595   // If the address is the result of an add, we will utilize the fact that the
2596   // address calculation includes an implicit add.  However, we can reduce
2597   // register pressure if we do not materialize a constant just for use as the
2598   // index register.  We only get rid of the add if it is not an add of a
2599   // value and a 16-bit signed constant and both have a single use.
2600   int16_t imm = 0;
2601   if (N.getOpcode() == ISD::ADD &&
2602       (!isIntS16Immediate(N.getOperand(1), imm) ||
2603        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2604     Base = N.getOperand(0);
2605     Index = N.getOperand(1);
2606     return true;
2607   }
2608 
2609   // Otherwise, do it the hard way, using R0 as the base register.
2610   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2611                          N.getValueType());
2612   Index = N;
2613   return true;
2614 }
2615 
2616 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2617   Ty *PCRelCand = dyn_cast<Ty>(N);
2618   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2619 }
2620 
2621 /// Returns true if this address is a PC Relative address.
2622 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2623 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2624 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2625   // This is a materialize PC Relative node. Always select this as PC Relative.
2626   Base = N;
2627   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2628     return true;
2629   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2630       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2631       isValidPCRelNode<JumpTableSDNode>(N) ||
2632       isValidPCRelNode<BlockAddressSDNode>(N))
2633     return true;
2634   return false;
2635 }
2636 
2637 /// Returns true if we should use a direct load into vector instruction
2638 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2639 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2640 
2641   // If there are any other uses other than scalar to vector, then we should
2642   // keep it as a scalar load -> direct move pattern to prevent multiple
2643   // loads.
2644   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2645   if (!LD)
2646     return false;
2647 
2648   EVT MemVT = LD->getMemoryVT();
2649   if (!MemVT.isSimple())
2650     return false;
2651   switch(MemVT.getSimpleVT().SimpleTy) {
2652   case MVT::i64:
2653     break;
2654   case MVT::i32:
2655     if (!ST.hasP8Vector())
2656       return false;
2657     break;
2658   case MVT::i16:
2659   case MVT::i8:
2660     if (!ST.hasP9Vector())
2661       return false;
2662     break;
2663   default:
2664     return false;
2665   }
2666 
2667   SDValue LoadedVal(N, 0);
2668   if (!LoadedVal.hasOneUse())
2669     return false;
2670 
2671   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2672        UI != UE; ++UI)
2673     if (UI.getUse().get().getResNo() == 0 &&
2674         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2675         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2676       return false;
2677 
2678   return true;
2679 }
2680 
2681 /// getPreIndexedAddressParts - returns true by value, base pointer and
2682 /// offset pointer and addressing mode by reference if the node's address
2683 /// can be legally represented as pre-indexed load / store address.
2684 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2685                                                   SDValue &Offset,
2686                                                   ISD::MemIndexedMode &AM,
2687                                                   SelectionDAG &DAG) const {
2688   if (DisablePPCPreinc) return false;
2689 
2690   bool isLoad = true;
2691   SDValue Ptr;
2692   EVT VT;
2693   unsigned Alignment;
2694   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2695     Ptr = LD->getBasePtr();
2696     VT = LD->getMemoryVT();
2697     Alignment = LD->getAlignment();
2698   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2699     Ptr = ST->getBasePtr();
2700     VT  = ST->getMemoryVT();
2701     Alignment = ST->getAlignment();
2702     isLoad = false;
2703   } else
2704     return false;
2705 
2706   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2707   // instructions because we can fold these into a more efficient instruction
2708   // instead, (such as LXSD).
2709   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2710     return false;
2711   }
2712 
2713   // PowerPC doesn't have preinc load/store instructions for vectors
2714   if (VT.isVector())
2715     return false;
2716 
2717   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2718     // Common code will reject creating a pre-inc form if the base pointer
2719     // is a frame index, or if N is a store and the base pointer is either
2720     // the same as or a predecessor of the value being stored.  Check for
2721     // those situations here, and try with swapped Base/Offset instead.
2722     bool Swap = false;
2723 
2724     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2725       Swap = true;
2726     else if (!isLoad) {
2727       SDValue Val = cast<StoreSDNode>(N)->getValue();
2728       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2729         Swap = true;
2730     }
2731 
2732     if (Swap)
2733       std::swap(Base, Offset);
2734 
2735     AM = ISD::PRE_INC;
2736     return true;
2737   }
2738 
2739   // LDU/STU can only handle immediates that are a multiple of 4.
2740   if (VT != MVT::i64) {
2741     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2742       return false;
2743   } else {
2744     // LDU/STU need an address with at least 4-byte alignment.
2745     if (Alignment < 4)
2746       return false;
2747 
2748     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2749       return false;
2750   }
2751 
2752   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2753     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2754     // sext i32 to i64 when addr mode is r+i.
2755     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2756         LD->getExtensionType() == ISD::SEXTLOAD &&
2757         isa<ConstantSDNode>(Offset))
2758       return false;
2759   }
2760 
2761   AM = ISD::PRE_INC;
2762   return true;
2763 }
2764 
2765 //===----------------------------------------------------------------------===//
2766 //  LowerOperation implementation
2767 //===----------------------------------------------------------------------===//
2768 
2769 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2770 /// and LoOpFlags to the target MO flags.
2771 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2772                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2773                                const GlobalValue *GV = nullptr) {
2774   HiOpFlags = PPCII::MO_HA;
2775   LoOpFlags = PPCII::MO_LO;
2776 
2777   // Don't use the pic base if not in PIC relocation model.
2778   if (IsPIC) {
2779     HiOpFlags |= PPCII::MO_PIC_FLAG;
2780     LoOpFlags |= PPCII::MO_PIC_FLAG;
2781   }
2782 }
2783 
2784 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2785                              SelectionDAG &DAG) {
2786   SDLoc DL(HiPart);
2787   EVT PtrVT = HiPart.getValueType();
2788   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2789 
2790   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2791   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2792 
2793   // With PIC, the first instruction is actually "GR+hi(&G)".
2794   if (isPIC)
2795     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2796                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2797 
2798   // Generate non-pic code that has direct accesses to the constant pool.
2799   // The address of the global is just (hi(&g)+lo(&g)).
2800   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2801 }
2802 
2803 static void setUsesTOCBasePtr(MachineFunction &MF) {
2804   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2805   FuncInfo->setUsesTOCBasePtr();
2806 }
2807 
2808 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2809   setUsesTOCBasePtr(DAG.getMachineFunction());
2810 }
2811 
2812 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2813                                        SDValue GA) const {
2814   const bool Is64Bit = Subtarget.isPPC64();
2815   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2816   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2817                         : Subtarget.isAIXABI()
2818                               ? DAG.getRegister(PPC::R2, VT)
2819                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2820   SDValue Ops[] = { GA, Reg };
2821   return DAG.getMemIntrinsicNode(
2822       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2823       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2824       MachineMemOperand::MOLoad);
2825 }
2826 
2827 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2828                                              SelectionDAG &DAG) const {
2829   EVT PtrVT = Op.getValueType();
2830   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2831   const Constant *C = CP->getConstVal();
2832 
2833   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2834   // The actual address of the GlobalValue is stored in the TOC.
2835   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2836     if (Subtarget.isUsingPCRelativeCalls()) {
2837       SDLoc DL(CP);
2838       EVT Ty = getPointerTy(DAG.getDataLayout());
2839       SDValue ConstPool = DAG.getTargetConstantPool(
2840           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2841       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2842     }
2843     setUsesTOCBasePtr(DAG);
2844     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2845     return getTOCEntry(DAG, SDLoc(CP), GA);
2846   }
2847 
2848   unsigned MOHiFlag, MOLoFlag;
2849   bool IsPIC = isPositionIndependent();
2850   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2851 
2852   if (IsPIC && Subtarget.isSVR4ABI()) {
2853     SDValue GA =
2854         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2855     return getTOCEntry(DAG, SDLoc(CP), GA);
2856   }
2857 
2858   SDValue CPIHi =
2859       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2860   SDValue CPILo =
2861       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2862   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2863 }
2864 
2865 // For 64-bit PowerPC, prefer the more compact relative encodings.
2866 // This trades 32 bits per jump table entry for one or two instructions
2867 // on the jump site.
2868 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2869   if (isJumpTableRelative())
2870     return MachineJumpTableInfo::EK_LabelDifference32;
2871 
2872   return TargetLowering::getJumpTableEncoding();
2873 }
2874 
2875 bool PPCTargetLowering::isJumpTableRelative() const {
2876   if (UseAbsoluteJumpTables)
2877     return false;
2878   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2879     return true;
2880   return TargetLowering::isJumpTableRelative();
2881 }
2882 
2883 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2884                                                     SelectionDAG &DAG) const {
2885   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2886     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2887 
2888   switch (getTargetMachine().getCodeModel()) {
2889   case CodeModel::Small:
2890   case CodeModel::Medium:
2891     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2892   default:
2893     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2894                        getPointerTy(DAG.getDataLayout()));
2895   }
2896 }
2897 
2898 const MCExpr *
2899 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2900                                                 unsigned JTI,
2901                                                 MCContext &Ctx) const {
2902   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2903     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2904 
2905   switch (getTargetMachine().getCodeModel()) {
2906   case CodeModel::Small:
2907   case CodeModel::Medium:
2908     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2909   default:
2910     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2911   }
2912 }
2913 
2914 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2915   EVT PtrVT = Op.getValueType();
2916   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2917 
2918   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2919   if (Subtarget.isUsingPCRelativeCalls()) {
2920     SDLoc DL(JT);
2921     EVT Ty = getPointerTy(DAG.getDataLayout());
2922     SDValue GA =
2923         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2924     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2925     return MatAddr;
2926   }
2927 
2928   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2929   // The actual address of the GlobalValue is stored in the TOC.
2930   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2931     setUsesTOCBasePtr(DAG);
2932     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2933     return getTOCEntry(DAG, SDLoc(JT), GA);
2934   }
2935 
2936   unsigned MOHiFlag, MOLoFlag;
2937   bool IsPIC = isPositionIndependent();
2938   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2939 
2940   if (IsPIC && Subtarget.isSVR4ABI()) {
2941     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2942                                         PPCII::MO_PIC_FLAG);
2943     return getTOCEntry(DAG, SDLoc(GA), GA);
2944   }
2945 
2946   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2947   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2948   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2949 }
2950 
2951 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2952                                              SelectionDAG &DAG) const {
2953   EVT PtrVT = Op.getValueType();
2954   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2955   const BlockAddress *BA = BASDN->getBlockAddress();
2956 
2957   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2958   if (Subtarget.isUsingPCRelativeCalls()) {
2959     SDLoc DL(BASDN);
2960     EVT Ty = getPointerTy(DAG.getDataLayout());
2961     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2962                                            PPCII::MO_PCREL_FLAG);
2963     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2964     return MatAddr;
2965   }
2966 
2967   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2968   // The actual BlockAddress is stored in the TOC.
2969   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2970     setUsesTOCBasePtr(DAG);
2971     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2972     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2973   }
2974 
2975   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2976   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2977     return getTOCEntry(
2978         DAG, SDLoc(BASDN),
2979         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2980 
2981   unsigned MOHiFlag, MOLoFlag;
2982   bool IsPIC = isPositionIndependent();
2983   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2984   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2985   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2986   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2987 }
2988 
2989 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2990                                               SelectionDAG &DAG) const {
2991   // FIXME: TLS addresses currently use medium model code sequences,
2992   // which is the most useful form.  Eventually support for small and
2993   // large models could be added if users need it, at the cost of
2994   // additional complexity.
2995   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
2996     report_fatal_error("Thread local storage is not supported with pc-relative"
2997                        " addressing - please compile with -mno-pcrel");
2998   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2999   if (DAG.getTarget().useEmulatedTLS())
3000     return LowerToTLSEmulatedModel(GA, DAG);
3001 
3002   SDLoc dl(GA);
3003   const GlobalValue *GV = GA->getGlobal();
3004   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3005   bool is64bit = Subtarget.isPPC64();
3006   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3007   PICLevel::Level picLevel = M->getPICLevel();
3008 
3009   const TargetMachine &TM = getTargetMachine();
3010   TLSModel::Model Model = TM.getTLSModel(GV);
3011 
3012   if (Model == TLSModel::LocalExec) {
3013     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3014                                                PPCII::MO_TPREL_HA);
3015     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3016                                                PPCII::MO_TPREL_LO);
3017     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3018                              : DAG.getRegister(PPC::R2, MVT::i32);
3019 
3020     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3021     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3022   }
3023 
3024   if (Model == TLSModel::InitialExec) {
3025     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3026     SDValue TGA = DAG.getTargetGlobalAddress(
3027         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3028     SDValue TGATLS = DAG.getTargetGlobalAddress(
3029         GV, dl, PtrVT, 0,
3030         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3031     SDValue TPOffset;
3032     if (IsPCRel) {
3033       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3034       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3035                              MachinePointerInfo());
3036     } else {
3037       SDValue GOTPtr;
3038       if (is64bit) {
3039         setUsesTOCBasePtr(DAG);
3040         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3041         GOTPtr =
3042             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3043       } else {
3044         if (!TM.isPositionIndependent())
3045           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3046         else if (picLevel == PICLevel::SmallPIC)
3047           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3048         else
3049           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3050       }
3051       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3052     }
3053     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3054   }
3055 
3056   if (Model == TLSModel::GeneralDynamic) {
3057     if (Subtarget.isUsingPCRelativeCalls()) {
3058       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3059                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3060       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3061     }
3062 
3063     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3064     SDValue GOTPtr;
3065     if (is64bit) {
3066       setUsesTOCBasePtr(DAG);
3067       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3068       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3069                                    GOTReg, TGA);
3070     } else {
3071       if (picLevel == PICLevel::SmallPIC)
3072         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3073       else
3074         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3075     }
3076     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3077                        GOTPtr, TGA, TGA);
3078   }
3079 
3080   if (Model == TLSModel::LocalDynamic) {
3081     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3082     SDValue GOTPtr;
3083     if (is64bit) {
3084       setUsesTOCBasePtr(DAG);
3085       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3086       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3087                            GOTReg, TGA);
3088     } else {
3089       if (picLevel == PICLevel::SmallPIC)
3090         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3091       else
3092         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3093     }
3094     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3095                                   PtrVT, GOTPtr, TGA, TGA);
3096     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3097                                       PtrVT, TLSAddr, TGA);
3098     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3099   }
3100 
3101   llvm_unreachable("Unknown TLS model!");
3102 }
3103 
3104 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3105                                               SelectionDAG &DAG) const {
3106   EVT PtrVT = Op.getValueType();
3107   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3108   SDLoc DL(GSDN);
3109   const GlobalValue *GV = GSDN->getGlobal();
3110 
3111   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3112   // The actual address of the GlobalValue is stored in the TOC.
3113   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3114     if (Subtarget.isUsingPCRelativeCalls()) {
3115       EVT Ty = getPointerTy(DAG.getDataLayout());
3116       if (isAccessedAsGotIndirect(Op)) {
3117         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3118                                                 PPCII::MO_PCREL_FLAG |
3119                                                     PPCII::MO_GOT_FLAG);
3120         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3121         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3122                                    MachinePointerInfo());
3123         return Load;
3124       } else {
3125         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3126                                                 PPCII::MO_PCREL_FLAG);
3127         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3128       }
3129     }
3130     setUsesTOCBasePtr(DAG);
3131     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3132     return getTOCEntry(DAG, DL, GA);
3133   }
3134 
3135   unsigned MOHiFlag, MOLoFlag;
3136   bool IsPIC = isPositionIndependent();
3137   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3138 
3139   if (IsPIC && Subtarget.isSVR4ABI()) {
3140     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3141                                             GSDN->getOffset(),
3142                                             PPCII::MO_PIC_FLAG);
3143     return getTOCEntry(DAG, DL, GA);
3144   }
3145 
3146   SDValue GAHi =
3147     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3148   SDValue GALo =
3149     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3150 
3151   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3152 }
3153 
3154 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3155   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3156   SDLoc dl(Op);
3157 
3158   if (Op.getValueType() == MVT::v2i64) {
3159     // When the operands themselves are v2i64 values, we need to do something
3160     // special because VSX has no underlying comparison operations for these.
3161     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3162       // Equality can be handled by casting to the legal type for Altivec
3163       // comparisons, everything else needs to be expanded.
3164       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3165         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3166                  DAG.getSetCC(dl, MVT::v4i32,
3167                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3168                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3169                    CC));
3170       }
3171 
3172       return SDValue();
3173     }
3174 
3175     // We handle most of these in the usual way.
3176     return Op;
3177   }
3178 
3179   // If we're comparing for equality to zero, expose the fact that this is
3180   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3181   // fold the new nodes.
3182   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3183     return V;
3184 
3185   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3186     // Leave comparisons against 0 and -1 alone for now, since they're usually
3187     // optimized.  FIXME: revisit this when we can custom lower all setcc
3188     // optimizations.
3189     if (C->isAllOnesValue() || C->isNullValue())
3190       return SDValue();
3191   }
3192 
3193   // If we have an integer seteq/setne, turn it into a compare against zero
3194   // by xor'ing the rhs with the lhs, which is faster than setting a
3195   // condition register, reading it back out, and masking the correct bit.  The
3196   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3197   // the result to other bit-twiddling opportunities.
3198   EVT LHSVT = Op.getOperand(0).getValueType();
3199   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3200     EVT VT = Op.getValueType();
3201     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3202                                 Op.getOperand(1));
3203     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3204   }
3205   return SDValue();
3206 }
3207 
3208 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3209   SDNode *Node = Op.getNode();
3210   EVT VT = Node->getValueType(0);
3211   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3212   SDValue InChain = Node->getOperand(0);
3213   SDValue VAListPtr = Node->getOperand(1);
3214   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3215   SDLoc dl(Node);
3216 
3217   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3218 
3219   // gpr_index
3220   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3221                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3222   InChain = GprIndex.getValue(1);
3223 
3224   if (VT == MVT::i64) {
3225     // Check if GprIndex is even
3226     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3227                                  DAG.getConstant(1, dl, MVT::i32));
3228     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3229                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3230     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3231                                           DAG.getConstant(1, dl, MVT::i32));
3232     // Align GprIndex to be even if it isn't
3233     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3234                            GprIndex);
3235   }
3236 
3237   // fpr index is 1 byte after gpr
3238   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3239                                DAG.getConstant(1, dl, MVT::i32));
3240 
3241   // fpr
3242   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3243                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3244   InChain = FprIndex.getValue(1);
3245 
3246   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3247                                        DAG.getConstant(8, dl, MVT::i32));
3248 
3249   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3250                                         DAG.getConstant(4, dl, MVT::i32));
3251 
3252   // areas
3253   SDValue OverflowArea =
3254       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3255   InChain = OverflowArea.getValue(1);
3256 
3257   SDValue RegSaveArea =
3258       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3259   InChain = RegSaveArea.getValue(1);
3260 
3261   // select overflow_area if index > 8
3262   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3263                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3264 
3265   // adjustment constant gpr_index * 4/8
3266   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3267                                     VT.isInteger() ? GprIndex : FprIndex,
3268                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3269                                                     MVT::i32));
3270 
3271   // OurReg = RegSaveArea + RegConstant
3272   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3273                                RegConstant);
3274 
3275   // Floating types are 32 bytes into RegSaveArea
3276   if (VT.isFloatingPoint())
3277     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3278                          DAG.getConstant(32, dl, MVT::i32));
3279 
3280   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3281   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3282                                    VT.isInteger() ? GprIndex : FprIndex,
3283                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3284                                                    MVT::i32));
3285 
3286   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3287                               VT.isInteger() ? VAListPtr : FprPtr,
3288                               MachinePointerInfo(SV), MVT::i8);
3289 
3290   // determine if we should load from reg_save_area or overflow_area
3291   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3292 
3293   // increase overflow_area by 4/8 if gpr/fpr > 8
3294   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3295                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3296                                           dl, MVT::i32));
3297 
3298   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3299                              OverflowAreaPlusN);
3300 
3301   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3302                               MachinePointerInfo(), MVT::i32);
3303 
3304   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3305 }
3306 
3307 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3308   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3309 
3310   // We have to copy the entire va_list struct:
3311   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3312   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3313                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3314                        false, true, false, MachinePointerInfo(),
3315                        MachinePointerInfo());
3316 }
3317 
3318 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3319                                                   SelectionDAG &DAG) const {
3320   if (Subtarget.isAIXABI())
3321     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3322 
3323   return Op.getOperand(0);
3324 }
3325 
3326 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3327                                                 SelectionDAG &DAG) const {
3328   if (Subtarget.isAIXABI())
3329     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3330 
3331   SDValue Chain = Op.getOperand(0);
3332   SDValue Trmp = Op.getOperand(1); // trampoline
3333   SDValue FPtr = Op.getOperand(2); // nested function
3334   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3335   SDLoc dl(Op);
3336 
3337   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3338   bool isPPC64 = (PtrVT == MVT::i64);
3339   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3340 
3341   TargetLowering::ArgListTy Args;
3342   TargetLowering::ArgListEntry Entry;
3343 
3344   Entry.Ty = IntPtrTy;
3345   Entry.Node = Trmp; Args.push_back(Entry);
3346 
3347   // TrampSize == (isPPC64 ? 48 : 40);
3348   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3349                                isPPC64 ? MVT::i64 : MVT::i32);
3350   Args.push_back(Entry);
3351 
3352   Entry.Node = FPtr; Args.push_back(Entry);
3353   Entry.Node = Nest; Args.push_back(Entry);
3354 
3355   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3356   TargetLowering::CallLoweringInfo CLI(DAG);
3357   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3358       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3359       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3360 
3361   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3362   return CallResult.second;
3363 }
3364 
3365 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3366   MachineFunction &MF = DAG.getMachineFunction();
3367   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3368   EVT PtrVT = getPointerTy(MF.getDataLayout());
3369 
3370   SDLoc dl(Op);
3371 
3372   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3373     // vastart just stores the address of the VarArgsFrameIndex slot into the
3374     // memory location argument.
3375     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3376     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3377     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3378                         MachinePointerInfo(SV));
3379   }
3380 
3381   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3382   // We suppose the given va_list is already allocated.
3383   //
3384   // typedef struct {
3385   //  char gpr;     /* index into the array of 8 GPRs
3386   //                 * stored in the register save area
3387   //                 * gpr=0 corresponds to r3,
3388   //                 * gpr=1 to r4, etc.
3389   //                 */
3390   //  char fpr;     /* index into the array of 8 FPRs
3391   //                 * stored in the register save area
3392   //                 * fpr=0 corresponds to f1,
3393   //                 * fpr=1 to f2, etc.
3394   //                 */
3395   //  char *overflow_arg_area;
3396   //                /* location on stack that holds
3397   //                 * the next overflow argument
3398   //                 */
3399   //  char *reg_save_area;
3400   //               /* where r3:r10 and f1:f8 (if saved)
3401   //                * are stored
3402   //                */
3403   // } va_list[1];
3404 
3405   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3406   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3407   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3408                                             PtrVT);
3409   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3410                                  PtrVT);
3411 
3412   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3413   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3414 
3415   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3416   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3417 
3418   uint64_t FPROffset = 1;
3419   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3420 
3421   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3422 
3423   // Store first byte : number of int regs
3424   SDValue firstStore =
3425       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3426                         MachinePointerInfo(SV), MVT::i8);
3427   uint64_t nextOffset = FPROffset;
3428   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3429                                   ConstFPROffset);
3430 
3431   // Store second byte : number of float regs
3432   SDValue secondStore =
3433       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3434                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3435   nextOffset += StackOffset;
3436   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3437 
3438   // Store second word : arguments given on stack
3439   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3440                                     MachinePointerInfo(SV, nextOffset));
3441   nextOffset += FrameOffset;
3442   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3443 
3444   // Store third word : arguments given in registers
3445   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3446                       MachinePointerInfo(SV, nextOffset));
3447 }
3448 
3449 /// FPR - The set of FP registers that should be allocated for arguments
3450 /// on Darwin and AIX.
3451 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3452                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3453                                 PPC::F11, PPC::F12, PPC::F13};
3454 
3455 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3456 /// the stack.
3457 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3458                                        unsigned PtrByteSize) {
3459   unsigned ArgSize = ArgVT.getStoreSize();
3460   if (Flags.isByVal())
3461     ArgSize = Flags.getByValSize();
3462 
3463   // Round up to multiples of the pointer size, except for array members,
3464   // which are always packed.
3465   if (!Flags.isInConsecutiveRegs())
3466     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3467 
3468   return ArgSize;
3469 }
3470 
3471 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3472 /// on the stack.
3473 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3474                                          ISD::ArgFlagsTy Flags,
3475                                          unsigned PtrByteSize) {
3476   Align Alignment(PtrByteSize);
3477 
3478   // Altivec parameters are padded to a 16 byte boundary.
3479   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3480       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3481       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3482       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3483     Alignment = Align(16);
3484 
3485   // ByVal parameters are aligned as requested.
3486   if (Flags.isByVal()) {
3487     auto BVAlign = Flags.getNonZeroByValAlign();
3488     if (BVAlign > PtrByteSize) {
3489       if (BVAlign.value() % PtrByteSize != 0)
3490         llvm_unreachable(
3491             "ByVal alignment is not a multiple of the pointer size");
3492 
3493       Alignment = BVAlign;
3494     }
3495   }
3496 
3497   // Array members are always packed to their original alignment.
3498   if (Flags.isInConsecutiveRegs()) {
3499     // If the array member was split into multiple registers, the first
3500     // needs to be aligned to the size of the full type.  (Except for
3501     // ppcf128, which is only aligned as its f64 components.)
3502     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3503       Alignment = Align(OrigVT.getStoreSize());
3504     else
3505       Alignment = Align(ArgVT.getStoreSize());
3506   }
3507 
3508   return Alignment;
3509 }
3510 
3511 /// CalculateStackSlotUsed - Return whether this argument will use its
3512 /// stack slot (instead of being passed in registers).  ArgOffset,
3513 /// AvailableFPRs, and AvailableVRs must hold the current argument
3514 /// position, and will be updated to account for this argument.
3515 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3516                                    unsigned PtrByteSize, unsigned LinkageSize,
3517                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3518                                    unsigned &AvailableFPRs,
3519                                    unsigned &AvailableVRs) {
3520   bool UseMemory = false;
3521 
3522   // Respect alignment of argument on the stack.
3523   Align Alignment =
3524       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3525   ArgOffset = alignTo(ArgOffset, Alignment);
3526   // If there's no space left in the argument save area, we must
3527   // use memory (this check also catches zero-sized arguments).
3528   if (ArgOffset >= LinkageSize + ParamAreaSize)
3529     UseMemory = true;
3530 
3531   // Allocate argument on the stack.
3532   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3533   if (Flags.isInConsecutiveRegsLast())
3534     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3535   // If we overran the argument save area, we must use memory
3536   // (this check catches arguments passed partially in memory)
3537   if (ArgOffset > LinkageSize + ParamAreaSize)
3538     UseMemory = true;
3539 
3540   // However, if the argument is actually passed in an FPR or a VR,
3541   // we don't use memory after all.
3542   if (!Flags.isByVal()) {
3543     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3544       if (AvailableFPRs > 0) {
3545         --AvailableFPRs;
3546         return false;
3547       }
3548     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3549         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3550         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3551         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3552       if (AvailableVRs > 0) {
3553         --AvailableVRs;
3554         return false;
3555       }
3556   }
3557 
3558   return UseMemory;
3559 }
3560 
3561 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3562 /// ensure minimum alignment required for target.
3563 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3564                                      unsigned NumBytes) {
3565   return alignTo(NumBytes, Lowering->getStackAlign());
3566 }
3567 
3568 SDValue PPCTargetLowering::LowerFormalArguments(
3569     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3570     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3571     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3572   if (Subtarget.isAIXABI())
3573     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3574                                     InVals);
3575   if (Subtarget.is64BitELFABI())
3576     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3577                                        InVals);
3578   if (Subtarget.is32BitELFABI())
3579     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3580                                        InVals);
3581 
3582   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3583                                      InVals);
3584 }
3585 
3586 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3587     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3588     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3589     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3590 
3591   // 32-bit SVR4 ABI Stack Frame Layout:
3592   //              +-----------------------------------+
3593   //        +-->  |            Back chain             |
3594   //        |     +-----------------------------------+
3595   //        |     | Floating-point register save area |
3596   //        |     +-----------------------------------+
3597   //        |     |    General register save area     |
3598   //        |     +-----------------------------------+
3599   //        |     |          CR save word             |
3600   //        |     +-----------------------------------+
3601   //        |     |         VRSAVE save word          |
3602   //        |     +-----------------------------------+
3603   //        |     |         Alignment padding         |
3604   //        |     +-----------------------------------+
3605   //        |     |     Vector register save area     |
3606   //        |     +-----------------------------------+
3607   //        |     |       Local variable space        |
3608   //        |     +-----------------------------------+
3609   //        |     |        Parameter list area        |
3610   //        |     +-----------------------------------+
3611   //        |     |           LR save word            |
3612   //        |     +-----------------------------------+
3613   // SP-->  +---  |            Back chain             |
3614   //              +-----------------------------------+
3615   //
3616   // Specifications:
3617   //   System V Application Binary Interface PowerPC Processor Supplement
3618   //   AltiVec Technology Programming Interface Manual
3619 
3620   MachineFunction &MF = DAG.getMachineFunction();
3621   MachineFrameInfo &MFI = MF.getFrameInfo();
3622   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3623 
3624   EVT PtrVT = getPointerTy(MF.getDataLayout());
3625   // Potential tail calls could cause overwriting of argument stack slots.
3626   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3627                        (CallConv == CallingConv::Fast));
3628   const Align PtrAlign(4);
3629 
3630   // Assign locations to all of the incoming arguments.
3631   SmallVector<CCValAssign, 16> ArgLocs;
3632   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3633                  *DAG.getContext());
3634 
3635   // Reserve space for the linkage area on the stack.
3636   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3637   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3638   if (useSoftFloat())
3639     CCInfo.PreAnalyzeFormalArguments(Ins);
3640 
3641   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3642   CCInfo.clearWasPPCF128();
3643 
3644   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3645     CCValAssign &VA = ArgLocs[i];
3646 
3647     // Arguments stored in registers.
3648     if (VA.isRegLoc()) {
3649       const TargetRegisterClass *RC;
3650       EVT ValVT = VA.getValVT();
3651 
3652       switch (ValVT.getSimpleVT().SimpleTy) {
3653         default:
3654           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3655         case MVT::i1:
3656         case MVT::i32:
3657           RC = &PPC::GPRCRegClass;
3658           break;
3659         case MVT::f32:
3660           if (Subtarget.hasP8Vector())
3661             RC = &PPC::VSSRCRegClass;
3662           else if (Subtarget.hasSPE())
3663             RC = &PPC::GPRCRegClass;
3664           else
3665             RC = &PPC::F4RCRegClass;
3666           break;
3667         case MVT::f64:
3668           if (Subtarget.hasVSX())
3669             RC = &PPC::VSFRCRegClass;
3670           else if (Subtarget.hasSPE())
3671             // SPE passes doubles in GPR pairs.
3672             RC = &PPC::GPRCRegClass;
3673           else
3674             RC = &PPC::F8RCRegClass;
3675           break;
3676         case MVT::v16i8:
3677         case MVT::v8i16:
3678         case MVT::v4i32:
3679           RC = &PPC::VRRCRegClass;
3680           break;
3681         case MVT::v4f32:
3682           RC = &PPC::VRRCRegClass;
3683           break;
3684         case MVT::v2f64:
3685         case MVT::v2i64:
3686           RC = &PPC::VRRCRegClass;
3687           break;
3688       }
3689 
3690       SDValue ArgValue;
3691       // Transform the arguments stored in physical registers into
3692       // virtual ones.
3693       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3694         assert(i + 1 < e && "No second half of double precision argument");
3695         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3696         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3697         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3698         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3699         if (!Subtarget.isLittleEndian())
3700           std::swap (ArgValueLo, ArgValueHi);
3701         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3702                                ArgValueHi);
3703       } else {
3704         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3705         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3706                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3707         if (ValVT == MVT::i1)
3708           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3709       }
3710 
3711       InVals.push_back(ArgValue);
3712     } else {
3713       // Argument stored in memory.
3714       assert(VA.isMemLoc());
3715 
3716       // Get the extended size of the argument type in stack
3717       unsigned ArgSize = VA.getLocVT().getStoreSize();
3718       // Get the actual size of the argument type
3719       unsigned ObjSize = VA.getValVT().getStoreSize();
3720       unsigned ArgOffset = VA.getLocMemOffset();
3721       // Stack objects in PPC32 are right justified.
3722       ArgOffset += ArgSize - ObjSize;
3723       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3724 
3725       // Create load nodes to retrieve arguments from the stack.
3726       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3727       InVals.push_back(
3728           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3729     }
3730   }
3731 
3732   // Assign locations to all of the incoming aggregate by value arguments.
3733   // Aggregates passed by value are stored in the local variable space of the
3734   // caller's stack frame, right above the parameter list area.
3735   SmallVector<CCValAssign, 16> ByValArgLocs;
3736   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3737                       ByValArgLocs, *DAG.getContext());
3738 
3739   // Reserve stack space for the allocations in CCInfo.
3740   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3741 
3742   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3743 
3744   // Area that is at least reserved in the caller of this function.
3745   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3746   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3747 
3748   // Set the size that is at least reserved in caller of this function.  Tail
3749   // call optimized function's reserved stack space needs to be aligned so that
3750   // taking the difference between two stack areas will result in an aligned
3751   // stack.
3752   MinReservedArea =
3753       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3754   FuncInfo->setMinReservedArea(MinReservedArea);
3755 
3756   SmallVector<SDValue, 8> MemOps;
3757 
3758   // If the function takes variable number of arguments, make a frame index for
3759   // the start of the first vararg value... for expansion of llvm.va_start.
3760   if (isVarArg) {
3761     static const MCPhysReg GPArgRegs[] = {
3762       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3763       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3764     };
3765     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3766 
3767     static const MCPhysReg FPArgRegs[] = {
3768       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3769       PPC::F8
3770     };
3771     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3772 
3773     if (useSoftFloat() || hasSPE())
3774        NumFPArgRegs = 0;
3775 
3776     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3777     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3778 
3779     // Make room for NumGPArgRegs and NumFPArgRegs.
3780     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3781                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3782 
3783     FuncInfo->setVarArgsStackOffset(
3784       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3785                             CCInfo.getNextStackOffset(), true));
3786 
3787     FuncInfo->setVarArgsFrameIndex(
3788         MFI.CreateStackObject(Depth, Align(8), false));
3789     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3790 
3791     // The fixed integer arguments of a variadic function are stored to the
3792     // VarArgsFrameIndex on the stack so that they may be loaded by
3793     // dereferencing the result of va_next.
3794     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3795       // Get an existing live-in vreg, or add a new one.
3796       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3797       if (!VReg)
3798         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3799 
3800       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3801       SDValue Store =
3802           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3803       MemOps.push_back(Store);
3804       // Increment the address by four for the next argument to store
3805       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3806       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3807     }
3808 
3809     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3810     // is set.
3811     // The double arguments are stored to the VarArgsFrameIndex
3812     // on the stack.
3813     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3814       // Get an existing live-in vreg, or add a new one.
3815       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3816       if (!VReg)
3817         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3818 
3819       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3820       SDValue Store =
3821           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3822       MemOps.push_back(Store);
3823       // Increment the address by eight for the next argument to store
3824       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3825                                          PtrVT);
3826       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3827     }
3828   }
3829 
3830   if (!MemOps.empty())
3831     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3832 
3833   return Chain;
3834 }
3835 
3836 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3837 // value to MVT::i64 and then truncate to the correct register size.
3838 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3839                                              EVT ObjectVT, SelectionDAG &DAG,
3840                                              SDValue ArgVal,
3841                                              const SDLoc &dl) const {
3842   if (Flags.isSExt())
3843     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3844                          DAG.getValueType(ObjectVT));
3845   else if (Flags.isZExt())
3846     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3847                          DAG.getValueType(ObjectVT));
3848 
3849   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3850 }
3851 
3852 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3853     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3854     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3855     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3856   // TODO: add description of PPC stack frame format, or at least some docs.
3857   //
3858   bool isELFv2ABI = Subtarget.isELFv2ABI();
3859   bool isLittleEndian = Subtarget.isLittleEndian();
3860   MachineFunction &MF = DAG.getMachineFunction();
3861   MachineFrameInfo &MFI = MF.getFrameInfo();
3862   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3863 
3864   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3865          "fastcc not supported on varargs functions");
3866 
3867   EVT PtrVT = getPointerTy(MF.getDataLayout());
3868   // Potential tail calls could cause overwriting of argument stack slots.
3869   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3870                        (CallConv == CallingConv::Fast));
3871   unsigned PtrByteSize = 8;
3872   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3873 
3874   static const MCPhysReg GPR[] = {
3875     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3876     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3877   };
3878   static const MCPhysReg VR[] = {
3879     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3880     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3881   };
3882 
3883   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3884   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3885   const unsigned Num_VR_Regs  = array_lengthof(VR);
3886 
3887   // Do a first pass over the arguments to determine whether the ABI
3888   // guarantees that our caller has allocated the parameter save area
3889   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3890   // in the ELFv2 ABI, it is true if this is a vararg function or if
3891   // any parameter is located in a stack slot.
3892 
3893   bool HasParameterArea = !isELFv2ABI || isVarArg;
3894   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3895   unsigned NumBytes = LinkageSize;
3896   unsigned AvailableFPRs = Num_FPR_Regs;
3897   unsigned AvailableVRs = Num_VR_Regs;
3898   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3899     if (Ins[i].Flags.isNest())
3900       continue;
3901 
3902     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3903                                PtrByteSize, LinkageSize, ParamAreaSize,
3904                                NumBytes, AvailableFPRs, AvailableVRs))
3905       HasParameterArea = true;
3906   }
3907 
3908   // Add DAG nodes to load the arguments or copy them out of registers.  On
3909   // entry to a function on PPC, the arguments start after the linkage area,
3910   // although the first ones are often in registers.
3911 
3912   unsigned ArgOffset = LinkageSize;
3913   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3914   SmallVector<SDValue, 8> MemOps;
3915   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3916   unsigned CurArgIdx = 0;
3917   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3918     SDValue ArgVal;
3919     bool needsLoad = false;
3920     EVT ObjectVT = Ins[ArgNo].VT;
3921     EVT OrigVT = Ins[ArgNo].ArgVT;
3922     unsigned ObjSize = ObjectVT.getStoreSize();
3923     unsigned ArgSize = ObjSize;
3924     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3925     if (Ins[ArgNo].isOrigArg()) {
3926       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3927       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3928     }
3929     // We re-align the argument offset for each argument, except when using the
3930     // fast calling convention, when we need to make sure we do that only when
3931     // we'll actually use a stack slot.
3932     unsigned CurArgOffset;
3933     Align Alignment;
3934     auto ComputeArgOffset = [&]() {
3935       /* Respect alignment of argument on the stack.  */
3936       Alignment =
3937           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3938       ArgOffset = alignTo(ArgOffset, Alignment);
3939       CurArgOffset = ArgOffset;
3940     };
3941 
3942     if (CallConv != CallingConv::Fast) {
3943       ComputeArgOffset();
3944 
3945       /* Compute GPR index associated with argument offset.  */
3946       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3947       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3948     }
3949 
3950     // FIXME the codegen can be much improved in some cases.
3951     // We do not have to keep everything in memory.
3952     if (Flags.isByVal()) {
3953       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3954 
3955       if (CallConv == CallingConv::Fast)
3956         ComputeArgOffset();
3957 
3958       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3959       ObjSize = Flags.getByValSize();
3960       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3961       // Empty aggregate parameters do not take up registers.  Examples:
3962       //   struct { } a;
3963       //   union  { } b;
3964       //   int c[0];
3965       // etc.  However, we have to provide a place-holder in InVals, so
3966       // pretend we have an 8-byte item at the current address for that
3967       // purpose.
3968       if (!ObjSize) {
3969         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3970         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3971         InVals.push_back(FIN);
3972         continue;
3973       }
3974 
3975       // Create a stack object covering all stack doublewords occupied
3976       // by the argument.  If the argument is (fully or partially) on
3977       // the stack, or if the argument is fully in registers but the
3978       // caller has allocated the parameter save anyway, we can refer
3979       // directly to the caller's stack frame.  Otherwise, create a
3980       // local copy in our own frame.
3981       int FI;
3982       if (HasParameterArea ||
3983           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3984         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3985       else
3986         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3987       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3988 
3989       // Handle aggregates smaller than 8 bytes.
3990       if (ObjSize < PtrByteSize) {
3991         // The value of the object is its address, which differs from the
3992         // address of the enclosing doubleword on big-endian systems.
3993         SDValue Arg = FIN;
3994         if (!isLittleEndian) {
3995           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3996           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3997         }
3998         InVals.push_back(Arg);
3999 
4000         if (GPR_idx != Num_GPR_Regs) {
4001           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4002           FuncInfo->addLiveInAttr(VReg, Flags);
4003           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4004           SDValue Store;
4005 
4006           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
4007             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
4008                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
4009             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4010                                       MachinePointerInfo(&*FuncArg), ObjType);
4011           } else {
4012             // For sizes that don't fit a truncating store (3, 5, 6, 7),
4013             // store the whole register as-is to the parameter save area
4014             // slot.
4015             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4016                                  MachinePointerInfo(&*FuncArg));
4017           }
4018 
4019           MemOps.push_back(Store);
4020         }
4021         // Whether we copied from a register or not, advance the offset
4022         // into the parameter save area by a full doubleword.
4023         ArgOffset += PtrByteSize;
4024         continue;
4025       }
4026 
4027       // The value of the object is its address, which is the address of
4028       // its first stack doubleword.
4029       InVals.push_back(FIN);
4030 
4031       // Store whatever pieces of the object are in registers to memory.
4032       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4033         if (GPR_idx == Num_GPR_Regs)
4034           break;
4035 
4036         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4037         FuncInfo->addLiveInAttr(VReg, Flags);
4038         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4039         SDValue Addr = FIN;
4040         if (j) {
4041           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4042           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4043         }
4044         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4045                                      MachinePointerInfo(&*FuncArg, j));
4046         MemOps.push_back(Store);
4047         ++GPR_idx;
4048       }
4049       ArgOffset += ArgSize;
4050       continue;
4051     }
4052 
4053     switch (ObjectVT.getSimpleVT().SimpleTy) {
4054     default: llvm_unreachable("Unhandled argument type!");
4055     case MVT::i1:
4056     case MVT::i32:
4057     case MVT::i64:
4058       if (Flags.isNest()) {
4059         // The 'nest' parameter, if any, is passed in R11.
4060         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4061         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4062 
4063         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4064           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4065 
4066         break;
4067       }
4068 
4069       // These can be scalar arguments or elements of an integer array type
4070       // passed directly.  Clang may use those instead of "byval" aggregate
4071       // types to avoid forcing arguments to memory unnecessarily.
4072       if (GPR_idx != Num_GPR_Regs) {
4073         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4074         FuncInfo->addLiveInAttr(VReg, Flags);
4075         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4076 
4077         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4078           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4079           // value to MVT::i64 and then truncate to the correct register size.
4080           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4081       } else {
4082         if (CallConv == CallingConv::Fast)
4083           ComputeArgOffset();
4084 
4085         needsLoad = true;
4086         ArgSize = PtrByteSize;
4087       }
4088       if (CallConv != CallingConv::Fast || needsLoad)
4089         ArgOffset += 8;
4090       break;
4091 
4092     case MVT::f32:
4093     case MVT::f64:
4094       // These can be scalar arguments or elements of a float array type
4095       // passed directly.  The latter are used to implement ELFv2 homogenous
4096       // float aggregates.
4097       if (FPR_idx != Num_FPR_Regs) {
4098         unsigned VReg;
4099 
4100         if (ObjectVT == MVT::f32)
4101           VReg = MF.addLiveIn(FPR[FPR_idx],
4102                               Subtarget.hasP8Vector()
4103                                   ? &PPC::VSSRCRegClass
4104                                   : &PPC::F4RCRegClass);
4105         else
4106           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4107                                                 ? &PPC::VSFRCRegClass
4108                                                 : &PPC::F8RCRegClass);
4109 
4110         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4111         ++FPR_idx;
4112       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4113         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4114         // once we support fp <-> gpr moves.
4115 
4116         // This can only ever happen in the presence of f32 array types,
4117         // since otherwise we never run out of FPRs before running out
4118         // of GPRs.
4119         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4120         FuncInfo->addLiveInAttr(VReg, Flags);
4121         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4122 
4123         if (ObjectVT == MVT::f32) {
4124           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4125             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4126                                  DAG.getConstant(32, dl, MVT::i32));
4127           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4128         }
4129 
4130         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4131       } else {
4132         if (CallConv == CallingConv::Fast)
4133           ComputeArgOffset();
4134 
4135         needsLoad = true;
4136       }
4137 
4138       // When passing an array of floats, the array occupies consecutive
4139       // space in the argument area; only round up to the next doubleword
4140       // at the end of the array.  Otherwise, each float takes 8 bytes.
4141       if (CallConv != CallingConv::Fast || needsLoad) {
4142         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4143         ArgOffset += ArgSize;
4144         if (Flags.isInConsecutiveRegsLast())
4145           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4146       }
4147       break;
4148     case MVT::v4f32:
4149     case MVT::v4i32:
4150     case MVT::v8i16:
4151     case MVT::v16i8:
4152     case MVT::v2f64:
4153     case MVT::v2i64:
4154     case MVT::v1i128:
4155     case MVT::f128:
4156       // These can be scalar arguments or elements of a vector array type
4157       // passed directly.  The latter are used to implement ELFv2 homogenous
4158       // vector aggregates.
4159       if (VR_idx != Num_VR_Regs) {
4160         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4161         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4162         ++VR_idx;
4163       } else {
4164         if (CallConv == CallingConv::Fast)
4165           ComputeArgOffset();
4166         needsLoad = true;
4167       }
4168       if (CallConv != CallingConv::Fast || needsLoad)
4169         ArgOffset += 16;
4170       break;
4171     }
4172 
4173     // We need to load the argument to a virtual register if we determined
4174     // above that we ran out of physical registers of the appropriate type.
4175     if (needsLoad) {
4176       if (ObjSize < ArgSize && !isLittleEndian)
4177         CurArgOffset += ArgSize - ObjSize;
4178       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4179       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4180       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4181     }
4182 
4183     InVals.push_back(ArgVal);
4184   }
4185 
4186   // Area that is at least reserved in the caller of this function.
4187   unsigned MinReservedArea;
4188   if (HasParameterArea)
4189     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4190   else
4191     MinReservedArea = LinkageSize;
4192 
4193   // Set the size that is at least reserved in caller of this function.  Tail
4194   // call optimized functions' reserved stack space needs to be aligned so that
4195   // taking the difference between two stack areas will result in an aligned
4196   // stack.
4197   MinReservedArea =
4198       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4199   FuncInfo->setMinReservedArea(MinReservedArea);
4200 
4201   // If the function takes variable number of arguments, make a frame index for
4202   // the start of the first vararg value... for expansion of llvm.va_start.
4203   // On ELFv2ABI spec, it writes:
4204   // C programs that are intended to be *portable* across different compilers
4205   // and architectures must use the header file <stdarg.h> to deal with variable
4206   // argument lists.
4207   if (isVarArg && MFI.hasVAStart()) {
4208     int Depth = ArgOffset;
4209 
4210     FuncInfo->setVarArgsFrameIndex(
4211       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4212     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4213 
4214     // If this function is vararg, store any remaining integer argument regs
4215     // to their spots on the stack so that they may be loaded by dereferencing
4216     // the result of va_next.
4217     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4218          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4219       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4220       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4221       SDValue Store =
4222           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4223       MemOps.push_back(Store);
4224       // Increment the address by four for the next argument to store
4225       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4226       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4227     }
4228   }
4229 
4230   if (!MemOps.empty())
4231     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4232 
4233   return Chain;
4234 }
4235 
4236 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4237     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4238     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4239     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4240   // TODO: add description of PPC stack frame format, or at least some docs.
4241   //
4242   MachineFunction &MF = DAG.getMachineFunction();
4243   MachineFrameInfo &MFI = MF.getFrameInfo();
4244   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4245 
4246   EVT PtrVT = getPointerTy(MF.getDataLayout());
4247   bool isPPC64 = PtrVT == MVT::i64;
4248   // Potential tail calls could cause overwriting of argument stack slots.
4249   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4250                        (CallConv == CallingConv::Fast));
4251   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4252   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4253   unsigned ArgOffset = LinkageSize;
4254   // Area that is at least reserved in caller of this function.
4255   unsigned MinReservedArea = ArgOffset;
4256 
4257   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4258     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4259     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4260   };
4261   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4262     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4263     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4264   };
4265   static const MCPhysReg VR[] = {
4266     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4267     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4268   };
4269 
4270   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4271   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4272   const unsigned Num_VR_Regs  = array_lengthof( VR);
4273 
4274   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4275 
4276   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4277 
4278   // In 32-bit non-varargs functions, the stack space for vectors is after the
4279   // stack space for non-vectors.  We do not use this space unless we have
4280   // too many vectors to fit in registers, something that only occurs in
4281   // constructed examples:), but we have to walk the arglist to figure
4282   // that out...for the pathological case, compute VecArgOffset as the
4283   // start of the vector parameter area.  Computing VecArgOffset is the
4284   // entire point of the following loop.
4285   unsigned VecArgOffset = ArgOffset;
4286   if (!isVarArg && !isPPC64) {
4287     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4288          ++ArgNo) {
4289       EVT ObjectVT = Ins[ArgNo].VT;
4290       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4291 
4292       if (Flags.isByVal()) {
4293         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4294         unsigned ObjSize = Flags.getByValSize();
4295         unsigned ArgSize =
4296                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4297         VecArgOffset += ArgSize;
4298         continue;
4299       }
4300 
4301       switch(ObjectVT.getSimpleVT().SimpleTy) {
4302       default: llvm_unreachable("Unhandled argument type!");
4303       case MVT::i1:
4304       case MVT::i32:
4305       case MVT::f32:
4306         VecArgOffset += 4;
4307         break;
4308       case MVT::i64:  // PPC64
4309       case MVT::f64:
4310         // FIXME: We are guaranteed to be !isPPC64 at this point.
4311         // Does MVT::i64 apply?
4312         VecArgOffset += 8;
4313         break;
4314       case MVT::v4f32:
4315       case MVT::v4i32:
4316       case MVT::v8i16:
4317       case MVT::v16i8:
4318         // Nothing to do, we're only looking at Nonvector args here.
4319         break;
4320       }
4321     }
4322   }
4323   // We've found where the vector parameter area in memory is.  Skip the
4324   // first 12 parameters; these don't use that memory.
4325   VecArgOffset = ((VecArgOffset+15)/16)*16;
4326   VecArgOffset += 12*16;
4327 
4328   // Add DAG nodes to load the arguments or copy them out of registers.  On
4329   // entry to a function on PPC, the arguments start after the linkage area,
4330   // although the first ones are often in registers.
4331 
4332   SmallVector<SDValue, 8> MemOps;
4333   unsigned nAltivecParamsAtEnd = 0;
4334   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4335   unsigned CurArgIdx = 0;
4336   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4337     SDValue ArgVal;
4338     bool needsLoad = false;
4339     EVT ObjectVT = Ins[ArgNo].VT;
4340     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4341     unsigned ArgSize = ObjSize;
4342     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4343     if (Ins[ArgNo].isOrigArg()) {
4344       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4345       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4346     }
4347     unsigned CurArgOffset = ArgOffset;
4348 
4349     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4350     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4351         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4352       if (isVarArg || isPPC64) {
4353         MinReservedArea = ((MinReservedArea+15)/16)*16;
4354         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4355                                                   Flags,
4356                                                   PtrByteSize);
4357       } else  nAltivecParamsAtEnd++;
4358     } else
4359       // Calculate min reserved area.
4360       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4361                                                 Flags,
4362                                                 PtrByteSize);
4363 
4364     // FIXME the codegen can be much improved in some cases.
4365     // We do not have to keep everything in memory.
4366     if (Flags.isByVal()) {
4367       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4368 
4369       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4370       ObjSize = Flags.getByValSize();
4371       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4372       // Objects of size 1 and 2 are right justified, everything else is
4373       // left justified.  This means the memory address is adjusted forwards.
4374       if (ObjSize==1 || ObjSize==2) {
4375         CurArgOffset = CurArgOffset + (4 - ObjSize);
4376       }
4377       // The value of the object is its address.
4378       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4379       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4380       InVals.push_back(FIN);
4381       if (ObjSize==1 || ObjSize==2) {
4382         if (GPR_idx != Num_GPR_Regs) {
4383           unsigned VReg;
4384           if (isPPC64)
4385             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4386           else
4387             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4388           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4389           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4390           SDValue Store =
4391               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4392                                 MachinePointerInfo(&*FuncArg), ObjType);
4393           MemOps.push_back(Store);
4394           ++GPR_idx;
4395         }
4396 
4397         ArgOffset += PtrByteSize;
4398 
4399         continue;
4400       }
4401       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4402         // Store whatever pieces of the object are in registers
4403         // to memory.  ArgOffset will be the address of the beginning
4404         // of the object.
4405         if (GPR_idx != Num_GPR_Regs) {
4406           unsigned VReg;
4407           if (isPPC64)
4408             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4409           else
4410             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4411           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4412           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4413           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4414           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4415                                        MachinePointerInfo(&*FuncArg, j));
4416           MemOps.push_back(Store);
4417           ++GPR_idx;
4418           ArgOffset += PtrByteSize;
4419         } else {
4420           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4421           break;
4422         }
4423       }
4424       continue;
4425     }
4426 
4427     switch (ObjectVT.getSimpleVT().SimpleTy) {
4428     default: llvm_unreachable("Unhandled argument type!");
4429     case MVT::i1:
4430     case MVT::i32:
4431       if (!isPPC64) {
4432         if (GPR_idx != Num_GPR_Regs) {
4433           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4434           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4435 
4436           if (ObjectVT == MVT::i1)
4437             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4438 
4439           ++GPR_idx;
4440         } else {
4441           needsLoad = true;
4442           ArgSize = PtrByteSize;
4443         }
4444         // All int arguments reserve stack space in the Darwin ABI.
4445         ArgOffset += PtrByteSize;
4446         break;
4447       }
4448       LLVM_FALLTHROUGH;
4449     case MVT::i64:  // PPC64
4450       if (GPR_idx != Num_GPR_Regs) {
4451         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4452         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4453 
4454         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4455           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4456           // value to MVT::i64 and then truncate to the correct register size.
4457           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4458 
4459         ++GPR_idx;
4460       } else {
4461         needsLoad = true;
4462         ArgSize = PtrByteSize;
4463       }
4464       // All int arguments reserve stack space in the Darwin ABI.
4465       ArgOffset += 8;
4466       break;
4467 
4468     case MVT::f32:
4469     case MVT::f64:
4470       // Every 4 bytes of argument space consumes one of the GPRs available for
4471       // argument passing.
4472       if (GPR_idx != Num_GPR_Regs) {
4473         ++GPR_idx;
4474         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4475           ++GPR_idx;
4476       }
4477       if (FPR_idx != Num_FPR_Regs) {
4478         unsigned VReg;
4479 
4480         if (ObjectVT == MVT::f32)
4481           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4482         else
4483           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4484 
4485         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4486         ++FPR_idx;
4487       } else {
4488         needsLoad = true;
4489       }
4490 
4491       // All FP arguments reserve stack space in the Darwin ABI.
4492       ArgOffset += isPPC64 ? 8 : ObjSize;
4493       break;
4494     case MVT::v4f32:
4495     case MVT::v4i32:
4496     case MVT::v8i16:
4497     case MVT::v16i8:
4498       // Note that vector arguments in registers don't reserve stack space,
4499       // except in varargs functions.
4500       if (VR_idx != Num_VR_Regs) {
4501         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4502         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4503         if (isVarArg) {
4504           while ((ArgOffset % 16) != 0) {
4505             ArgOffset += PtrByteSize;
4506             if (GPR_idx != Num_GPR_Regs)
4507               GPR_idx++;
4508           }
4509           ArgOffset += 16;
4510           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4511         }
4512         ++VR_idx;
4513       } else {
4514         if (!isVarArg && !isPPC64) {
4515           // Vectors go after all the nonvectors.
4516           CurArgOffset = VecArgOffset;
4517           VecArgOffset += 16;
4518         } else {
4519           // Vectors are aligned.
4520           ArgOffset = ((ArgOffset+15)/16)*16;
4521           CurArgOffset = ArgOffset;
4522           ArgOffset += 16;
4523         }
4524         needsLoad = true;
4525       }
4526       break;
4527     }
4528 
4529     // We need to load the argument to a virtual register if we determined above
4530     // that we ran out of physical registers of the appropriate type.
4531     if (needsLoad) {
4532       int FI = MFI.CreateFixedObject(ObjSize,
4533                                      CurArgOffset + (ArgSize - ObjSize),
4534                                      isImmutable);
4535       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4536       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4537     }
4538 
4539     InVals.push_back(ArgVal);
4540   }
4541 
4542   // Allow for Altivec parameters at the end, if needed.
4543   if (nAltivecParamsAtEnd) {
4544     MinReservedArea = ((MinReservedArea+15)/16)*16;
4545     MinReservedArea += 16*nAltivecParamsAtEnd;
4546   }
4547 
4548   // Area that is at least reserved in the caller of this function.
4549   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4550 
4551   // Set the size that is at least reserved in caller of this function.  Tail
4552   // call optimized functions' reserved stack space needs to be aligned so that
4553   // taking the difference between two stack areas will result in an aligned
4554   // stack.
4555   MinReservedArea =
4556       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4557   FuncInfo->setMinReservedArea(MinReservedArea);
4558 
4559   // If the function takes variable number of arguments, make a frame index for
4560   // the start of the first vararg value... for expansion of llvm.va_start.
4561   if (isVarArg) {
4562     int Depth = ArgOffset;
4563 
4564     FuncInfo->setVarArgsFrameIndex(
4565       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4566                             Depth, true));
4567     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4568 
4569     // If this function is vararg, store any remaining integer argument regs
4570     // to their spots on the stack so that they may be loaded by dereferencing
4571     // the result of va_next.
4572     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4573       unsigned VReg;
4574 
4575       if (isPPC64)
4576         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4577       else
4578         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4579 
4580       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4581       SDValue Store =
4582           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4583       MemOps.push_back(Store);
4584       // Increment the address by four for the next argument to store
4585       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4586       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4587     }
4588   }
4589 
4590   if (!MemOps.empty())
4591     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4592 
4593   return Chain;
4594 }
4595 
4596 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4597 /// adjusted to accommodate the arguments for the tailcall.
4598 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4599                                    unsigned ParamSize) {
4600 
4601   if (!isTailCall) return 0;
4602 
4603   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4604   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4605   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4606   // Remember only if the new adjustment is bigger.
4607   if (SPDiff < FI->getTailCallSPDelta())
4608     FI->setTailCallSPDelta(SPDiff);
4609 
4610   return SPDiff;
4611 }
4612 
4613 static bool isFunctionGlobalAddress(SDValue Callee);
4614 
4615 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4616                               const TargetMachine &TM) {
4617   // It does not make sense to call callsShareTOCBase() with a caller that
4618   // is PC Relative since PC Relative callers do not have a TOC.
4619 #ifndef NDEBUG
4620   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4621   assert(!STICaller->isUsingPCRelativeCalls() &&
4622          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4623 #endif
4624 
4625   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4626   // don't have enough information to determine if the caller and callee share
4627   // the same  TOC base, so we have to pessimistically assume they don't for
4628   // correctness.
4629   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4630   if (!G)
4631     return false;
4632 
4633   const GlobalValue *GV = G->getGlobal();
4634 
4635   // If the callee is preemptable, then the static linker will use a plt-stub
4636   // which saves the toc to the stack, and needs a nop after the call
4637   // instruction to convert to a toc-restore.
4638   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4639     return false;
4640 
4641   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4642   // We may need a TOC restore in the situation where the caller requires a
4643   // valid TOC but the callee is PC Relative and does not.
4644   const Function *F = dyn_cast<Function>(GV);
4645   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4646 
4647   // If we have an Alias we can try to get the function from there.
4648   if (Alias) {
4649     const GlobalObject *GlobalObj = Alias->getBaseObject();
4650     F = dyn_cast<Function>(GlobalObj);
4651   }
4652 
4653   // If we still have no valid function pointer we do not have enough
4654   // information to determine if the callee uses PC Relative calls so we must
4655   // assume that it does.
4656   if (!F)
4657     return false;
4658 
4659   // If the callee uses PC Relative we cannot guarantee that the callee won't
4660   // clobber the TOC of the caller and so we must assume that the two
4661   // functions do not share a TOC base.
4662   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4663   if (STICallee->isUsingPCRelativeCalls())
4664     return false;
4665 
4666   // The medium and large code models are expected to provide a sufficiently
4667   // large TOC to provide all data addressing needs of a module with a
4668   // single TOC.
4669   if (CodeModel::Medium == TM.getCodeModel() ||
4670       CodeModel::Large == TM.getCodeModel())
4671     return true;
4672 
4673   // Otherwise we need to ensure callee and caller are in the same section,
4674   // since the linker may allocate multiple TOCs, and we don't know which
4675   // sections will belong to the same TOC base.
4676   if (!GV->isStrongDefinitionForLinker())
4677     return false;
4678 
4679   // Any explicitly-specified sections and section prefixes must also match.
4680   // Also, if we're using -ffunction-sections, then each function is always in
4681   // a different section (the same is true for COMDAT functions).
4682   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4683       GV->getSection() != Caller->getSection())
4684     return false;
4685   if (const auto *F = dyn_cast<Function>(GV)) {
4686     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4687       return false;
4688   }
4689 
4690   return true;
4691 }
4692 
4693 static bool
4694 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4695                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4696   assert(Subtarget.is64BitELFABI());
4697 
4698   const unsigned PtrByteSize = 8;
4699   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4700 
4701   static const MCPhysReg GPR[] = {
4702     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4703     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4704   };
4705   static const MCPhysReg VR[] = {
4706     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4707     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4708   };
4709 
4710   const unsigned NumGPRs = array_lengthof(GPR);
4711   const unsigned NumFPRs = 13;
4712   const unsigned NumVRs = array_lengthof(VR);
4713   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4714 
4715   unsigned NumBytes = LinkageSize;
4716   unsigned AvailableFPRs = NumFPRs;
4717   unsigned AvailableVRs = NumVRs;
4718 
4719   for (const ISD::OutputArg& Param : Outs) {
4720     if (Param.Flags.isNest()) continue;
4721 
4722     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4723                                LinkageSize, ParamAreaSize, NumBytes,
4724                                AvailableFPRs, AvailableVRs))
4725       return true;
4726   }
4727   return false;
4728 }
4729 
4730 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4731   if (CB.arg_size() != CallerFn->arg_size())
4732     return false;
4733 
4734   auto CalleeArgIter = CB.arg_begin();
4735   auto CalleeArgEnd = CB.arg_end();
4736   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4737 
4738   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4739     const Value* CalleeArg = *CalleeArgIter;
4740     const Value* CallerArg = &(*CallerArgIter);
4741     if (CalleeArg == CallerArg)
4742       continue;
4743 
4744     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4745     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4746     //      }
4747     // 1st argument of callee is undef and has the same type as caller.
4748     if (CalleeArg->getType() == CallerArg->getType() &&
4749         isa<UndefValue>(CalleeArg))
4750       continue;
4751 
4752     return false;
4753   }
4754 
4755   return true;
4756 }
4757 
4758 // Returns true if TCO is possible between the callers and callees
4759 // calling conventions.
4760 static bool
4761 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4762                                     CallingConv::ID CalleeCC) {
4763   // Tail calls are possible with fastcc and ccc.
4764   auto isTailCallableCC  = [] (CallingConv::ID CC){
4765       return  CC == CallingConv::C || CC == CallingConv::Fast;
4766   };
4767   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4768     return false;
4769 
4770   // We can safely tail call both fastcc and ccc callees from a c calling
4771   // convention caller. If the caller is fastcc, we may have less stack space
4772   // than a non-fastcc caller with the same signature so disable tail-calls in
4773   // that case.
4774   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4775 }
4776 
4777 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4778     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4779     const SmallVectorImpl<ISD::OutputArg> &Outs,
4780     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4781   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4782 
4783   if (DisableSCO && !TailCallOpt) return false;
4784 
4785   // Variadic argument functions are not supported.
4786   if (isVarArg) return false;
4787 
4788   auto &Caller = DAG.getMachineFunction().getFunction();
4789   // Check that the calling conventions are compatible for tco.
4790   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4791     return false;
4792 
4793   // Caller contains any byval parameter is not supported.
4794   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4795     return false;
4796 
4797   // Callee contains any byval parameter is not supported, too.
4798   // Note: This is a quick work around, because in some cases, e.g.
4799   // caller's stack size > callee's stack size, we are still able to apply
4800   // sibling call optimization. For example, gcc is able to do SCO for caller1
4801   // in the following example, but not for caller2.
4802   //   struct test {
4803   //     long int a;
4804   //     char ary[56];
4805   //   } gTest;
4806   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4807   //     b->a = v.a;
4808   //     return 0;
4809   //   }
4810   //   void caller1(struct test a, struct test c, struct test *b) {
4811   //     callee(gTest, b); }
4812   //   void caller2(struct test *b) { callee(gTest, b); }
4813   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4814     return false;
4815 
4816   // If callee and caller use different calling conventions, we cannot pass
4817   // parameters on stack since offsets for the parameter area may be different.
4818   if (Caller.getCallingConv() != CalleeCC &&
4819       needStackSlotPassParameters(Subtarget, Outs))
4820     return false;
4821 
4822   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4823   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4824   // callee potentially have different TOC bases then we cannot tail call since
4825   // we need to restore the TOC pointer after the call.
4826   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4827   // We cannot guarantee this for indirect calls or calls to external functions.
4828   // When PC-Relative addressing is used, the concept of the TOC is no longer
4829   // applicable so this check is not required.
4830   // Check first for indirect calls.
4831   if (!Subtarget.isUsingPCRelativeCalls() &&
4832       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4833     return false;
4834 
4835   // Check if we share the TOC base.
4836   if (!Subtarget.isUsingPCRelativeCalls() &&
4837       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4838     return false;
4839 
4840   // TCO allows altering callee ABI, so we don't have to check further.
4841   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4842     return true;
4843 
4844   if (DisableSCO) return false;
4845 
4846   // If callee use the same argument list that caller is using, then we can
4847   // apply SCO on this case. If it is not, then we need to check if callee needs
4848   // stack for passing arguments.
4849   // PC Relative tail calls may not have a CallBase.
4850   // If there is no CallBase we cannot verify if we have the same argument
4851   // list so assume that we don't have the same argument list.
4852   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4853       needStackSlotPassParameters(Subtarget, Outs))
4854     return false;
4855   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4856     return false;
4857 
4858   return true;
4859 }
4860 
4861 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4862 /// for tail call optimization. Targets which want to do tail call
4863 /// optimization should implement this function.
4864 bool
4865 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4866                                                      CallingConv::ID CalleeCC,
4867                                                      bool isVarArg,
4868                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4869                                                      SelectionDAG& DAG) const {
4870   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4871     return false;
4872 
4873   // Variable argument functions are not supported.
4874   if (isVarArg)
4875     return false;
4876 
4877   MachineFunction &MF = DAG.getMachineFunction();
4878   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4879   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4880     // Functions containing by val parameters are not supported.
4881     for (unsigned i = 0; i != Ins.size(); i++) {
4882        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4883        if (Flags.isByVal()) return false;
4884     }
4885 
4886     // Non-PIC/GOT tail calls are supported.
4887     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4888       return true;
4889 
4890     // At the moment we can only do local tail calls (in same module, hidden
4891     // or protected) if we are generating PIC.
4892     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4893       return G->getGlobal()->hasHiddenVisibility()
4894           || G->getGlobal()->hasProtectedVisibility();
4895   }
4896 
4897   return false;
4898 }
4899 
4900 /// isCallCompatibleAddress - Return the immediate to use if the specified
4901 /// 32-bit value is representable in the immediate field of a BxA instruction.
4902 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4903   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4904   if (!C) return nullptr;
4905 
4906   int Addr = C->getZExtValue();
4907   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4908       SignExtend32<26>(Addr) != Addr)
4909     return nullptr;  // Top 6 bits have to be sext of immediate.
4910 
4911   return DAG
4912       .getConstant(
4913           (int)C->getZExtValue() >> 2, SDLoc(Op),
4914           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4915       .getNode();
4916 }
4917 
4918 namespace {
4919 
4920 struct TailCallArgumentInfo {
4921   SDValue Arg;
4922   SDValue FrameIdxOp;
4923   int FrameIdx = 0;
4924 
4925   TailCallArgumentInfo() = default;
4926 };
4927 
4928 } // end anonymous namespace
4929 
4930 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4931 static void StoreTailCallArgumentsToStackSlot(
4932     SelectionDAG &DAG, SDValue Chain,
4933     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4934     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4935   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4936     SDValue Arg = TailCallArgs[i].Arg;
4937     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4938     int FI = TailCallArgs[i].FrameIdx;
4939     // Store relative to framepointer.
4940     MemOpChains.push_back(DAG.getStore(
4941         Chain, dl, Arg, FIN,
4942         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4943   }
4944 }
4945 
4946 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4947 /// the appropriate stack slot for the tail call optimized function call.
4948 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4949                                              SDValue OldRetAddr, SDValue OldFP,
4950                                              int SPDiff, const SDLoc &dl) {
4951   if (SPDiff) {
4952     // Calculate the new stack slot for the return address.
4953     MachineFunction &MF = DAG.getMachineFunction();
4954     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4955     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4956     bool isPPC64 = Subtarget.isPPC64();
4957     int SlotSize = isPPC64 ? 8 : 4;
4958     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4959     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4960                                                          NewRetAddrLoc, true);
4961     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4962     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4963     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4964                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4965   }
4966   return Chain;
4967 }
4968 
4969 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4970 /// the position of the argument.
4971 static void
4972 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4973                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4974                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4975   int Offset = ArgOffset + SPDiff;
4976   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4977   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4978   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4979   SDValue FIN = DAG.getFrameIndex(FI, VT);
4980   TailCallArgumentInfo Info;
4981   Info.Arg = Arg;
4982   Info.FrameIdxOp = FIN;
4983   Info.FrameIdx = FI;
4984   TailCallArguments.push_back(Info);
4985 }
4986 
4987 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4988 /// stack slot. Returns the chain as result and the loaded frame pointers in
4989 /// LROpOut/FPOpout. Used when tail calling.
4990 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4991     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4992     SDValue &FPOpOut, const SDLoc &dl) const {
4993   if (SPDiff) {
4994     // Load the LR and FP stack slot for later adjusting.
4995     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4996     LROpOut = getReturnAddrFrameIndex(DAG);
4997     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4998     Chain = SDValue(LROpOut.getNode(), 1);
4999   }
5000   return Chain;
5001 }
5002 
5003 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5004 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5005 /// specified by the specific parameter attribute. The copy will be passed as
5006 /// a byval function parameter.
5007 /// Sometimes what we are copying is the end of a larger object, the part that
5008 /// does not fit in registers.
5009 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5010                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5011                                          SelectionDAG &DAG, const SDLoc &dl) {
5012   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5013   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5014                        Flags.getNonZeroByValAlign(), false, false, false,
5015                        MachinePointerInfo(), MachinePointerInfo());
5016 }
5017 
5018 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5019 /// tail calls.
5020 static void LowerMemOpCallTo(
5021     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5022     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5023     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5024     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5025   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5026   if (!isTailCall) {
5027     if (isVector) {
5028       SDValue StackPtr;
5029       if (isPPC64)
5030         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5031       else
5032         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5033       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5034                            DAG.getConstant(ArgOffset, dl, PtrVT));
5035     }
5036     MemOpChains.push_back(
5037         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5038     // Calculate and remember argument location.
5039   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5040                                   TailCallArguments);
5041 }
5042 
5043 static void
5044 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5045                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5046                 SDValue FPOp,
5047                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5048   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5049   // might overwrite each other in case of tail call optimization.
5050   SmallVector<SDValue, 8> MemOpChains2;
5051   // Do not flag preceding copytoreg stuff together with the following stuff.
5052   InFlag = SDValue();
5053   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5054                                     MemOpChains2, dl);
5055   if (!MemOpChains2.empty())
5056     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5057 
5058   // Store the return address to the appropriate stack slot.
5059   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5060 
5061   // Emit callseq_end just before tailcall node.
5062   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5063                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5064   InFlag = Chain.getValue(1);
5065 }
5066 
5067 // Is this global address that of a function that can be called by name? (as
5068 // opposed to something that must hold a descriptor for an indirect call).
5069 static bool isFunctionGlobalAddress(SDValue Callee) {
5070   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5071     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5072         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5073       return false;
5074 
5075     return G->getGlobal()->getValueType()->isFunctionTy();
5076   }
5077 
5078   return false;
5079 }
5080 
5081 SDValue PPCTargetLowering::LowerCallResult(
5082     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5083     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5084     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5085   SmallVector<CCValAssign, 16> RVLocs;
5086   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5087                     *DAG.getContext());
5088 
5089   CCRetInfo.AnalyzeCallResult(
5090       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5091                ? RetCC_PPC_Cold
5092                : RetCC_PPC);
5093 
5094   // Copy all of the result registers out of their specified physreg.
5095   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5096     CCValAssign &VA = RVLocs[i];
5097     assert(VA.isRegLoc() && "Can only return in registers!");
5098 
5099     SDValue Val;
5100 
5101     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5102       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5103                                       InFlag);
5104       Chain = Lo.getValue(1);
5105       InFlag = Lo.getValue(2);
5106       VA = RVLocs[++i]; // skip ahead to next loc
5107       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5108                                       InFlag);
5109       Chain = Hi.getValue(1);
5110       InFlag = Hi.getValue(2);
5111       if (!Subtarget.isLittleEndian())
5112         std::swap (Lo, Hi);
5113       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5114     } else {
5115       Val = DAG.getCopyFromReg(Chain, dl,
5116                                VA.getLocReg(), VA.getLocVT(), InFlag);
5117       Chain = Val.getValue(1);
5118       InFlag = Val.getValue(2);
5119     }
5120 
5121     switch (VA.getLocInfo()) {
5122     default: llvm_unreachable("Unknown loc info!");
5123     case CCValAssign::Full: break;
5124     case CCValAssign::AExt:
5125       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5126       break;
5127     case CCValAssign::ZExt:
5128       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5129                         DAG.getValueType(VA.getValVT()));
5130       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5131       break;
5132     case CCValAssign::SExt:
5133       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5134                         DAG.getValueType(VA.getValVT()));
5135       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5136       break;
5137     }
5138 
5139     InVals.push_back(Val);
5140   }
5141 
5142   return Chain;
5143 }
5144 
5145 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5146                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5147   // PatchPoint calls are not indirect.
5148   if (isPatchPoint)
5149     return false;
5150 
5151   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5152     return false;
5153 
5154   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5155   // becuase the immediate function pointer points to a descriptor instead of
5156   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5157   // pointer immediate points to the global entry point, while the BLA would
5158   // need to jump to the local entry point (see rL211174).
5159   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5160       isBLACompatibleAddress(Callee, DAG))
5161     return false;
5162 
5163   return true;
5164 }
5165 
5166 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5167 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5168   return Subtarget.isAIXABI() ||
5169          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5170 }
5171 
5172 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5173                               const Function &Caller,
5174                               const SDValue &Callee,
5175                               const PPCSubtarget &Subtarget,
5176                               const TargetMachine &TM) {
5177   if (CFlags.IsTailCall)
5178     return PPCISD::TC_RETURN;
5179 
5180   // This is a call through a function pointer.
5181   if (CFlags.IsIndirect) {
5182     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5183     // indirect calls. The save of the caller's TOC pointer to the stack will be
5184     // inserted into the DAG as part of call lowering. The restore of the TOC
5185     // pointer is modeled by using a pseudo instruction for the call opcode that
5186     // represents the 2 instruction sequence of an indirect branch and link,
5187     // immediately followed by a load of the TOC pointer from the the stack save
5188     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5189     // as it is not saved or used.
5190     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5191                                                : PPCISD::BCTRL;
5192   }
5193 
5194   if (Subtarget.isUsingPCRelativeCalls()) {
5195     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5196     return PPCISD::CALL_NOTOC;
5197   }
5198 
5199   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5200   // immediately following the call instruction if the caller and callee may
5201   // have different TOC bases. At link time if the linker determines the calls
5202   // may not share a TOC base, the call is redirected to a trampoline inserted
5203   // by the linker. The trampoline will (among other things) save the callers
5204   // TOC pointer at an ABI designated offset in the linkage area and the linker
5205   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5206   // into gpr2.
5207   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5208     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5209                                                   : PPCISD::CALL_NOP;
5210 
5211   return PPCISD::CALL;
5212 }
5213 
5214 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5215                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5216   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5217     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5218       return SDValue(Dest, 0);
5219 
5220   // Returns true if the callee is local, and false otherwise.
5221   auto isLocalCallee = [&]() {
5222     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5223     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5224     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5225 
5226     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5227            !dyn_cast_or_null<GlobalIFunc>(GV);
5228   };
5229 
5230   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5231   // a static relocation model causes some versions of GNU LD (2.17.50, at
5232   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5233   // built with secure-PLT.
5234   bool UsePlt =
5235       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5236       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5237 
5238   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5239     const TargetMachine &TM = Subtarget.getTargetMachine();
5240     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5241     MCSymbolXCOFF *S =
5242         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5243 
5244     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5245     return DAG.getMCSymbol(S, PtrVT);
5246   };
5247 
5248   if (isFunctionGlobalAddress(Callee)) {
5249     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5250 
5251     if (Subtarget.isAIXABI()) {
5252       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5253       return getAIXFuncEntryPointSymbolSDNode(GV);
5254     }
5255     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5256                                       UsePlt ? PPCII::MO_PLT : 0);
5257   }
5258 
5259   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5260     const char *SymName = S->getSymbol();
5261     if (Subtarget.isAIXABI()) {
5262       // If there exists a user-declared function whose name is the same as the
5263       // ExternalSymbol's, then we pick up the user-declared version.
5264       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5265       if (const Function *F =
5266               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5267         return getAIXFuncEntryPointSymbolSDNode(F);
5268 
5269       // On AIX, direct function calls reference the symbol for the function's
5270       // entry point, which is named by prepending a "." before the function's
5271       // C-linkage name. A Qualname is returned here because an external
5272       // function entry point is a csect with XTY_ER property.
5273       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5274         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5275         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5276             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5277             SectionKind::getMetadata());
5278         return Sec->getQualNameSymbol();
5279       };
5280 
5281       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5282     }
5283     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5284                                        UsePlt ? PPCII::MO_PLT : 0);
5285   }
5286 
5287   // No transformation needed.
5288   assert(Callee.getNode() && "What no callee?");
5289   return Callee;
5290 }
5291 
5292 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5293   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5294          "Expected a CALLSEQ_STARTSDNode.");
5295 
5296   // The last operand is the chain, except when the node has glue. If the node
5297   // has glue, then the last operand is the glue, and the chain is the second
5298   // last operand.
5299   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5300   if (LastValue.getValueType() != MVT::Glue)
5301     return LastValue;
5302 
5303   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5304 }
5305 
5306 // Creates the node that moves a functions address into the count register
5307 // to prepare for an indirect call instruction.
5308 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5309                                 SDValue &Glue, SDValue &Chain,
5310                                 const SDLoc &dl) {
5311   SDValue MTCTROps[] = {Chain, Callee, Glue};
5312   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5313   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5314                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5315   // The glue is the second value produced.
5316   Glue = Chain.getValue(1);
5317 }
5318 
5319 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5320                                           SDValue &Glue, SDValue &Chain,
5321                                           SDValue CallSeqStart,
5322                                           const CallBase *CB, const SDLoc &dl,
5323                                           bool hasNest,
5324                                           const PPCSubtarget &Subtarget) {
5325   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5326   // entry point, but to the function descriptor (the function entry point
5327   // address is part of the function descriptor though).
5328   // The function descriptor is a three doubleword structure with the
5329   // following fields: function entry point, TOC base address and
5330   // environment pointer.
5331   // Thus for a call through a function pointer, the following actions need
5332   // to be performed:
5333   //   1. Save the TOC of the caller in the TOC save area of its stack
5334   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5335   //   2. Load the address of the function entry point from the function
5336   //      descriptor.
5337   //   3. Load the TOC of the callee from the function descriptor into r2.
5338   //   4. Load the environment pointer from the function descriptor into
5339   //      r11.
5340   //   5. Branch to the function entry point address.
5341   //   6. On return of the callee, the TOC of the caller needs to be
5342   //      restored (this is done in FinishCall()).
5343   //
5344   // The loads are scheduled at the beginning of the call sequence, and the
5345   // register copies are flagged together to ensure that no other
5346   // operations can be scheduled in between. E.g. without flagging the
5347   // copies together, a TOC access in the caller could be scheduled between
5348   // the assignment of the callee TOC and the branch to the callee, which leads
5349   // to incorrect code.
5350 
5351   // Start by loading the function address from the descriptor.
5352   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5353   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5354                       ? (MachineMemOperand::MODereferenceable |
5355                          MachineMemOperand::MOInvariant)
5356                       : MachineMemOperand::MONone;
5357 
5358   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5359 
5360   // Registers used in building the DAG.
5361   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5362   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5363 
5364   // Offsets of descriptor members.
5365   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5366   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5367 
5368   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5369   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5370 
5371   // One load for the functions entry point address.
5372   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5373                                     Alignment, MMOFlags);
5374 
5375   // One for loading the TOC anchor for the module that contains the called
5376   // function.
5377   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5378   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5379   SDValue TOCPtr =
5380       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5381                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5382 
5383   // One for loading the environment pointer.
5384   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5385   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5386   SDValue LoadEnvPtr =
5387       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5388                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5389 
5390 
5391   // Then copy the newly loaded TOC anchor to the TOC pointer.
5392   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5393   Chain = TOCVal.getValue(0);
5394   Glue = TOCVal.getValue(1);
5395 
5396   // If the function call has an explicit 'nest' parameter, it takes the
5397   // place of the environment pointer.
5398   assert((!hasNest || !Subtarget.isAIXABI()) &&
5399          "Nest parameter is not supported on AIX.");
5400   if (!hasNest) {
5401     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5402     Chain = EnvVal.getValue(0);
5403     Glue = EnvVal.getValue(1);
5404   }
5405 
5406   // The rest of the indirect call sequence is the same as the non-descriptor
5407   // DAG.
5408   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5409 }
5410 
5411 static void
5412 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5413                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5414                   SelectionDAG &DAG,
5415                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5416                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5417                   const PPCSubtarget &Subtarget) {
5418   const bool IsPPC64 = Subtarget.isPPC64();
5419   // MVT for a general purpose register.
5420   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5421 
5422   // First operand is always the chain.
5423   Ops.push_back(Chain);
5424 
5425   // If it's a direct call pass the callee as the second operand.
5426   if (!CFlags.IsIndirect)
5427     Ops.push_back(Callee);
5428   else {
5429     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5430 
5431     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5432     // on the stack (this would have been done in `LowerCall_64SVR4` or
5433     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5434     // represents both the indirect branch and a load that restores the TOC
5435     // pointer from the linkage area. The operand for the TOC restore is an add
5436     // of the TOC save offset to the stack pointer. This must be the second
5437     // operand: after the chain input but before any other variadic arguments.
5438     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5439     // saved or used.
5440     if (isTOCSaveRestoreRequired(Subtarget)) {
5441       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5442 
5443       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5444       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5445       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5446       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5447       Ops.push_back(AddTOC);
5448     }
5449 
5450     // Add the register used for the environment pointer.
5451     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5452       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5453                                     RegVT));
5454 
5455 
5456     // Add CTR register as callee so a bctr can be emitted later.
5457     if (CFlags.IsTailCall)
5458       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5459   }
5460 
5461   // If this is a tail call add stack pointer delta.
5462   if (CFlags.IsTailCall)
5463     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5464 
5465   // Add argument registers to the end of the list so that they are known live
5466   // into the call.
5467   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5468     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5469                                   RegsToPass[i].second.getValueType()));
5470 
5471   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5472   // no way to mark dependencies as implicit here.
5473   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5474   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5475        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5476     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5477 
5478   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5479   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5480     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5481 
5482   // Add a register mask operand representing the call-preserved registers.
5483   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5484   const uint32_t *Mask =
5485       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5486   assert(Mask && "Missing call preserved mask for calling convention");
5487   Ops.push_back(DAG.getRegisterMask(Mask));
5488 
5489   // If the glue is valid, it is the last operand.
5490   if (Glue.getNode())
5491     Ops.push_back(Glue);
5492 }
5493 
5494 SDValue PPCTargetLowering::FinishCall(
5495     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5496     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5497     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5498     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5499     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5500 
5501   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5502       Subtarget.isAIXABI())
5503     setUsesTOCBasePtr(DAG);
5504 
5505   unsigned CallOpc =
5506       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5507                     Subtarget, DAG.getTarget());
5508 
5509   if (!CFlags.IsIndirect)
5510     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5511   else if (Subtarget.usesFunctionDescriptors())
5512     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5513                                   dl, CFlags.HasNest, Subtarget);
5514   else
5515     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5516 
5517   // Build the operand list for the call instruction.
5518   SmallVector<SDValue, 8> Ops;
5519   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5520                     SPDiff, Subtarget);
5521 
5522   // Emit tail call.
5523   if (CFlags.IsTailCall) {
5524     // Indirect tail call when using PC Relative calls do not have the same
5525     // constraints.
5526     assert(((Callee.getOpcode() == ISD::Register &&
5527              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5528             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5529             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5530             isa<ConstantSDNode>(Callee) ||
5531             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5532            "Expecting a global address, external symbol, absolute value, "
5533            "register or an indirect tail call when PC Relative calls are "
5534            "used.");
5535     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5536     assert(CallOpc == PPCISD::TC_RETURN &&
5537            "Unexpected call opcode for a tail call.");
5538     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5539     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5540   }
5541 
5542   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5543   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5544   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5545   Glue = Chain.getValue(1);
5546 
5547   // When performing tail call optimization the callee pops its arguments off
5548   // the stack. Account for this here so these bytes can be pushed back on in
5549   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5550   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5551                          getTargetMachine().Options.GuaranteedTailCallOpt)
5552                             ? NumBytes
5553                             : 0;
5554 
5555   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5556                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5557                              Glue, dl);
5558   Glue = Chain.getValue(1);
5559 
5560   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5561                          DAG, InVals);
5562 }
5563 
5564 SDValue
5565 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5566                              SmallVectorImpl<SDValue> &InVals) const {
5567   SelectionDAG &DAG                     = CLI.DAG;
5568   SDLoc &dl                             = CLI.DL;
5569   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5570   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5571   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5572   SDValue Chain                         = CLI.Chain;
5573   SDValue Callee                        = CLI.Callee;
5574   bool &isTailCall                      = CLI.IsTailCall;
5575   CallingConv::ID CallConv              = CLI.CallConv;
5576   bool isVarArg                         = CLI.IsVarArg;
5577   bool isPatchPoint                     = CLI.IsPatchPoint;
5578   const CallBase *CB                    = CLI.CB;
5579 
5580   if (isTailCall) {
5581     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5582       isTailCall = false;
5583     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5584       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5585           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5586     else
5587       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5588                                                      Ins, DAG);
5589     if (isTailCall) {
5590       ++NumTailCalls;
5591       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5592         ++NumSiblingCalls;
5593 
5594       // PC Relative calls no longer guarantee that the callee is a Global
5595       // Address Node. The callee could be an indirect tail call in which
5596       // case the SDValue for the callee could be a load (to load the address
5597       // of a function pointer) or it may be a register copy (to move the
5598       // address of the callee from a function parameter into a virtual
5599       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5600       assert((Subtarget.isUsingPCRelativeCalls() ||
5601               isa<GlobalAddressSDNode>(Callee)) &&
5602              "Callee should be an llvm::Function object.");
5603 
5604       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5605                         << "\nTCO callee: ");
5606       LLVM_DEBUG(Callee.dump());
5607     }
5608   }
5609 
5610   if (!isTailCall && CB && CB->isMustTailCall())
5611     report_fatal_error("failed to perform tail call elimination on a call "
5612                        "site marked musttail");
5613 
5614   // When long calls (i.e. indirect calls) are always used, calls are always
5615   // made via function pointer. If we have a function name, first translate it
5616   // into a pointer.
5617   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5618       !isTailCall)
5619     Callee = LowerGlobalAddress(Callee, DAG);
5620 
5621   CallFlags CFlags(
5622       CallConv, isTailCall, isVarArg, isPatchPoint,
5623       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5624       // hasNest
5625       Subtarget.is64BitELFABI() &&
5626           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5627       CLI.NoMerge);
5628 
5629   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5630     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5631                             InVals, CB);
5632 
5633   if (Subtarget.isSVR4ABI())
5634     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5635                             InVals, CB);
5636 
5637   if (Subtarget.isAIXABI())
5638     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5639                          InVals, CB);
5640 
5641   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5642                           InVals, CB);
5643 }
5644 
5645 SDValue PPCTargetLowering::LowerCall_32SVR4(
5646     SDValue Chain, SDValue Callee, CallFlags CFlags,
5647     const SmallVectorImpl<ISD::OutputArg> &Outs,
5648     const SmallVectorImpl<SDValue> &OutVals,
5649     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5650     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5651     const CallBase *CB) const {
5652   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5653   // of the 32-bit SVR4 ABI stack frame layout.
5654 
5655   const CallingConv::ID CallConv = CFlags.CallConv;
5656   const bool IsVarArg = CFlags.IsVarArg;
5657   const bool IsTailCall = CFlags.IsTailCall;
5658 
5659   assert((CallConv == CallingConv::C ||
5660           CallConv == CallingConv::Cold ||
5661           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5662 
5663   const Align PtrAlign(4);
5664 
5665   MachineFunction &MF = DAG.getMachineFunction();
5666 
5667   // Mark this function as potentially containing a function that contains a
5668   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5669   // and restoring the callers stack pointer in this functions epilog. This is
5670   // done because by tail calling the called function might overwrite the value
5671   // in this function's (MF) stack pointer stack slot 0(SP).
5672   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5673       CallConv == CallingConv::Fast)
5674     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5675 
5676   // Count how many bytes are to be pushed on the stack, including the linkage
5677   // area, parameter list area and the part of the local variable space which
5678   // contains copies of aggregates which are passed by value.
5679 
5680   // Assign locations to all of the outgoing arguments.
5681   SmallVector<CCValAssign, 16> ArgLocs;
5682   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5683 
5684   // Reserve space for the linkage area on the stack.
5685   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5686                        PtrAlign);
5687   if (useSoftFloat())
5688     CCInfo.PreAnalyzeCallOperands(Outs);
5689 
5690   if (IsVarArg) {
5691     // Handle fixed and variable vector arguments differently.
5692     // Fixed vector arguments go into registers as long as registers are
5693     // available. Variable vector arguments always go into memory.
5694     unsigned NumArgs = Outs.size();
5695 
5696     for (unsigned i = 0; i != NumArgs; ++i) {
5697       MVT ArgVT = Outs[i].VT;
5698       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5699       bool Result;
5700 
5701       if (Outs[i].IsFixed) {
5702         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5703                                CCInfo);
5704       } else {
5705         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5706                                       ArgFlags, CCInfo);
5707       }
5708 
5709       if (Result) {
5710 #ifndef NDEBUG
5711         errs() << "Call operand #" << i << " has unhandled type "
5712              << EVT(ArgVT).getEVTString() << "\n";
5713 #endif
5714         llvm_unreachable(nullptr);
5715       }
5716     }
5717   } else {
5718     // All arguments are treated the same.
5719     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5720   }
5721   CCInfo.clearWasPPCF128();
5722 
5723   // Assign locations to all of the outgoing aggregate by value arguments.
5724   SmallVector<CCValAssign, 16> ByValArgLocs;
5725   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5726 
5727   // Reserve stack space for the allocations in CCInfo.
5728   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5729 
5730   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5731 
5732   // Size of the linkage area, parameter list area and the part of the local
5733   // space variable where copies of aggregates which are passed by value are
5734   // stored.
5735   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5736 
5737   // Calculate by how many bytes the stack has to be adjusted in case of tail
5738   // call optimization.
5739   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5740 
5741   // Adjust the stack pointer for the new arguments...
5742   // These operations are automatically eliminated by the prolog/epilog pass
5743   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5744   SDValue CallSeqStart = Chain;
5745 
5746   // Load the return address and frame pointer so it can be moved somewhere else
5747   // later.
5748   SDValue LROp, FPOp;
5749   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5750 
5751   // Set up a copy of the stack pointer for use loading and storing any
5752   // arguments that may not fit in the registers available for argument
5753   // passing.
5754   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5755 
5756   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5757   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5758   SmallVector<SDValue, 8> MemOpChains;
5759 
5760   bool seenFloatArg = false;
5761   // Walk the register/memloc assignments, inserting copies/loads.
5762   // i - Tracks the index into the list of registers allocated for the call
5763   // RealArgIdx - Tracks the index into the list of actual function arguments
5764   // j - Tracks the index into the list of byval arguments
5765   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5766        i != e;
5767        ++i, ++RealArgIdx) {
5768     CCValAssign &VA = ArgLocs[i];
5769     SDValue Arg = OutVals[RealArgIdx];
5770     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5771 
5772     if (Flags.isByVal()) {
5773       // Argument is an aggregate which is passed by value, thus we need to
5774       // create a copy of it in the local variable space of the current stack
5775       // frame (which is the stack frame of the caller) and pass the address of
5776       // this copy to the callee.
5777       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5778       CCValAssign &ByValVA = ByValArgLocs[j++];
5779       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5780 
5781       // Memory reserved in the local variable space of the callers stack frame.
5782       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5783 
5784       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5785       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5786                            StackPtr, PtrOff);
5787 
5788       // Create a copy of the argument in the local area of the current
5789       // stack frame.
5790       SDValue MemcpyCall =
5791         CreateCopyOfByValArgument(Arg, PtrOff,
5792                                   CallSeqStart.getNode()->getOperand(0),
5793                                   Flags, DAG, dl);
5794 
5795       // This must go outside the CALLSEQ_START..END.
5796       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5797                                                      SDLoc(MemcpyCall));
5798       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5799                              NewCallSeqStart.getNode());
5800       Chain = CallSeqStart = NewCallSeqStart;
5801 
5802       // Pass the address of the aggregate copy on the stack either in a
5803       // physical register or in the parameter list area of the current stack
5804       // frame to the callee.
5805       Arg = PtrOff;
5806     }
5807 
5808     // When useCRBits() is true, there can be i1 arguments.
5809     // It is because getRegisterType(MVT::i1) => MVT::i1,
5810     // and for other integer types getRegisterType() => MVT::i32.
5811     // Extend i1 and ensure callee will get i32.
5812     if (Arg.getValueType() == MVT::i1)
5813       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5814                         dl, MVT::i32, Arg);
5815 
5816     if (VA.isRegLoc()) {
5817       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5818       // Put argument in a physical register.
5819       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5820         bool IsLE = Subtarget.isLittleEndian();
5821         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5822                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5823         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5824         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5825                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5826         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5827                              SVal.getValue(0)));
5828       } else
5829         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5830     } else {
5831       // Put argument in the parameter list area of the current stack frame.
5832       assert(VA.isMemLoc());
5833       unsigned LocMemOffset = VA.getLocMemOffset();
5834 
5835       if (!IsTailCall) {
5836         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5837         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5838                              StackPtr, PtrOff);
5839 
5840         MemOpChains.push_back(
5841             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5842       } else {
5843         // Calculate and remember argument location.
5844         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5845                                  TailCallArguments);
5846       }
5847     }
5848   }
5849 
5850   if (!MemOpChains.empty())
5851     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5852 
5853   // Build a sequence of copy-to-reg nodes chained together with token chain
5854   // and flag operands which copy the outgoing args into the appropriate regs.
5855   SDValue InFlag;
5856   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5857     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5858                              RegsToPass[i].second, InFlag);
5859     InFlag = Chain.getValue(1);
5860   }
5861 
5862   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5863   // registers.
5864   if (IsVarArg) {
5865     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5866     SDValue Ops[] = { Chain, InFlag };
5867 
5868     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5869                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5870 
5871     InFlag = Chain.getValue(1);
5872   }
5873 
5874   if (IsTailCall)
5875     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5876                     TailCallArguments);
5877 
5878   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5879                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5880 }
5881 
5882 // Copy an argument into memory, being careful to do this outside the
5883 // call sequence for the call to which the argument belongs.
5884 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5885     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5886     SelectionDAG &DAG, const SDLoc &dl) const {
5887   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5888                         CallSeqStart.getNode()->getOperand(0),
5889                         Flags, DAG, dl);
5890   // The MEMCPY must go outside the CALLSEQ_START..END.
5891   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5892   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5893                                                  SDLoc(MemcpyCall));
5894   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5895                          NewCallSeqStart.getNode());
5896   return NewCallSeqStart;
5897 }
5898 
5899 SDValue PPCTargetLowering::LowerCall_64SVR4(
5900     SDValue Chain, SDValue Callee, CallFlags CFlags,
5901     const SmallVectorImpl<ISD::OutputArg> &Outs,
5902     const SmallVectorImpl<SDValue> &OutVals,
5903     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5904     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5905     const CallBase *CB) const {
5906   bool isELFv2ABI = Subtarget.isELFv2ABI();
5907   bool isLittleEndian = Subtarget.isLittleEndian();
5908   unsigned NumOps = Outs.size();
5909   bool IsSibCall = false;
5910   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5911 
5912   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5913   unsigned PtrByteSize = 8;
5914 
5915   MachineFunction &MF = DAG.getMachineFunction();
5916 
5917   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5918     IsSibCall = true;
5919 
5920   // Mark this function as potentially containing a function that contains a
5921   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5922   // and restoring the callers stack pointer in this functions epilog. This is
5923   // done because by tail calling the called function might overwrite the value
5924   // in this function's (MF) stack pointer stack slot 0(SP).
5925   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5926     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5927 
5928   assert(!(IsFastCall && CFlags.IsVarArg) &&
5929          "fastcc not supported on varargs functions");
5930 
5931   // Count how many bytes are to be pushed on the stack, including the linkage
5932   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5933   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5934   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5935   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5936   unsigned NumBytes = LinkageSize;
5937   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5938 
5939   static const MCPhysReg GPR[] = {
5940     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5941     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5942   };
5943   static const MCPhysReg VR[] = {
5944     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5945     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5946   };
5947 
5948   const unsigned NumGPRs = array_lengthof(GPR);
5949   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5950   const unsigned NumVRs  = array_lengthof(VR);
5951 
5952   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5953   // can be passed to the callee in registers.
5954   // For the fast calling convention, there is another check below.
5955   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5956   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5957   if (!HasParameterArea) {
5958     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5959     unsigned AvailableFPRs = NumFPRs;
5960     unsigned AvailableVRs = NumVRs;
5961     unsigned NumBytesTmp = NumBytes;
5962     for (unsigned i = 0; i != NumOps; ++i) {
5963       if (Outs[i].Flags.isNest()) continue;
5964       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5965                                  PtrByteSize, LinkageSize, ParamAreaSize,
5966                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5967         HasParameterArea = true;
5968     }
5969   }
5970 
5971   // When using the fast calling convention, we don't provide backing for
5972   // arguments that will be in registers.
5973   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5974 
5975   // Avoid allocating parameter area for fastcc functions if all the arguments
5976   // can be passed in the registers.
5977   if (IsFastCall)
5978     HasParameterArea = false;
5979 
5980   // Add up all the space actually used.
5981   for (unsigned i = 0; i != NumOps; ++i) {
5982     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5983     EVT ArgVT = Outs[i].VT;
5984     EVT OrigVT = Outs[i].ArgVT;
5985 
5986     if (Flags.isNest())
5987       continue;
5988 
5989     if (IsFastCall) {
5990       if (Flags.isByVal()) {
5991         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5992         if (NumGPRsUsed > NumGPRs)
5993           HasParameterArea = true;
5994       } else {
5995         switch (ArgVT.getSimpleVT().SimpleTy) {
5996         default: llvm_unreachable("Unexpected ValueType for argument!");
5997         case MVT::i1:
5998         case MVT::i32:
5999         case MVT::i64:
6000           if (++NumGPRsUsed <= NumGPRs)
6001             continue;
6002           break;
6003         case MVT::v4i32:
6004         case MVT::v8i16:
6005         case MVT::v16i8:
6006         case MVT::v2f64:
6007         case MVT::v2i64:
6008         case MVT::v1i128:
6009         case MVT::f128:
6010           if (++NumVRsUsed <= NumVRs)
6011             continue;
6012           break;
6013         case MVT::v4f32:
6014           if (++NumVRsUsed <= NumVRs)
6015             continue;
6016           break;
6017         case MVT::f32:
6018         case MVT::f64:
6019           if (++NumFPRsUsed <= NumFPRs)
6020             continue;
6021           break;
6022         }
6023         HasParameterArea = true;
6024       }
6025     }
6026 
6027     /* Respect alignment of argument on the stack.  */
6028     auto Alignement =
6029         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6030     NumBytes = alignTo(NumBytes, Alignement);
6031 
6032     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6033     if (Flags.isInConsecutiveRegsLast())
6034       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6035   }
6036 
6037   unsigned NumBytesActuallyUsed = NumBytes;
6038 
6039   // In the old ELFv1 ABI,
6040   // the prolog code of the callee may store up to 8 GPR argument registers to
6041   // the stack, allowing va_start to index over them in memory if its varargs.
6042   // Because we cannot tell if this is needed on the caller side, we have to
6043   // conservatively assume that it is needed.  As such, make sure we have at
6044   // least enough stack space for the caller to store the 8 GPRs.
6045   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6046   // really requires memory operands, e.g. a vararg function.
6047   if (HasParameterArea)
6048     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6049   else
6050     NumBytes = LinkageSize;
6051 
6052   // Tail call needs the stack to be aligned.
6053   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6054     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6055 
6056   int SPDiff = 0;
6057 
6058   // Calculate by how many bytes the stack has to be adjusted in case of tail
6059   // call optimization.
6060   if (!IsSibCall)
6061     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6062 
6063   // To protect arguments on the stack from being clobbered in a tail call,
6064   // force all the loads to happen before doing any other lowering.
6065   if (CFlags.IsTailCall)
6066     Chain = DAG.getStackArgumentTokenFactor(Chain);
6067 
6068   // Adjust the stack pointer for the new arguments...
6069   // These operations are automatically eliminated by the prolog/epilog pass
6070   if (!IsSibCall)
6071     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6072   SDValue CallSeqStart = Chain;
6073 
6074   // Load the return address and frame pointer so it can be move somewhere else
6075   // later.
6076   SDValue LROp, FPOp;
6077   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6078 
6079   // Set up a copy of the stack pointer for use loading and storing any
6080   // arguments that may not fit in the registers available for argument
6081   // passing.
6082   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6083 
6084   // Figure out which arguments are going to go in registers, and which in
6085   // memory.  Also, if this is a vararg function, floating point operations
6086   // must be stored to our stack, and loaded into integer regs as well, if
6087   // any integer regs are available for argument passing.
6088   unsigned ArgOffset = LinkageSize;
6089 
6090   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6091   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6092 
6093   SmallVector<SDValue, 8> MemOpChains;
6094   for (unsigned i = 0; i != NumOps; ++i) {
6095     SDValue Arg = OutVals[i];
6096     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6097     EVT ArgVT = Outs[i].VT;
6098     EVT OrigVT = Outs[i].ArgVT;
6099 
6100     // PtrOff will be used to store the current argument to the stack if a
6101     // register cannot be found for it.
6102     SDValue PtrOff;
6103 
6104     // We re-align the argument offset for each argument, except when using the
6105     // fast calling convention, when we need to make sure we do that only when
6106     // we'll actually use a stack slot.
6107     auto ComputePtrOff = [&]() {
6108       /* Respect alignment of argument on the stack.  */
6109       auto Alignment =
6110           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6111       ArgOffset = alignTo(ArgOffset, Alignment);
6112 
6113       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6114 
6115       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6116     };
6117 
6118     if (!IsFastCall) {
6119       ComputePtrOff();
6120 
6121       /* Compute GPR index associated with argument offset.  */
6122       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6123       GPR_idx = std::min(GPR_idx, NumGPRs);
6124     }
6125 
6126     // Promote integers to 64-bit values.
6127     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6128       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6129       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6130       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6131     }
6132 
6133     // FIXME memcpy is used way more than necessary.  Correctness first.
6134     // Note: "by value" is code for passing a structure by value, not
6135     // basic types.
6136     if (Flags.isByVal()) {
6137       // Note: Size includes alignment padding, so
6138       //   struct x { short a; char b; }
6139       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6140       // These are the proper values we need for right-justifying the
6141       // aggregate in a parameter register.
6142       unsigned Size = Flags.getByValSize();
6143 
6144       // An empty aggregate parameter takes up no storage and no
6145       // registers.
6146       if (Size == 0)
6147         continue;
6148 
6149       if (IsFastCall)
6150         ComputePtrOff();
6151 
6152       // All aggregates smaller than 8 bytes must be passed right-justified.
6153       if (Size==1 || Size==2 || Size==4) {
6154         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6155         if (GPR_idx != NumGPRs) {
6156           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6157                                         MachinePointerInfo(), VT);
6158           MemOpChains.push_back(Load.getValue(1));
6159           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6160 
6161           ArgOffset += PtrByteSize;
6162           continue;
6163         }
6164       }
6165 
6166       if (GPR_idx == NumGPRs && Size < 8) {
6167         SDValue AddPtr = PtrOff;
6168         if (!isLittleEndian) {
6169           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6170                                           PtrOff.getValueType());
6171           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6172         }
6173         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6174                                                           CallSeqStart,
6175                                                           Flags, DAG, dl);
6176         ArgOffset += PtrByteSize;
6177         continue;
6178       }
6179       // Copy entire object into memory.  There are cases where gcc-generated
6180       // code assumes it is there, even if it could be put entirely into
6181       // registers.  (This is not what the doc says.)
6182 
6183       // FIXME: The above statement is likely due to a misunderstanding of the
6184       // documents.  All arguments must be copied into the parameter area BY
6185       // THE CALLEE in the event that the callee takes the address of any
6186       // formal argument.  That has not yet been implemented.  However, it is
6187       // reasonable to use the stack area as a staging area for the register
6188       // load.
6189 
6190       // Skip this for small aggregates, as we will use the same slot for a
6191       // right-justified copy, below.
6192       if (Size >= 8)
6193         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6194                                                           CallSeqStart,
6195                                                           Flags, DAG, dl);
6196 
6197       // When a register is available, pass a small aggregate right-justified.
6198       if (Size < 8 && GPR_idx != NumGPRs) {
6199         // The easiest way to get this right-justified in a register
6200         // is to copy the structure into the rightmost portion of a
6201         // local variable slot, then load the whole slot into the
6202         // register.
6203         // FIXME: The memcpy seems to produce pretty awful code for
6204         // small aggregates, particularly for packed ones.
6205         // FIXME: It would be preferable to use the slot in the
6206         // parameter save area instead of a new local variable.
6207         SDValue AddPtr = PtrOff;
6208         if (!isLittleEndian) {
6209           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6210           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6211         }
6212         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6213                                                           CallSeqStart,
6214                                                           Flags, DAG, dl);
6215 
6216         // Load the slot into the register.
6217         SDValue Load =
6218             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6219         MemOpChains.push_back(Load.getValue(1));
6220         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6221 
6222         // Done with this argument.
6223         ArgOffset += PtrByteSize;
6224         continue;
6225       }
6226 
6227       // For aggregates larger than PtrByteSize, copy the pieces of the
6228       // object that fit into registers from the parameter save area.
6229       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6230         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6231         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6232         if (GPR_idx != NumGPRs) {
6233           SDValue Load =
6234               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6235           MemOpChains.push_back(Load.getValue(1));
6236           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6237           ArgOffset += PtrByteSize;
6238         } else {
6239           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6240           break;
6241         }
6242       }
6243       continue;
6244     }
6245 
6246     switch (Arg.getSimpleValueType().SimpleTy) {
6247     default: llvm_unreachable("Unexpected ValueType for argument!");
6248     case MVT::i1:
6249     case MVT::i32:
6250     case MVT::i64:
6251       if (Flags.isNest()) {
6252         // The 'nest' parameter, if any, is passed in R11.
6253         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6254         break;
6255       }
6256 
6257       // These can be scalar arguments or elements of an integer array type
6258       // passed directly.  Clang may use those instead of "byval" aggregate
6259       // types to avoid forcing arguments to memory unnecessarily.
6260       if (GPR_idx != NumGPRs) {
6261         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6262       } else {
6263         if (IsFastCall)
6264           ComputePtrOff();
6265 
6266         assert(HasParameterArea &&
6267                "Parameter area must exist to pass an argument in memory.");
6268         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6269                          true, CFlags.IsTailCall, false, MemOpChains,
6270                          TailCallArguments, dl);
6271         if (IsFastCall)
6272           ArgOffset += PtrByteSize;
6273       }
6274       if (!IsFastCall)
6275         ArgOffset += PtrByteSize;
6276       break;
6277     case MVT::f32:
6278     case MVT::f64: {
6279       // These can be scalar arguments or elements of a float array type
6280       // passed directly.  The latter are used to implement ELFv2 homogenous
6281       // float aggregates.
6282 
6283       // Named arguments go into FPRs first, and once they overflow, the
6284       // remaining arguments go into GPRs and then the parameter save area.
6285       // Unnamed arguments for vararg functions always go to GPRs and
6286       // then the parameter save area.  For now, put all arguments to vararg
6287       // routines always in both locations (FPR *and* GPR or stack slot).
6288       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6289       bool NeededLoad = false;
6290 
6291       // First load the argument into the next available FPR.
6292       if (FPR_idx != NumFPRs)
6293         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6294 
6295       // Next, load the argument into GPR or stack slot if needed.
6296       if (!NeedGPROrStack)
6297         ;
6298       else if (GPR_idx != NumGPRs && !IsFastCall) {
6299         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6300         // once we support fp <-> gpr moves.
6301 
6302         // In the non-vararg case, this can only ever happen in the
6303         // presence of f32 array types, since otherwise we never run
6304         // out of FPRs before running out of GPRs.
6305         SDValue ArgVal;
6306 
6307         // Double values are always passed in a single GPR.
6308         if (Arg.getValueType() != MVT::f32) {
6309           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6310 
6311         // Non-array float values are extended and passed in a GPR.
6312         } else if (!Flags.isInConsecutiveRegs()) {
6313           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6314           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6315 
6316         // If we have an array of floats, we collect every odd element
6317         // together with its predecessor into one GPR.
6318         } else if (ArgOffset % PtrByteSize != 0) {
6319           SDValue Lo, Hi;
6320           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6321           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6322           if (!isLittleEndian)
6323             std::swap(Lo, Hi);
6324           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6325 
6326         // The final element, if even, goes into the first half of a GPR.
6327         } else if (Flags.isInConsecutiveRegsLast()) {
6328           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6329           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6330           if (!isLittleEndian)
6331             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6332                                  DAG.getConstant(32, dl, MVT::i32));
6333 
6334         // Non-final even elements are skipped; they will be handled
6335         // together the with subsequent argument on the next go-around.
6336         } else
6337           ArgVal = SDValue();
6338 
6339         if (ArgVal.getNode())
6340           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6341       } else {
6342         if (IsFastCall)
6343           ComputePtrOff();
6344 
6345         // Single-precision floating-point values are mapped to the
6346         // second (rightmost) word of the stack doubleword.
6347         if (Arg.getValueType() == MVT::f32 &&
6348             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6349           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6350           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6351         }
6352 
6353         assert(HasParameterArea &&
6354                "Parameter area must exist to pass an argument in memory.");
6355         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6356                          true, CFlags.IsTailCall, false, MemOpChains,
6357                          TailCallArguments, dl);
6358 
6359         NeededLoad = true;
6360       }
6361       // When passing an array of floats, the array occupies consecutive
6362       // space in the argument area; only round up to the next doubleword
6363       // at the end of the array.  Otherwise, each float takes 8 bytes.
6364       if (!IsFastCall || NeededLoad) {
6365         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6366                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6367         if (Flags.isInConsecutiveRegsLast())
6368           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6369       }
6370       break;
6371     }
6372     case MVT::v4f32:
6373     case MVT::v4i32:
6374     case MVT::v8i16:
6375     case MVT::v16i8:
6376     case MVT::v2f64:
6377     case MVT::v2i64:
6378     case MVT::v1i128:
6379     case MVT::f128:
6380       // These can be scalar arguments or elements of a vector array type
6381       // passed directly.  The latter are used to implement ELFv2 homogenous
6382       // vector aggregates.
6383 
6384       // For a varargs call, named arguments go into VRs or on the stack as
6385       // usual; unnamed arguments always go to the stack or the corresponding
6386       // GPRs when within range.  For now, we always put the value in both
6387       // locations (or even all three).
6388       if (CFlags.IsVarArg) {
6389         assert(HasParameterArea &&
6390                "Parameter area must exist if we have a varargs call.");
6391         // We could elide this store in the case where the object fits
6392         // entirely in R registers.  Maybe later.
6393         SDValue Store =
6394             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6395         MemOpChains.push_back(Store);
6396         if (VR_idx != NumVRs) {
6397           SDValue Load =
6398               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6399           MemOpChains.push_back(Load.getValue(1));
6400           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6401         }
6402         ArgOffset += 16;
6403         for (unsigned i=0; i<16; i+=PtrByteSize) {
6404           if (GPR_idx == NumGPRs)
6405             break;
6406           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6407                                    DAG.getConstant(i, dl, PtrVT));
6408           SDValue Load =
6409               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6410           MemOpChains.push_back(Load.getValue(1));
6411           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6412         }
6413         break;
6414       }
6415 
6416       // Non-varargs Altivec params go into VRs or on the stack.
6417       if (VR_idx != NumVRs) {
6418         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6419       } else {
6420         if (IsFastCall)
6421           ComputePtrOff();
6422 
6423         assert(HasParameterArea &&
6424                "Parameter area must exist to pass an argument in memory.");
6425         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6426                          true, CFlags.IsTailCall, true, MemOpChains,
6427                          TailCallArguments, dl);
6428         if (IsFastCall)
6429           ArgOffset += 16;
6430       }
6431 
6432       if (!IsFastCall)
6433         ArgOffset += 16;
6434       break;
6435     }
6436   }
6437 
6438   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6439          "mismatch in size of parameter area");
6440   (void)NumBytesActuallyUsed;
6441 
6442   if (!MemOpChains.empty())
6443     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6444 
6445   // Check if this is an indirect call (MTCTR/BCTRL).
6446   // See prepareDescriptorIndirectCall and buildCallOperands for more
6447   // information about calls through function pointers in the 64-bit SVR4 ABI.
6448   if (CFlags.IsIndirect) {
6449     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6450     // caller in the TOC save area.
6451     if (isTOCSaveRestoreRequired(Subtarget)) {
6452       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6453       // Load r2 into a virtual register and store it to the TOC save area.
6454       setUsesTOCBasePtr(DAG);
6455       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6456       // TOC save area offset.
6457       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6458       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6459       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6460       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6461                            MachinePointerInfo::getStack(
6462                                DAG.getMachineFunction(), TOCSaveOffset));
6463     }
6464     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6465     // This does not mean the MTCTR instruction must use R12; it's easier
6466     // to model this as an extra parameter, so do that.
6467     if (isELFv2ABI && !CFlags.IsPatchPoint)
6468       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6469   }
6470 
6471   // Build a sequence of copy-to-reg nodes chained together with token chain
6472   // and flag operands which copy the outgoing args into the appropriate regs.
6473   SDValue InFlag;
6474   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6475     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6476                              RegsToPass[i].second, InFlag);
6477     InFlag = Chain.getValue(1);
6478   }
6479 
6480   if (CFlags.IsTailCall && !IsSibCall)
6481     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6482                     TailCallArguments);
6483 
6484   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6485                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6486 }
6487 
6488 SDValue PPCTargetLowering::LowerCall_Darwin(
6489     SDValue Chain, SDValue Callee, CallFlags CFlags,
6490     const SmallVectorImpl<ISD::OutputArg> &Outs,
6491     const SmallVectorImpl<SDValue> &OutVals,
6492     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6493     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6494     const CallBase *CB) const {
6495   unsigned NumOps = Outs.size();
6496 
6497   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6498   bool isPPC64 = PtrVT == MVT::i64;
6499   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6500 
6501   MachineFunction &MF = DAG.getMachineFunction();
6502 
6503   // Mark this function as potentially containing a function that contains a
6504   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6505   // and restoring the callers stack pointer in this functions epilog. This is
6506   // done because by tail calling the called function might overwrite the value
6507   // in this function's (MF) stack pointer stack slot 0(SP).
6508   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6509       CFlags.CallConv == CallingConv::Fast)
6510     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6511 
6512   // Count how many bytes are to be pushed on the stack, including the linkage
6513   // area, and parameter passing area.  We start with 24/48 bytes, which is
6514   // prereserved space for [SP][CR][LR][3 x unused].
6515   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6516   unsigned NumBytes = LinkageSize;
6517 
6518   // Add up all the space actually used.
6519   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6520   // they all go in registers, but we must reserve stack space for them for
6521   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6522   // assigned stack space in order, with padding so Altivec parameters are
6523   // 16-byte aligned.
6524   unsigned nAltivecParamsAtEnd = 0;
6525   for (unsigned i = 0; i != NumOps; ++i) {
6526     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6527     EVT ArgVT = Outs[i].VT;
6528     // Varargs Altivec parameters are padded to a 16 byte boundary.
6529     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6530         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6531         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6532       if (!CFlags.IsVarArg && !isPPC64) {
6533         // Non-varargs Altivec parameters go after all the non-Altivec
6534         // parameters; handle those later so we know how much padding we need.
6535         nAltivecParamsAtEnd++;
6536         continue;
6537       }
6538       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6539       NumBytes = ((NumBytes+15)/16)*16;
6540     }
6541     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6542   }
6543 
6544   // Allow for Altivec parameters at the end, if needed.
6545   if (nAltivecParamsAtEnd) {
6546     NumBytes = ((NumBytes+15)/16)*16;
6547     NumBytes += 16*nAltivecParamsAtEnd;
6548   }
6549 
6550   // The prolog code of the callee may store up to 8 GPR argument registers to
6551   // the stack, allowing va_start to index over them in memory if its varargs.
6552   // Because we cannot tell if this is needed on the caller side, we have to
6553   // conservatively assume that it is needed.  As such, make sure we have at
6554   // least enough stack space for the caller to store the 8 GPRs.
6555   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6556 
6557   // Tail call needs the stack to be aligned.
6558   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6559       CFlags.CallConv == CallingConv::Fast)
6560     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6561 
6562   // Calculate by how many bytes the stack has to be adjusted in case of tail
6563   // call optimization.
6564   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6565 
6566   // To protect arguments on the stack from being clobbered in a tail call,
6567   // force all the loads to happen before doing any other lowering.
6568   if (CFlags.IsTailCall)
6569     Chain = DAG.getStackArgumentTokenFactor(Chain);
6570 
6571   // Adjust the stack pointer for the new arguments...
6572   // These operations are automatically eliminated by the prolog/epilog pass
6573   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6574   SDValue CallSeqStart = Chain;
6575 
6576   // Load the return address and frame pointer so it can be move somewhere else
6577   // later.
6578   SDValue LROp, FPOp;
6579   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6580 
6581   // Set up a copy of the stack pointer for use loading and storing any
6582   // arguments that may not fit in the registers available for argument
6583   // passing.
6584   SDValue StackPtr;
6585   if (isPPC64)
6586     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6587   else
6588     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6589 
6590   // Figure out which arguments are going to go in registers, and which in
6591   // memory.  Also, if this is a vararg function, floating point operations
6592   // must be stored to our stack, and loaded into integer regs as well, if
6593   // any integer regs are available for argument passing.
6594   unsigned ArgOffset = LinkageSize;
6595   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6596 
6597   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6598     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6599     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6600   };
6601   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6602     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6603     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6604   };
6605   static const MCPhysReg VR[] = {
6606     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6607     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6608   };
6609   const unsigned NumGPRs = array_lengthof(GPR_32);
6610   const unsigned NumFPRs = 13;
6611   const unsigned NumVRs  = array_lengthof(VR);
6612 
6613   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6614 
6615   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6616   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6617 
6618   SmallVector<SDValue, 8> MemOpChains;
6619   for (unsigned i = 0; i != NumOps; ++i) {
6620     SDValue Arg = OutVals[i];
6621     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6622 
6623     // PtrOff will be used to store the current argument to the stack if a
6624     // register cannot be found for it.
6625     SDValue PtrOff;
6626 
6627     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6628 
6629     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6630 
6631     // On PPC64, promote integers to 64-bit values.
6632     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6633       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6634       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6635       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6636     }
6637 
6638     // FIXME memcpy is used way more than necessary.  Correctness first.
6639     // Note: "by value" is code for passing a structure by value, not
6640     // basic types.
6641     if (Flags.isByVal()) {
6642       unsigned Size = Flags.getByValSize();
6643       // Very small objects are passed right-justified.  Everything else is
6644       // passed left-justified.
6645       if (Size==1 || Size==2) {
6646         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6647         if (GPR_idx != NumGPRs) {
6648           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6649                                         MachinePointerInfo(), VT);
6650           MemOpChains.push_back(Load.getValue(1));
6651           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6652 
6653           ArgOffset += PtrByteSize;
6654         } else {
6655           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6656                                           PtrOff.getValueType());
6657           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6658           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6659                                                             CallSeqStart,
6660                                                             Flags, DAG, dl);
6661           ArgOffset += PtrByteSize;
6662         }
6663         continue;
6664       }
6665       // Copy entire object into memory.  There are cases where gcc-generated
6666       // code assumes it is there, even if it could be put entirely into
6667       // registers.  (This is not what the doc says.)
6668       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6669                                                         CallSeqStart,
6670                                                         Flags, DAG, dl);
6671 
6672       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6673       // copy the pieces of the object that fit into registers from the
6674       // parameter save area.
6675       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6676         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6677         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6678         if (GPR_idx != NumGPRs) {
6679           SDValue Load =
6680               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6681           MemOpChains.push_back(Load.getValue(1));
6682           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6683           ArgOffset += PtrByteSize;
6684         } else {
6685           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6686           break;
6687         }
6688       }
6689       continue;
6690     }
6691 
6692     switch (Arg.getSimpleValueType().SimpleTy) {
6693     default: llvm_unreachable("Unexpected ValueType for argument!");
6694     case MVT::i1:
6695     case MVT::i32:
6696     case MVT::i64:
6697       if (GPR_idx != NumGPRs) {
6698         if (Arg.getValueType() == MVT::i1)
6699           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6700 
6701         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6702       } else {
6703         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6704                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6705                          TailCallArguments, dl);
6706       }
6707       ArgOffset += PtrByteSize;
6708       break;
6709     case MVT::f32:
6710     case MVT::f64:
6711       if (FPR_idx != NumFPRs) {
6712         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6713 
6714         if (CFlags.IsVarArg) {
6715           SDValue Store =
6716               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6717           MemOpChains.push_back(Store);
6718 
6719           // Float varargs are always shadowed in available integer registers
6720           if (GPR_idx != NumGPRs) {
6721             SDValue Load =
6722                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6723             MemOpChains.push_back(Load.getValue(1));
6724             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6725           }
6726           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6727             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6728             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6729             SDValue Load =
6730                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6731             MemOpChains.push_back(Load.getValue(1));
6732             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6733           }
6734         } else {
6735           // If we have any FPRs remaining, we may also have GPRs remaining.
6736           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6737           // GPRs.
6738           if (GPR_idx != NumGPRs)
6739             ++GPR_idx;
6740           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6741               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6742             ++GPR_idx;
6743         }
6744       } else
6745         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6746                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6747                          TailCallArguments, dl);
6748       if (isPPC64)
6749         ArgOffset += 8;
6750       else
6751         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6752       break;
6753     case MVT::v4f32:
6754     case MVT::v4i32:
6755     case MVT::v8i16:
6756     case MVT::v16i8:
6757       if (CFlags.IsVarArg) {
6758         // These go aligned on the stack, or in the corresponding R registers
6759         // when within range.  The Darwin PPC ABI doc claims they also go in
6760         // V registers; in fact gcc does this only for arguments that are
6761         // prototyped, not for those that match the ...  We do it for all
6762         // arguments, seems to work.
6763         while (ArgOffset % 16 !=0) {
6764           ArgOffset += PtrByteSize;
6765           if (GPR_idx != NumGPRs)
6766             GPR_idx++;
6767         }
6768         // We could elide this store in the case where the object fits
6769         // entirely in R registers.  Maybe later.
6770         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6771                              DAG.getConstant(ArgOffset, dl, PtrVT));
6772         SDValue Store =
6773             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6774         MemOpChains.push_back(Store);
6775         if (VR_idx != NumVRs) {
6776           SDValue Load =
6777               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6778           MemOpChains.push_back(Load.getValue(1));
6779           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6780         }
6781         ArgOffset += 16;
6782         for (unsigned i=0; i<16; i+=PtrByteSize) {
6783           if (GPR_idx == NumGPRs)
6784             break;
6785           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6786                                    DAG.getConstant(i, dl, PtrVT));
6787           SDValue Load =
6788               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6789           MemOpChains.push_back(Load.getValue(1));
6790           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6791         }
6792         break;
6793       }
6794 
6795       // Non-varargs Altivec params generally go in registers, but have
6796       // stack space allocated at the end.
6797       if (VR_idx != NumVRs) {
6798         // Doesn't have GPR space allocated.
6799         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6800       } else if (nAltivecParamsAtEnd==0) {
6801         // We are emitting Altivec params in order.
6802         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6803                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6804                          TailCallArguments, dl);
6805         ArgOffset += 16;
6806       }
6807       break;
6808     }
6809   }
6810   // If all Altivec parameters fit in registers, as they usually do,
6811   // they get stack space following the non-Altivec parameters.  We
6812   // don't track this here because nobody below needs it.
6813   // If there are more Altivec parameters than fit in registers emit
6814   // the stores here.
6815   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6816     unsigned j = 0;
6817     // Offset is aligned; skip 1st 12 params which go in V registers.
6818     ArgOffset = ((ArgOffset+15)/16)*16;
6819     ArgOffset += 12*16;
6820     for (unsigned i = 0; i != NumOps; ++i) {
6821       SDValue Arg = OutVals[i];
6822       EVT ArgType = Outs[i].VT;
6823       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6824           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6825         if (++j > NumVRs) {
6826           SDValue PtrOff;
6827           // We are emitting Altivec params in order.
6828           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6829                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6830                            TailCallArguments, dl);
6831           ArgOffset += 16;
6832         }
6833       }
6834     }
6835   }
6836 
6837   if (!MemOpChains.empty())
6838     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6839 
6840   // On Darwin, R12 must contain the address of an indirect callee.  This does
6841   // not mean the MTCTR instruction must use R12; it's easier to model this as
6842   // an extra parameter, so do that.
6843   if (CFlags.IsIndirect) {
6844     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6845     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6846                                                    PPC::R12), Callee));
6847   }
6848 
6849   // Build a sequence of copy-to-reg nodes chained together with token chain
6850   // and flag operands which copy the outgoing args into the appropriate regs.
6851   SDValue InFlag;
6852   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6853     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6854                              RegsToPass[i].second, InFlag);
6855     InFlag = Chain.getValue(1);
6856   }
6857 
6858   if (CFlags.IsTailCall)
6859     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6860                     TailCallArguments);
6861 
6862   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6863                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6864 }
6865 
6866 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6867                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6868                    CCState &State) {
6869 
6870   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6871       State.getMachineFunction().getSubtarget());
6872   const bool IsPPC64 = Subtarget.isPPC64();
6873   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6874   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6875 
6876   assert((!ValVT.isInteger() ||
6877           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6878          "Integer argument exceeds register size: should have been legalized");
6879 
6880   if (ValVT == MVT::f128)
6881     report_fatal_error("f128 is unimplemented on AIX.");
6882 
6883   if (ArgFlags.isNest())
6884     report_fatal_error("Nest arguments are unimplemented.");
6885 
6886   if (ValVT.isVector() || LocVT.isVector())
6887     report_fatal_error("Vector arguments are unimplemented on AIX.");
6888 
6889   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6890                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6891                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6892   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6893                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6894                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6895 
6896   if (ArgFlags.isByVal()) {
6897     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6898       report_fatal_error("Pass-by-value arguments with alignment greater than "
6899                          "register width are not supported.");
6900 
6901     const unsigned ByValSize = ArgFlags.getByValSize();
6902 
6903     // An empty aggregate parameter takes up no storage and no registers,
6904     // but needs a MemLoc for a stack slot for the formal arguments side.
6905     if (ByValSize == 0) {
6906       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6907                                        State.getNextStackOffset(), RegVT,
6908                                        LocInfo));
6909       return false;
6910     }
6911 
6912     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6913     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6914     for (const unsigned E = Offset + StackSize; Offset < E;
6915          Offset += PtrAlign.value()) {
6916       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6917         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6918       else {
6919         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6920                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6921                                          LocInfo));
6922         break;
6923       }
6924     }
6925     return false;
6926   }
6927 
6928   // Arguments always reserve parameter save area.
6929   switch (ValVT.SimpleTy) {
6930   default:
6931     report_fatal_error("Unhandled value type for argument.");
6932   case MVT::i64:
6933     // i64 arguments should have been split to i32 for PPC32.
6934     assert(IsPPC64 && "PPC32 should have split i64 values.");
6935     LLVM_FALLTHROUGH;
6936   case MVT::i1:
6937   case MVT::i32: {
6938     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6939     // AIX integer arguments are always passed in register width.
6940     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6941       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6942                                   : CCValAssign::LocInfo::ZExt;
6943     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6944       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6945     else
6946       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6947 
6948     return false;
6949   }
6950   case MVT::f32:
6951   case MVT::f64: {
6952     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6953     const unsigned StoreSize = LocVT.getStoreSize();
6954     // Floats are always 4-byte aligned in the PSA on AIX.
6955     // This includes f64 in 64-bit mode for ABI compatibility.
6956     const unsigned Offset =
6957         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6958     unsigned FReg = State.AllocateReg(FPR);
6959     if (FReg)
6960       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6961 
6962     // Reserve and initialize GPRs or initialize the PSA as required.
6963     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6964       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6965         assert(FReg && "An FPR should be available when a GPR is reserved.");
6966         if (State.isVarArg()) {
6967           // Successfully reserved GPRs are only initialized for vararg calls.
6968           // Custom handling is required for:
6969           //   f64 in PPC32 needs to be split into 2 GPRs.
6970           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6971           State.addLoc(
6972               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6973         }
6974       } else {
6975         // If there are insufficient GPRs, the PSA needs to be initialized.
6976         // Initialization occurs even if an FPR was initialized for
6977         // compatibility with the AIX XL compiler. The full memory for the
6978         // argument will be initialized even if a prior word is saved in GPR.
6979         // A custom memLoc is used when the argument also passes in FPR so
6980         // that the callee handling can skip over it easily.
6981         State.addLoc(
6982             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6983                                              LocInfo)
6984                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6985         break;
6986       }
6987     }
6988 
6989     return false;
6990   }
6991   }
6992   return true;
6993 }
6994 
6995 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6996                                                     bool IsPPC64) {
6997   assert((IsPPC64 || SVT != MVT::i64) &&
6998          "i64 should have been split for 32-bit codegen.");
6999 
7000   switch (SVT) {
7001   default:
7002     report_fatal_error("Unexpected value type for formal argument");
7003   case MVT::i1:
7004   case MVT::i32:
7005   case MVT::i64:
7006     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7007   case MVT::f32:
7008     return &PPC::F4RCRegClass;
7009   case MVT::f64:
7010     return &PPC::F8RCRegClass;
7011   }
7012 }
7013 
7014 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
7015                                         SelectionDAG &DAG, SDValue ArgValue,
7016                                         MVT LocVT, const SDLoc &dl) {
7017   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7018   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
7019 
7020   if (Flags.isSExt())
7021     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7022                            DAG.getValueType(ValVT));
7023   else if (Flags.isZExt())
7024     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7025                            DAG.getValueType(ValVT));
7026 
7027   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7028 }
7029 
7030 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7031   const unsigned LASize = FL->getLinkageSize();
7032 
7033   if (PPC::GPRCRegClass.contains(Reg)) {
7034     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7035            "Reg must be a valid argument register!");
7036     return LASize + 4 * (Reg - PPC::R3);
7037   }
7038 
7039   if (PPC::G8RCRegClass.contains(Reg)) {
7040     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7041            "Reg must be a valid argument register!");
7042     return LASize + 8 * (Reg - PPC::X3);
7043   }
7044 
7045   llvm_unreachable("Only general purpose registers expected.");
7046 }
7047 
7048 //   AIX ABI Stack Frame Layout:
7049 //
7050 //   Low Memory +--------------------------------------------+
7051 //   SP   +---> | Back chain                                 | ---+
7052 //        |     +--------------------------------------------+    |
7053 //        |     | Saved Condition Register                   |    |
7054 //        |     +--------------------------------------------+    |
7055 //        |     | Saved Linkage Register                     |    |
7056 //        |     +--------------------------------------------+    | Linkage Area
7057 //        |     | Reserved for compilers                     |    |
7058 //        |     +--------------------------------------------+    |
7059 //        |     | Reserved for binders                       |    |
7060 //        |     +--------------------------------------------+    |
7061 //        |     | Saved TOC pointer                          | ---+
7062 //        |     +--------------------------------------------+
7063 //        |     | Parameter save area                        |
7064 //        |     +--------------------------------------------+
7065 //        |     | Alloca space                               |
7066 //        |     +--------------------------------------------+
7067 //        |     | Local variable space                       |
7068 //        |     +--------------------------------------------+
7069 //        |     | Float/int conversion temporary             |
7070 //        |     +--------------------------------------------+
7071 //        |     | Save area for AltiVec registers            |
7072 //        |     +--------------------------------------------+
7073 //        |     | AltiVec alignment padding                  |
7074 //        |     +--------------------------------------------+
7075 //        |     | Save area for VRSAVE register              |
7076 //        |     +--------------------------------------------+
7077 //        |     | Save area for General Purpose registers    |
7078 //        |     +--------------------------------------------+
7079 //        |     | Save area for Floating Point registers     |
7080 //        |     +--------------------------------------------+
7081 //        +---- | Back chain                                 |
7082 // High Memory  +--------------------------------------------+
7083 //
7084 //  Specifications:
7085 //  AIX 7.2 Assembler Language Reference
7086 //  Subroutine linkage convention
7087 
7088 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7089     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7090     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7091     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7092 
7093   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7094           CallConv == CallingConv::Fast) &&
7095          "Unexpected calling convention!");
7096 
7097   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7098     report_fatal_error("Tail call support is unimplemented on AIX.");
7099 
7100   if (useSoftFloat())
7101     report_fatal_error("Soft float support is unimplemented on AIX.");
7102 
7103   const PPCSubtarget &Subtarget =
7104       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7105 
7106   const bool IsPPC64 = Subtarget.isPPC64();
7107   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7108 
7109   // Assign locations to all of the incoming arguments.
7110   SmallVector<CCValAssign, 16> ArgLocs;
7111   MachineFunction &MF = DAG.getMachineFunction();
7112   MachineFrameInfo &MFI = MF.getFrameInfo();
7113   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7114 
7115   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7116   // Reserve space for the linkage area on the stack.
7117   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7118   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7119   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7120 
7121   SmallVector<SDValue, 8> MemOps;
7122 
7123   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7124     CCValAssign &VA = ArgLocs[I++];
7125     MVT LocVT = VA.getLocVT();
7126     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7127 
7128     // For compatibility with the AIX XL compiler, the float args in the
7129     // parameter save area are initialized even if the argument is available
7130     // in register.  The caller is required to initialize both the register
7131     // and memory, however, the callee can choose to expect it in either.
7132     // The memloc is dismissed here because the argument is retrieved from
7133     // the register.
7134     if (VA.isMemLoc() && VA.needsCustom())
7135       continue;
7136 
7137     if (Flags.isByVal() && VA.isMemLoc()) {
7138       const unsigned Size =
7139           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7140                   PtrByteSize);
7141       const int FI = MF.getFrameInfo().CreateFixedObject(
7142           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7143           /* IsAliased */ true);
7144       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7145       InVals.push_back(FIN);
7146 
7147       continue;
7148     }
7149 
7150     if (Flags.isByVal()) {
7151       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7152 
7153       const MCPhysReg ArgReg = VA.getLocReg();
7154       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7155 
7156       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7157         report_fatal_error("Over aligned byvals not supported yet.");
7158 
7159       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7160       const int FI = MF.getFrameInfo().CreateFixedObject(
7161           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7162           /* IsAliased */ true);
7163       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7164       InVals.push_back(FIN);
7165 
7166       // Add live ins for all the RegLocs for the same ByVal.
7167       const TargetRegisterClass *RegClass =
7168           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7169 
7170       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7171                                                unsigned Offset) {
7172         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7173         // Since the callers side has left justified the aggregate in the
7174         // register, we can simply store the entire register into the stack
7175         // slot.
7176         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7177         // The store to the fixedstack object is needed becuase accessing a
7178         // field of the ByVal will use a gep and load. Ideally we will optimize
7179         // to extracting the value from the register directly, and elide the
7180         // stores when the arguments address is not taken, but that will need to
7181         // be future work.
7182         SDValue Store = DAG.getStore(
7183             CopyFrom.getValue(1), dl, CopyFrom,
7184             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7185             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7186 
7187         MemOps.push_back(Store);
7188       };
7189 
7190       unsigned Offset = 0;
7191       HandleRegLoc(VA.getLocReg(), Offset);
7192       Offset += PtrByteSize;
7193       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7194            Offset += PtrByteSize) {
7195         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7196                "RegLocs should be for ByVal argument.");
7197 
7198         const CCValAssign RL = ArgLocs[I++];
7199         HandleRegLoc(RL.getLocReg(), Offset);
7200       }
7201 
7202       if (Offset != StackSize) {
7203         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7204                "Expected MemLoc for remaining bytes.");
7205         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7206         // Consume the MemLoc.The InVal has already been emitted, so nothing
7207         // more needs to be done.
7208         ++I;
7209       }
7210 
7211       continue;
7212     }
7213 
7214     EVT ValVT = VA.getValVT();
7215     if (VA.isRegLoc() && !VA.needsCustom()) {
7216       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7217       unsigned VReg =
7218           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7219       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7220       if (ValVT.isScalarInteger() &&
7221           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7222         ArgValue =
7223             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7224       }
7225       InVals.push_back(ArgValue);
7226       continue;
7227     }
7228     if (VA.isMemLoc()) {
7229       const unsigned LocSize = LocVT.getStoreSize();
7230       const unsigned ValSize = ValVT.getStoreSize();
7231       assert((ValSize <= LocSize) &&
7232              "Object size is larger than size of MemLoc");
7233       int CurArgOffset = VA.getLocMemOffset();
7234       // Objects are right-justified because AIX is big-endian.
7235       if (LocSize > ValSize)
7236         CurArgOffset += LocSize - ValSize;
7237       // Potential tail calls could cause overwriting of argument stack slots.
7238       const bool IsImmutable =
7239           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7240             (CallConv == CallingConv::Fast));
7241       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7242       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7243       SDValue ArgValue =
7244           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7245       InVals.push_back(ArgValue);
7246       continue;
7247     }
7248   }
7249 
7250   // On AIX a minimum of 8 words is saved to the parameter save area.
7251   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7252   // Area that is at least reserved in the caller of this function.
7253   unsigned CallerReservedArea =
7254       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7255 
7256   // Set the size that is at least reserved in caller of this function. Tail
7257   // call optimized function's reserved stack space needs to be aligned so
7258   // that taking the difference between two stack areas will result in an
7259   // aligned stack.
7260   CallerReservedArea =
7261       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7262   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7263   FuncInfo->setMinReservedArea(CallerReservedArea);
7264 
7265   if (isVarArg) {
7266     FuncInfo->setVarArgsFrameIndex(
7267         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7268     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7269 
7270     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7271                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7272 
7273     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7274                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7275     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7276 
7277     // The fixed integer arguments of a variadic function are stored to the
7278     // VarArgsFrameIndex on the stack so that they may be loaded by
7279     // dereferencing the result of va_next.
7280     for (unsigned GPRIndex =
7281              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7282          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7283 
7284       const unsigned VReg =
7285           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7286                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7287 
7288       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7289       SDValue Store =
7290           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7291       MemOps.push_back(Store);
7292       // Increment the address for the next argument to store.
7293       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7294       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7295     }
7296   }
7297 
7298   if (!MemOps.empty())
7299     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7300 
7301   return Chain;
7302 }
7303 
7304 SDValue PPCTargetLowering::LowerCall_AIX(
7305     SDValue Chain, SDValue Callee, CallFlags CFlags,
7306     const SmallVectorImpl<ISD::OutputArg> &Outs,
7307     const SmallVectorImpl<SDValue> &OutVals,
7308     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7309     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7310     const CallBase *CB) const {
7311   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7312   // AIX ABI stack frame layout.
7313 
7314   assert((CFlags.CallConv == CallingConv::C ||
7315           CFlags.CallConv == CallingConv::Cold ||
7316           CFlags.CallConv == CallingConv::Fast) &&
7317          "Unexpected calling convention!");
7318 
7319   if (CFlags.IsPatchPoint)
7320     report_fatal_error("This call type is unimplemented on AIX.");
7321 
7322   const PPCSubtarget& Subtarget =
7323       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7324   if (Subtarget.hasAltivec())
7325     report_fatal_error("Altivec support is unimplemented on AIX.");
7326 
7327   MachineFunction &MF = DAG.getMachineFunction();
7328   SmallVector<CCValAssign, 16> ArgLocs;
7329   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7330                  *DAG.getContext());
7331 
7332   // Reserve space for the linkage save area (LSA) on the stack.
7333   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7334   //   [SP][CR][LR][2 x reserved][TOC].
7335   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7336   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7337   const bool IsPPC64 = Subtarget.isPPC64();
7338   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7339   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7340   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7341   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7342 
7343   // The prolog code of the callee may store up to 8 GPR argument registers to
7344   // the stack, allowing va_start to index over them in memory if the callee
7345   // is variadic.
7346   // Because we cannot tell if this is needed on the caller side, we have to
7347   // conservatively assume that it is needed.  As such, make sure we have at
7348   // least enough stack space for the caller to store the 8 GPRs.
7349   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7350   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7351                                      CCInfo.getNextStackOffset());
7352 
7353   // Adjust the stack pointer for the new arguments...
7354   // These operations are automatically eliminated by the prolog/epilog pass.
7355   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7356   SDValue CallSeqStart = Chain;
7357 
7358   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7359   SmallVector<SDValue, 8> MemOpChains;
7360 
7361   // Set up a copy of the stack pointer for loading and storing any
7362   // arguments that may not fit in the registers available for argument
7363   // passing.
7364   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7365                                    : DAG.getRegister(PPC::R1, MVT::i32);
7366 
7367   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7368     const unsigned ValNo = ArgLocs[I].getValNo();
7369     SDValue Arg = OutVals[ValNo];
7370     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7371 
7372     if (Flags.isByVal()) {
7373       const unsigned ByValSize = Flags.getByValSize();
7374 
7375       // Nothing to do for zero-sized ByVals on the caller side.
7376       if (!ByValSize) {
7377         ++I;
7378         continue;
7379       }
7380 
7381       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7382         return DAG.getExtLoad(
7383             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7384             (LoadOffset != 0)
7385                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7386                 : Arg,
7387             MachinePointerInfo(), VT);
7388       };
7389 
7390       unsigned LoadOffset = 0;
7391 
7392       // Initialize registers, which are fully occupied by the by-val argument.
7393       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7394         SDValue Load = GetLoad(PtrVT, LoadOffset);
7395         MemOpChains.push_back(Load.getValue(1));
7396         LoadOffset += PtrByteSize;
7397         const CCValAssign &ByValVA = ArgLocs[I++];
7398         assert(ByValVA.getValNo() == ValNo &&
7399                "Unexpected location for pass-by-value argument.");
7400         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7401       }
7402 
7403       if (LoadOffset == ByValSize)
7404         continue;
7405 
7406       // There must be one more loc to handle the remainder.
7407       assert(ArgLocs[I].getValNo() == ValNo &&
7408              "Expected additional location for by-value argument.");
7409 
7410       if (ArgLocs[I].isMemLoc()) {
7411         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7412         const CCValAssign &ByValVA = ArgLocs[I++];
7413         ISD::ArgFlagsTy MemcpyFlags = Flags;
7414         // Only memcpy the bytes that don't pass in register.
7415         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7416         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7417             (LoadOffset != 0)
7418                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7419                 : Arg,
7420             DAG.getObjectPtrOffset(dl, StackPtr,
7421                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7422             CallSeqStart, MemcpyFlags, DAG, dl);
7423         continue;
7424       }
7425 
7426       // Initialize the final register residue.
7427       // Any residue that occupies the final by-val arg register must be
7428       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7429       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7430       // 2 and 1 byte loads.
7431       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7432       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7433              "Unexpected register residue for by-value argument.");
7434       SDValue ResidueVal;
7435       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7436         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7437         const MVT VT =
7438             N == 1 ? MVT::i8
7439                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7440         SDValue Load = GetLoad(VT, LoadOffset);
7441         MemOpChains.push_back(Load.getValue(1));
7442         LoadOffset += N;
7443         Bytes += N;
7444 
7445         // By-val arguments are passed left-justfied in register.
7446         // Every load here needs to be shifted, otherwise a full register load
7447         // should have been used.
7448         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7449                "Unexpected load emitted during handling of pass-by-value "
7450                "argument.");
7451         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7452         EVT ShiftAmountTy =
7453             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7454         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7455         SDValue ShiftedLoad =
7456             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7457         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7458                                               ShiftedLoad)
7459                                 : ShiftedLoad;
7460       }
7461 
7462       const CCValAssign &ByValVA = ArgLocs[I++];
7463       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7464       continue;
7465     }
7466 
7467     CCValAssign &VA = ArgLocs[I++];
7468     const MVT LocVT = VA.getLocVT();
7469     const MVT ValVT = VA.getValVT();
7470 
7471     switch (VA.getLocInfo()) {
7472     default:
7473       report_fatal_error("Unexpected argument extension type.");
7474     case CCValAssign::Full:
7475       break;
7476     case CCValAssign::ZExt:
7477       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7478       break;
7479     case CCValAssign::SExt:
7480       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7481       break;
7482     }
7483 
7484     if (VA.isRegLoc() && !VA.needsCustom()) {
7485       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7486       continue;
7487     }
7488 
7489     if (VA.isMemLoc()) {
7490       SDValue PtrOff =
7491           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7492       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7493       MemOpChains.push_back(
7494           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7495 
7496       continue;
7497     }
7498 
7499     // Custom handling is used for GPR initializations for vararg float
7500     // arguments.
7501     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7502            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7503            "Unexpected register handling for calling convention.");
7504 
7505     SDValue ArgAsInt =
7506         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7507 
7508     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7509       // f32 in 32-bit GPR
7510       // f64 in 64-bit GPR
7511       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7512     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7513       // f32 in 64-bit GPR.
7514       RegsToPass.push_back(std::make_pair(
7515           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7516     else {
7517       // f64 in two 32-bit GPRs
7518       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7519       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7520              "Unexpected custom register for argument!");
7521       CCValAssign &GPR1 = VA;
7522       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7523                                      DAG.getConstant(32, dl, MVT::i8));
7524       RegsToPass.push_back(std::make_pair(
7525           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7526 
7527       if (I != E) {
7528         // If only 1 GPR was available, there will only be one custom GPR and
7529         // the argument will also pass in memory.
7530         CCValAssign &PeekArg = ArgLocs[I];
7531         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7532           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7533           CCValAssign &GPR2 = ArgLocs[I++];
7534           RegsToPass.push_back(std::make_pair(
7535               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7536         }
7537       }
7538     }
7539   }
7540 
7541   if (!MemOpChains.empty())
7542     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7543 
7544   // For indirect calls, we need to save the TOC base to the stack for
7545   // restoration after the call.
7546   if (CFlags.IsIndirect) {
7547     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7548     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7549     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7550     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7551     const unsigned TOCSaveOffset =
7552         Subtarget.getFrameLowering()->getTOCSaveOffset();
7553 
7554     setUsesTOCBasePtr(DAG);
7555     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7556     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7557     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7558     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7559     Chain = DAG.getStore(
7560         Val.getValue(1), dl, Val, AddPtr,
7561         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7562   }
7563 
7564   // Build a sequence of copy-to-reg nodes chained together with token chain
7565   // and flag operands which copy the outgoing args into the appropriate regs.
7566   SDValue InFlag;
7567   for (auto Reg : RegsToPass) {
7568     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7569     InFlag = Chain.getValue(1);
7570   }
7571 
7572   const int SPDiff = 0;
7573   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7574                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7575 }
7576 
7577 bool
7578 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7579                                   MachineFunction &MF, bool isVarArg,
7580                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7581                                   LLVMContext &Context) const {
7582   SmallVector<CCValAssign, 16> RVLocs;
7583   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7584   return CCInfo.CheckReturn(
7585       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7586                 ? RetCC_PPC_Cold
7587                 : RetCC_PPC);
7588 }
7589 
7590 SDValue
7591 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7592                                bool isVarArg,
7593                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7594                                const SmallVectorImpl<SDValue> &OutVals,
7595                                const SDLoc &dl, SelectionDAG &DAG) const {
7596   SmallVector<CCValAssign, 16> RVLocs;
7597   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7598                  *DAG.getContext());
7599   CCInfo.AnalyzeReturn(Outs,
7600                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7601                            ? RetCC_PPC_Cold
7602                            : RetCC_PPC);
7603 
7604   SDValue Flag;
7605   SmallVector<SDValue, 4> RetOps(1, Chain);
7606 
7607   // Copy the result values into the output registers.
7608   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7609     CCValAssign &VA = RVLocs[i];
7610     assert(VA.isRegLoc() && "Can only return in registers!");
7611 
7612     SDValue Arg = OutVals[RealResIdx];
7613 
7614     switch (VA.getLocInfo()) {
7615     default: llvm_unreachable("Unknown loc info!");
7616     case CCValAssign::Full: break;
7617     case CCValAssign::AExt:
7618       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7619       break;
7620     case CCValAssign::ZExt:
7621       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7622       break;
7623     case CCValAssign::SExt:
7624       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7625       break;
7626     }
7627     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7628       bool isLittleEndian = Subtarget.isLittleEndian();
7629       // Legalize ret f64 -> ret 2 x i32.
7630       SDValue SVal =
7631           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7632                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7633       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7634       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7635       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7636                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7637       Flag = Chain.getValue(1);
7638       VA = RVLocs[++i]; // skip ahead to next loc
7639       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7640     } else
7641       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7642     Flag = Chain.getValue(1);
7643     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7644   }
7645 
7646   RetOps[0] = Chain;  // Update chain.
7647 
7648   // Add the flag if we have it.
7649   if (Flag.getNode())
7650     RetOps.push_back(Flag);
7651 
7652   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7653 }
7654 
7655 SDValue
7656 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7657                                                 SelectionDAG &DAG) const {
7658   SDLoc dl(Op);
7659 
7660   // Get the correct type for integers.
7661   EVT IntVT = Op.getValueType();
7662 
7663   // Get the inputs.
7664   SDValue Chain = Op.getOperand(0);
7665   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7666   // Build a DYNAREAOFFSET node.
7667   SDValue Ops[2] = {Chain, FPSIdx};
7668   SDVTList VTs = DAG.getVTList(IntVT);
7669   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7670 }
7671 
7672 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7673                                              SelectionDAG &DAG) const {
7674   // When we pop the dynamic allocation we need to restore the SP link.
7675   SDLoc dl(Op);
7676 
7677   // Get the correct type for pointers.
7678   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7679 
7680   // Construct the stack pointer operand.
7681   bool isPPC64 = Subtarget.isPPC64();
7682   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7683   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7684 
7685   // Get the operands for the STACKRESTORE.
7686   SDValue Chain = Op.getOperand(0);
7687   SDValue SaveSP = Op.getOperand(1);
7688 
7689   // Load the old link SP.
7690   SDValue LoadLinkSP =
7691       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7692 
7693   // Restore the stack pointer.
7694   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7695 
7696   // Store the old link SP.
7697   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7698 }
7699 
7700 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7701   MachineFunction &MF = DAG.getMachineFunction();
7702   bool isPPC64 = Subtarget.isPPC64();
7703   EVT PtrVT = getPointerTy(MF.getDataLayout());
7704 
7705   // Get current frame pointer save index.  The users of this index will be
7706   // primarily DYNALLOC instructions.
7707   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7708   int RASI = FI->getReturnAddrSaveIndex();
7709 
7710   // If the frame pointer save index hasn't been defined yet.
7711   if (!RASI) {
7712     // Find out what the fix offset of the frame pointer save area.
7713     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7714     // Allocate the frame index for frame pointer save area.
7715     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7716     // Save the result.
7717     FI->setReturnAddrSaveIndex(RASI);
7718   }
7719   return DAG.getFrameIndex(RASI, PtrVT);
7720 }
7721 
7722 SDValue
7723 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7724   MachineFunction &MF = DAG.getMachineFunction();
7725   bool isPPC64 = Subtarget.isPPC64();
7726   EVT PtrVT = getPointerTy(MF.getDataLayout());
7727 
7728   // Get current frame pointer save index.  The users of this index will be
7729   // primarily DYNALLOC instructions.
7730   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7731   int FPSI = FI->getFramePointerSaveIndex();
7732 
7733   // If the frame pointer save index hasn't been defined yet.
7734   if (!FPSI) {
7735     // Find out what the fix offset of the frame pointer save area.
7736     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7737     // Allocate the frame index for frame pointer save area.
7738     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7739     // Save the result.
7740     FI->setFramePointerSaveIndex(FPSI);
7741   }
7742   return DAG.getFrameIndex(FPSI, PtrVT);
7743 }
7744 
7745 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7746                                                    SelectionDAG &DAG) const {
7747   MachineFunction &MF = DAG.getMachineFunction();
7748   // Get the inputs.
7749   SDValue Chain = Op.getOperand(0);
7750   SDValue Size  = Op.getOperand(1);
7751   SDLoc dl(Op);
7752 
7753   // Get the correct type for pointers.
7754   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7755   // Negate the size.
7756   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7757                                 DAG.getConstant(0, dl, PtrVT), Size);
7758   // Construct a node for the frame pointer save index.
7759   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7760   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7761   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7762   if (hasInlineStackProbe(MF))
7763     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7764   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7765 }
7766 
7767 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7768                                                      SelectionDAG &DAG) const {
7769   MachineFunction &MF = DAG.getMachineFunction();
7770 
7771   bool isPPC64 = Subtarget.isPPC64();
7772   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7773 
7774   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7775   return DAG.getFrameIndex(FI, PtrVT);
7776 }
7777 
7778 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7779                                                SelectionDAG &DAG) const {
7780   SDLoc DL(Op);
7781   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7782                      DAG.getVTList(MVT::i32, MVT::Other),
7783                      Op.getOperand(0), Op.getOperand(1));
7784 }
7785 
7786 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7787                                                 SelectionDAG &DAG) const {
7788   SDLoc DL(Op);
7789   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7790                      Op.getOperand(0), Op.getOperand(1));
7791 }
7792 
7793 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7794 
7795   assert(Op.getValueType() == MVT::i1 &&
7796          "Custom lowering only for i1 loads");
7797 
7798   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7799 
7800   SDLoc dl(Op);
7801   LoadSDNode *LD = cast<LoadSDNode>(Op);
7802 
7803   SDValue Chain = LD->getChain();
7804   SDValue BasePtr = LD->getBasePtr();
7805   MachineMemOperand *MMO = LD->getMemOperand();
7806 
7807   SDValue NewLD =
7808       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7809                      BasePtr, MVT::i8, MMO);
7810   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7811 
7812   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7813   return DAG.getMergeValues(Ops, dl);
7814 }
7815 
7816 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7817   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7818          "Custom lowering only for i1 stores");
7819 
7820   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7821 
7822   SDLoc dl(Op);
7823   StoreSDNode *ST = cast<StoreSDNode>(Op);
7824 
7825   SDValue Chain = ST->getChain();
7826   SDValue BasePtr = ST->getBasePtr();
7827   SDValue Value = ST->getValue();
7828   MachineMemOperand *MMO = ST->getMemOperand();
7829 
7830   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7831                       Value);
7832   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7833 }
7834 
7835 // FIXME: Remove this once the ANDI glue bug is fixed:
7836 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7837   assert(Op.getValueType() == MVT::i1 &&
7838          "Custom lowering only for i1 results");
7839 
7840   SDLoc DL(Op);
7841   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7842 }
7843 
7844 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7845                                                SelectionDAG &DAG) const {
7846 
7847   // Implements a vector truncate that fits in a vector register as a shuffle.
7848   // We want to legalize vector truncates down to where the source fits in
7849   // a vector register (and target is therefore smaller than vector register
7850   // size).  At that point legalization will try to custom lower the sub-legal
7851   // result and get here - where we can contain the truncate as a single target
7852   // operation.
7853 
7854   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7855   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7856   //
7857   // We will implement it for big-endian ordering as this (where x denotes
7858   // undefined):
7859   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7860   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7861   //
7862   // The same operation in little-endian ordering will be:
7863   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7864   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7865 
7866   EVT TrgVT = Op.getValueType();
7867   assert(TrgVT.isVector() && "Vector type expected.");
7868   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7869   EVT EltVT = TrgVT.getVectorElementType();
7870   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7871       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7872       !isPowerOf2_32(EltVT.getSizeInBits()))
7873     return SDValue();
7874 
7875   SDValue N1 = Op.getOperand(0);
7876   EVT SrcVT = N1.getValueType();
7877   unsigned SrcSize = SrcVT.getSizeInBits();
7878   if (SrcSize > 256 ||
7879       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7880       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7881     return SDValue();
7882   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7883     return SDValue();
7884 
7885   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7886   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7887 
7888   SDLoc DL(Op);
7889   SDValue Op1, Op2;
7890   if (SrcSize == 256) {
7891     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7892     EVT SplitVT =
7893         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7894     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7895     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7896                       DAG.getConstant(0, DL, VecIdxTy));
7897     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7898                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7899   }
7900   else {
7901     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7902     Op2 = DAG.getUNDEF(WideVT);
7903   }
7904 
7905   // First list the elements we want to keep.
7906   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7907   SmallVector<int, 16> ShuffV;
7908   if (Subtarget.isLittleEndian())
7909     for (unsigned i = 0; i < TrgNumElts; ++i)
7910       ShuffV.push_back(i * SizeMult);
7911   else
7912     for (unsigned i = 1; i <= TrgNumElts; ++i)
7913       ShuffV.push_back(i * SizeMult - 1);
7914 
7915   // Populate the remaining elements with undefs.
7916   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7917     // ShuffV.push_back(i + WideNumElts);
7918     ShuffV.push_back(WideNumElts + 1);
7919 
7920   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7921   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7922   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7923 }
7924 
7925 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7926 /// possible.
7927 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7928   // Not FP, or using SPE? Not a fsel.
7929   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7930       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7931     return Op;
7932 
7933   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7934 
7935   EVT ResVT = Op.getValueType();
7936   EVT CmpVT = Op.getOperand(0).getValueType();
7937   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7938   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7939   SDLoc dl(Op);
7940   SDNodeFlags Flags = Op.getNode()->getFlags();
7941 
7942   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7943   // presence of infinities.
7944   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7945     switch (CC) {
7946     default:
7947       break;
7948     case ISD::SETOGT:
7949     case ISD::SETGT:
7950       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7951     case ISD::SETOLT:
7952     case ISD::SETLT:
7953       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7954     }
7955   }
7956 
7957   // We might be able to do better than this under some circumstances, but in
7958   // general, fsel-based lowering of select is a finite-math-only optimization.
7959   // For more information, see section F.3 of the 2.06 ISA specification.
7960   // With ISA 3.0
7961   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7962       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7963     return Op;
7964 
7965   // If the RHS of the comparison is a 0.0, we don't need to do the
7966   // subtraction at all.
7967   SDValue Sel1;
7968   if (isFloatingPointZero(RHS))
7969     switch (CC) {
7970     default: break;       // SETUO etc aren't handled by fsel.
7971     case ISD::SETNE:
7972       std::swap(TV, FV);
7973       LLVM_FALLTHROUGH;
7974     case ISD::SETEQ:
7975       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7976         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7977       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7978       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7979         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7980       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7981                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7982     case ISD::SETULT:
7983     case ISD::SETLT:
7984       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7985       LLVM_FALLTHROUGH;
7986     case ISD::SETOGE:
7987     case ISD::SETGE:
7988       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7989         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7990       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7991     case ISD::SETUGT:
7992     case ISD::SETGT:
7993       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7994       LLVM_FALLTHROUGH;
7995     case ISD::SETOLE:
7996     case ISD::SETLE:
7997       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7998         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7999       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8000                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8001     }
8002 
8003   SDValue Cmp;
8004   switch (CC) {
8005   default: break;       // SETUO etc aren't handled by fsel.
8006   case ISD::SETNE:
8007     std::swap(TV, FV);
8008     LLVM_FALLTHROUGH;
8009   case ISD::SETEQ:
8010     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8011     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8012       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8013     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8014     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
8015       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
8016     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8017                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8018   case ISD::SETULT:
8019   case ISD::SETLT:
8020     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8021     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8022       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8023     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8024   case ISD::SETOGE:
8025   case ISD::SETGE:
8026     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8027     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8028       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8029     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8030   case ISD::SETUGT:
8031   case ISD::SETGT:
8032     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8033     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8034       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8035     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8036   case ISD::SETOLE:
8037   case ISD::SETLE:
8038     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8039     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8040       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8041     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8042   }
8043   return Op;
8044 }
8045 
8046 static unsigned getPPCStrictOpcode(unsigned Opc) {
8047   switch (Opc) {
8048   default:
8049     llvm_unreachable("No strict version of this opcode!");
8050   case PPCISD::FCTIDZ:
8051     return PPCISD::STRICT_FCTIDZ;
8052   case PPCISD::FCTIWZ:
8053     return PPCISD::STRICT_FCTIWZ;
8054   case PPCISD::FCTIDUZ:
8055     return PPCISD::STRICT_FCTIDUZ;
8056   case PPCISD::FCTIWUZ:
8057     return PPCISD::STRICT_FCTIWUZ;
8058   case PPCISD::FCFID:
8059     return PPCISD::STRICT_FCFID;
8060   case PPCISD::FCFIDU:
8061     return PPCISD::STRICT_FCFIDU;
8062   case PPCISD::FCFIDS:
8063     return PPCISD::STRICT_FCFIDS;
8064   case PPCISD::FCFIDUS:
8065     return PPCISD::STRICT_FCFIDUS;
8066   }
8067 }
8068 
8069 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8070                               const PPCSubtarget &Subtarget) {
8071   SDLoc dl(Op);
8072   bool IsStrict = Op->isStrictFPOpcode();
8073   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8074                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8075   // For strict nodes, source is the second operand.
8076   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8077   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8078   assert(Src.getValueType().isFloatingPoint());
8079   if (Src.getValueType() == MVT::f32) {
8080     if (IsStrict) {
8081       Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other},
8082                         {Chain, Src});
8083       Chain = Src.getValue(1);
8084     } else
8085       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8086   }
8087   SDValue Conv;
8088   unsigned Opc = ISD::DELETED_NODE;
8089   switch (Op.getSimpleValueType().SimpleTy) {
8090   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8091   case MVT::i32:
8092     Opc = IsSigned ? PPCISD::FCTIWZ
8093                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8094     break;
8095   case MVT::i64:
8096     assert((IsSigned || Subtarget.hasFPCVT()) &&
8097            "i64 FP_TO_UINT is supported only with FPCVT");
8098     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8099   }
8100   if (IsStrict) {
8101     Opc = getPPCStrictOpcode(Opc);
8102     Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src});
8103   } else {
8104     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8105   }
8106   return Conv;
8107 }
8108 
8109 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8110                                                SelectionDAG &DAG,
8111                                                const SDLoc &dl) const {
8112   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8113   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8114                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8115   bool IsStrict = Op->isStrictFPOpcode();
8116 
8117   // Convert the FP value to an int value through memory.
8118   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8119                   (IsSigned || Subtarget.hasFPCVT());
8120   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8121   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8122   MachinePointerInfo MPI =
8123       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8124 
8125   // Emit a store to the stack slot.
8126   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8127   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8128   if (i32Stack) {
8129     MachineFunction &MF = DAG.getMachineFunction();
8130     Alignment = Align(4);
8131     MachineMemOperand *MMO =
8132         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8133     SDValue Ops[] = { Chain, Tmp, FIPtr };
8134     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8135               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8136   } else
8137     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8138 
8139   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8140   // add in a bias on big endian.
8141   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8142     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8143                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8144     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8145   }
8146 
8147   RLI.Chain = Chain;
8148   RLI.Ptr = FIPtr;
8149   RLI.MPI = MPI;
8150   RLI.Alignment = Alignment;
8151 }
8152 
8153 /// Custom lowers floating point to integer conversions to use
8154 /// the direct move instructions available in ISA 2.07 to avoid the
8155 /// need for load/store combinations.
8156 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8157                                                     SelectionDAG &DAG,
8158                                                     const SDLoc &dl) const {
8159   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8160   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8161   if (Op->isStrictFPOpcode())
8162     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8163   else
8164     return Mov;
8165 }
8166 
8167 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8168                                           const SDLoc &dl) const {
8169   bool IsStrict = Op->isStrictFPOpcode();
8170   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8171                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8172   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8173   // FP to INT conversions are legal for f128.
8174   if (Src.getValueType() == MVT::f128)
8175     return Op;
8176 
8177   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8178   // PPC (the libcall is not available).
8179   if (Src.getValueType() == MVT::ppcf128 && !IsStrict) {
8180     if (Op.getValueType() == MVT::i32) {
8181       if (IsSigned) {
8182         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8183                                  DAG.getIntPtrConstant(0, dl));
8184         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8185                                  DAG.getIntPtrConstant(1, dl));
8186 
8187         // Add the two halves of the long double in round-to-zero mode.
8188         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8189 
8190         // Now use a smaller FP_TO_SINT.
8191         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8192       } else {
8193         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8194         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8195         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8196         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8197         // FIXME: generated code sucks.
8198         // TODO: Are there fast-math-flags to propagate to this FSUB?
8199         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8200         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8201         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8202                            DAG.getConstant(0x80000000, dl, MVT::i32));
8203         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8204         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8205       }
8206     }
8207 
8208     return SDValue();
8209   }
8210 
8211   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8212     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8213 
8214   ReuseLoadInfo RLI;
8215   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8216 
8217   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8218                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8219 }
8220 
8221 // We're trying to insert a regular store, S, and then a load, L. If the
8222 // incoming value, O, is a load, we might just be able to have our load use the
8223 // address used by O. However, we don't know if anything else will store to
8224 // that address before we can load from it. To prevent this situation, we need
8225 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8226 // the same chain operand as O, we create a token factor from the chain results
8227 // of O and L, and we replace all uses of O's chain result with that token
8228 // factor (see spliceIntoChain below for this last part).
8229 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8230                                             ReuseLoadInfo &RLI,
8231                                             SelectionDAG &DAG,
8232                                             ISD::LoadExtType ET) const {
8233   // Conservatively skip reusing for constrained FP nodes.
8234   if (Op->isStrictFPOpcode())
8235     return false;
8236 
8237   SDLoc dl(Op);
8238   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8239                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8240   if (ET == ISD::NON_EXTLOAD &&
8241       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8242       isOperationLegalOrCustom(Op.getOpcode(),
8243                                Op.getOperand(0).getValueType())) {
8244 
8245     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8246     return true;
8247   }
8248 
8249   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8250   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8251       LD->isNonTemporal())
8252     return false;
8253   if (LD->getMemoryVT() != MemVT)
8254     return false;
8255 
8256   RLI.Ptr = LD->getBasePtr();
8257   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8258     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8259            "Non-pre-inc AM on PPC?");
8260     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8261                           LD->getOffset());
8262   }
8263 
8264   RLI.Chain = LD->getChain();
8265   RLI.MPI = LD->getPointerInfo();
8266   RLI.IsDereferenceable = LD->isDereferenceable();
8267   RLI.IsInvariant = LD->isInvariant();
8268   RLI.Alignment = LD->getAlign();
8269   RLI.AAInfo = LD->getAAInfo();
8270   RLI.Ranges = LD->getRanges();
8271 
8272   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8273   return true;
8274 }
8275 
8276 // Given the head of the old chain, ResChain, insert a token factor containing
8277 // it and NewResChain, and make users of ResChain now be users of that token
8278 // factor.
8279 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8280 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8281                                         SDValue NewResChain,
8282                                         SelectionDAG &DAG) const {
8283   if (!ResChain)
8284     return;
8285 
8286   SDLoc dl(NewResChain);
8287 
8288   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8289                            NewResChain, DAG.getUNDEF(MVT::Other));
8290   assert(TF.getNode() != NewResChain.getNode() &&
8291          "A new TF really is required here");
8292 
8293   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8294   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8295 }
8296 
8297 /// Analyze profitability of direct move
8298 /// prefer float load to int load plus direct move
8299 /// when there is no integer use of int load
8300 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8301   SDNode *Origin = Op.getOperand(0).getNode();
8302   if (Origin->getOpcode() != ISD::LOAD)
8303     return true;
8304 
8305   // If there is no LXSIBZX/LXSIHZX, like Power8,
8306   // prefer direct move if the memory size is 1 or 2 bytes.
8307   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8308   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8309     return true;
8310 
8311   for (SDNode::use_iterator UI = Origin->use_begin(),
8312                             UE = Origin->use_end();
8313        UI != UE; ++UI) {
8314 
8315     // Only look at the users of the loaded value.
8316     if (UI.getUse().get().getResNo() != 0)
8317       continue;
8318 
8319     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8320         UI->getOpcode() != ISD::UINT_TO_FP &&
8321         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8322         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8323       return true;
8324   }
8325 
8326   return false;
8327 }
8328 
8329 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8330                               const PPCSubtarget &Subtarget,
8331                               SDValue Chain = SDValue()) {
8332   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8333                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8334   SDLoc dl(Op);
8335   // If we have FCFIDS, then use it when converting to single-precision.
8336   // Otherwise, convert to double-precision and then round.
8337   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8338   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8339                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8340   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8341   if (Op->isStrictFPOpcode()) {
8342     if (!Chain)
8343       Chain = Op.getOperand(0);
8344     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl, {ConvTy, MVT::Other},
8345                        {Chain, Src});
8346   } else
8347     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8348 }
8349 
8350 /// Custom lowers integer to floating point conversions to use
8351 /// the direct move instructions available in ISA 2.07 to avoid the
8352 /// need for load/store combinations.
8353 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8354                                                     SelectionDAG &DAG,
8355                                                     const SDLoc &dl) const {
8356   assert((Op.getValueType() == MVT::f32 ||
8357           Op.getValueType() == MVT::f64) &&
8358          "Invalid floating point type as target of conversion");
8359   assert(Subtarget.hasFPCVT() &&
8360          "Int to FP conversions with direct moves require FPCVT");
8361   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8362   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8363   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8364                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8365   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8366   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8367   return convertIntToFP(Op, Mov, DAG, Subtarget);
8368 }
8369 
8370 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8371 
8372   EVT VecVT = Vec.getValueType();
8373   assert(VecVT.isVector() && "Expected a vector type.");
8374   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8375 
8376   EVT EltVT = VecVT.getVectorElementType();
8377   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8378   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8379 
8380   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8381   SmallVector<SDValue, 16> Ops(NumConcat);
8382   Ops[0] = Vec;
8383   SDValue UndefVec = DAG.getUNDEF(VecVT);
8384   for (unsigned i = 1; i < NumConcat; ++i)
8385     Ops[i] = UndefVec;
8386 
8387   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8388 }
8389 
8390 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8391                                                 const SDLoc &dl) const {
8392   bool IsStrict = Op->isStrictFPOpcode();
8393   unsigned Opc = Op.getOpcode();
8394   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8395   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8396           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8397          "Unexpected conversion type");
8398   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8399          "Supports conversions to v2f64/v4f32 only.");
8400 
8401   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8402   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8403 
8404   SDValue Wide = widenVec(DAG, Src, dl);
8405   EVT WideVT = Wide.getValueType();
8406   unsigned WideNumElts = WideVT.getVectorNumElements();
8407   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8408 
8409   SmallVector<int, 16> ShuffV;
8410   for (unsigned i = 0; i < WideNumElts; ++i)
8411     ShuffV.push_back(i + WideNumElts);
8412 
8413   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8414   int SaveElts = FourEltRes ? 4 : 2;
8415   if (Subtarget.isLittleEndian())
8416     for (int i = 0; i < SaveElts; i++)
8417       ShuffV[i * Stride] = i;
8418   else
8419     for (int i = 1; i <= SaveElts; i++)
8420       ShuffV[i * Stride - 1] = i - 1;
8421 
8422   SDValue ShuffleSrc2 =
8423       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8424   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8425 
8426   SDValue Extend;
8427   if (SignedConv) {
8428     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8429     EVT ExtVT = Src.getValueType();
8430     if (Subtarget.hasP9Altivec())
8431       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8432                                IntermediateVT.getVectorNumElements());
8433 
8434     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8435                          DAG.getValueType(ExtVT));
8436   } else
8437     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8438 
8439   if (IsStrict)
8440     return DAG.getNode(Opc, dl, {Op.getValueType(), MVT::Other},
8441                        {Op.getOperand(0), Extend});
8442 
8443   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8444 }
8445 
8446 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8447                                           SelectionDAG &DAG) const {
8448   SDLoc dl(Op);
8449   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8450                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8451   bool IsStrict = Op->isStrictFPOpcode();
8452   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8453   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8454 
8455   EVT InVT = Src.getValueType();
8456   EVT OutVT = Op.getValueType();
8457   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8458       isOperationCustom(Op.getOpcode(), InVT))
8459     return LowerINT_TO_FPVector(Op, DAG, dl);
8460 
8461   // Conversions to f128 are legal.
8462   if (Op.getValueType() == MVT::f128)
8463     return Op;
8464 
8465   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8466   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8467     return SDValue();
8468 
8469   if (Src.getValueType() == MVT::i1)
8470     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8471                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8472                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8473 
8474   // If we have direct moves, we can do all the conversion, skip the store/load
8475   // however, without FPCVT we can't do most conversions.
8476   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8477       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8478     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8479 
8480   assert((IsSigned || Subtarget.hasFPCVT()) &&
8481          "UINT_TO_FP is supported only with FPCVT");
8482 
8483   if (Src.getValueType() == MVT::i64) {
8484     SDValue SINT = Src;
8485     // When converting to single-precision, we actually need to convert
8486     // to double-precision first and then round to single-precision.
8487     // To avoid double-rounding effects during that operation, we have
8488     // to prepare the input operand.  Bits that might be truncated when
8489     // converting to double-precision are replaced by a bit that won't
8490     // be lost at this stage, but is below the single-precision rounding
8491     // position.
8492     //
8493     // However, if -enable-unsafe-fp-math is in effect, accept double
8494     // rounding to avoid the extra overhead.
8495     if (Op.getValueType() == MVT::f32 &&
8496         !Subtarget.hasFPCVT() &&
8497         !DAG.getTarget().Options.UnsafeFPMath) {
8498 
8499       // Twiddle input to make sure the low 11 bits are zero.  (If this
8500       // is the case, we are guaranteed the value will fit into the 53 bit
8501       // mantissa of an IEEE double-precision value without rounding.)
8502       // If any of those low 11 bits were not zero originally, make sure
8503       // bit 12 (value 2048) is set instead, so that the final rounding
8504       // to single-precision gets the correct result.
8505       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8506                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8507       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8508                           Round, DAG.getConstant(2047, dl, MVT::i64));
8509       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8510       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8511                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8512 
8513       // However, we cannot use that value unconditionally: if the magnitude
8514       // of the input value is small, the bit-twiddling we did above might
8515       // end up visibly changing the output.  Fortunately, in that case, we
8516       // don't need to twiddle bits since the original input will convert
8517       // exactly to double-precision floating-point already.  Therefore,
8518       // construct a conditional to use the original value if the top 11
8519       // bits are all sign-bit copies, and use the rounded value computed
8520       // above otherwise.
8521       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8522                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8523       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8524                          Cond, DAG.getConstant(1, dl, MVT::i64));
8525       Cond = DAG.getSetCC(
8526           dl,
8527           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8528           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8529 
8530       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8531     }
8532 
8533     ReuseLoadInfo RLI;
8534     SDValue Bits;
8535 
8536     MachineFunction &MF = DAG.getMachineFunction();
8537     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8538       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8539                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8540       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8541     } else if (Subtarget.hasLFIWAX() &&
8542                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8543       MachineMemOperand *MMO =
8544         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8545                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8546       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8547       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8548                                      DAG.getVTList(MVT::f64, MVT::Other),
8549                                      Ops, MVT::i32, MMO);
8550       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8551     } else if (Subtarget.hasFPCVT() &&
8552                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8553       MachineMemOperand *MMO =
8554         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8555                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8556       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8557       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8558                                      DAG.getVTList(MVT::f64, MVT::Other),
8559                                      Ops, MVT::i32, MMO);
8560       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8561     } else if (((Subtarget.hasLFIWAX() &&
8562                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8563                 (Subtarget.hasFPCVT() &&
8564                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8565                SINT.getOperand(0).getValueType() == MVT::i32) {
8566       MachineFrameInfo &MFI = MF.getFrameInfo();
8567       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8568 
8569       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8570       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8571 
8572       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8573                                    MachinePointerInfo::getFixedStack(
8574                                        DAG.getMachineFunction(), FrameIdx));
8575       Chain = Store;
8576 
8577       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8578              "Expected an i32 store");
8579 
8580       RLI.Ptr = FIdx;
8581       RLI.Chain = Chain;
8582       RLI.MPI =
8583           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8584       RLI.Alignment = Align(4);
8585 
8586       MachineMemOperand *MMO =
8587         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8588                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8589       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8590       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8591                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8592                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8593                                      Ops, MVT::i32, MMO);
8594       Chain = Bits.getValue(1);
8595     } else
8596       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8597 
8598     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8599     if (IsStrict)
8600       Chain = FP.getValue(1);
8601 
8602     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8603       if (IsStrict)
8604         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other},
8605                          {Chain, FP, DAG.getIntPtrConstant(0, dl)});
8606       else
8607         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8608                          DAG.getIntPtrConstant(0, dl));
8609     }
8610     return FP;
8611   }
8612 
8613   assert(Src.getValueType() == MVT::i32 &&
8614          "Unhandled INT_TO_FP type in custom expander!");
8615   // Since we only generate this in 64-bit mode, we can take advantage of
8616   // 64-bit registers.  In particular, sign extend the input value into the
8617   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8618   // then lfd it and fcfid it.
8619   MachineFunction &MF = DAG.getMachineFunction();
8620   MachineFrameInfo &MFI = MF.getFrameInfo();
8621   EVT PtrVT = getPointerTy(MF.getDataLayout());
8622 
8623   SDValue Ld;
8624   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8625     ReuseLoadInfo RLI;
8626     bool ReusingLoad;
8627     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8628       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8629       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8630 
8631       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8632                                    MachinePointerInfo::getFixedStack(
8633                                        DAG.getMachineFunction(), FrameIdx));
8634       Chain = Store;
8635 
8636       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8637              "Expected an i32 store");
8638 
8639       RLI.Ptr = FIdx;
8640       RLI.Chain = Chain;
8641       RLI.MPI =
8642           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8643       RLI.Alignment = Align(4);
8644     }
8645 
8646     MachineMemOperand *MMO =
8647       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8648                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8649     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8650     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8651                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8652                                  MVT::i32, MMO);
8653     Chain = Ld.getValue(1);
8654     if (ReusingLoad)
8655       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8656   } else {
8657     assert(Subtarget.isPPC64() &&
8658            "i32->FP without LFIWAX supported only on PPC64");
8659 
8660     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8661     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8662 
8663     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8664 
8665     // STD the extended value into the stack slot.
8666     SDValue Store = DAG.getStore(
8667         Chain, dl, Ext64, FIdx,
8668         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8669     Chain = Store;
8670 
8671     // Load the value as a double.
8672     Ld = DAG.getLoad(
8673         MVT::f64, dl, Chain, FIdx,
8674         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8675     Chain = Ld.getValue(1);
8676   }
8677 
8678   // FCFID it and return it.
8679   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8680   if (IsStrict)
8681     Chain = FP.getValue(1);
8682   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8683     if (IsStrict)
8684       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {MVT::f32, MVT::Other},
8685                        {Chain, FP, DAG.getIntPtrConstant(0, dl)});
8686     else
8687       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8688                        DAG.getIntPtrConstant(0, dl));
8689   }
8690   return FP;
8691 }
8692 
8693 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8694                                             SelectionDAG &DAG) const {
8695   SDLoc dl(Op);
8696   /*
8697    The rounding mode is in bits 30:31 of FPSR, and has the following
8698    settings:
8699      00 Round to nearest
8700      01 Round to 0
8701      10 Round to +inf
8702      11 Round to -inf
8703 
8704   FLT_ROUNDS, on the other hand, expects the following:
8705     -1 Undefined
8706      0 Round to 0
8707      1 Round to nearest
8708      2 Round to +inf
8709      3 Round to -inf
8710 
8711   To perform the conversion, we do:
8712     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8713   */
8714 
8715   MachineFunction &MF = DAG.getMachineFunction();
8716   EVT VT = Op.getValueType();
8717   EVT PtrVT = getPointerTy(MF.getDataLayout());
8718 
8719   // Save FP Control Word to register
8720   SDValue Chain = Op.getOperand(0);
8721   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8722   Chain = MFFS.getValue(1);
8723 
8724   // Save FP register to stack slot
8725   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8726   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8727   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8728 
8729   // Load FP Control Word from low 32 bits of stack slot.
8730   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8731   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8732   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8733   Chain = CWD.getValue(1);
8734 
8735   // Transform as necessary
8736   SDValue CWD1 =
8737     DAG.getNode(ISD::AND, dl, MVT::i32,
8738                 CWD, DAG.getConstant(3, dl, MVT::i32));
8739   SDValue CWD2 =
8740     DAG.getNode(ISD::SRL, dl, MVT::i32,
8741                 DAG.getNode(ISD::AND, dl, MVT::i32,
8742                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8743                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8744                             DAG.getConstant(3, dl, MVT::i32)),
8745                 DAG.getConstant(1, dl, MVT::i32));
8746 
8747   SDValue RetVal =
8748     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8749 
8750   RetVal =
8751       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8752                   dl, VT, RetVal);
8753 
8754   return DAG.getMergeValues({RetVal, Chain}, dl);
8755 }
8756 
8757 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8758   EVT VT = Op.getValueType();
8759   unsigned BitWidth = VT.getSizeInBits();
8760   SDLoc dl(Op);
8761   assert(Op.getNumOperands() == 3 &&
8762          VT == Op.getOperand(1).getValueType() &&
8763          "Unexpected SHL!");
8764 
8765   // Expand into a bunch of logical ops.  Note that these ops
8766   // depend on the PPC behavior for oversized shift amounts.
8767   SDValue Lo = Op.getOperand(0);
8768   SDValue Hi = Op.getOperand(1);
8769   SDValue Amt = Op.getOperand(2);
8770   EVT AmtVT = Amt.getValueType();
8771 
8772   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8773                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8774   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8775   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8776   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8777   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8778                              DAG.getConstant(-BitWidth, dl, AmtVT));
8779   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8780   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8781   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8782   SDValue OutOps[] = { OutLo, OutHi };
8783   return DAG.getMergeValues(OutOps, dl);
8784 }
8785 
8786 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8787   EVT VT = Op.getValueType();
8788   SDLoc dl(Op);
8789   unsigned BitWidth = VT.getSizeInBits();
8790   assert(Op.getNumOperands() == 3 &&
8791          VT == Op.getOperand(1).getValueType() &&
8792          "Unexpected SRL!");
8793 
8794   // Expand into a bunch of logical ops.  Note that these ops
8795   // depend on the PPC behavior for oversized shift amounts.
8796   SDValue Lo = Op.getOperand(0);
8797   SDValue Hi = Op.getOperand(1);
8798   SDValue Amt = Op.getOperand(2);
8799   EVT AmtVT = Amt.getValueType();
8800 
8801   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8802                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8803   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8804   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8805   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8806   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8807                              DAG.getConstant(-BitWidth, dl, AmtVT));
8808   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8809   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8810   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8811   SDValue OutOps[] = { OutLo, OutHi };
8812   return DAG.getMergeValues(OutOps, dl);
8813 }
8814 
8815 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8816   SDLoc dl(Op);
8817   EVT VT = Op.getValueType();
8818   unsigned BitWidth = VT.getSizeInBits();
8819   assert(Op.getNumOperands() == 3 &&
8820          VT == Op.getOperand(1).getValueType() &&
8821          "Unexpected SRA!");
8822 
8823   // Expand into a bunch of logical ops, followed by a select_cc.
8824   SDValue Lo = Op.getOperand(0);
8825   SDValue Hi = Op.getOperand(1);
8826   SDValue Amt = Op.getOperand(2);
8827   EVT AmtVT = Amt.getValueType();
8828 
8829   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8830                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8831   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8832   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8833   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8834   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8835                              DAG.getConstant(-BitWidth, dl, AmtVT));
8836   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8837   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8838   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8839                                   Tmp4, Tmp6, ISD::SETLE);
8840   SDValue OutOps[] = { OutLo, OutHi };
8841   return DAG.getMergeValues(OutOps, dl);
8842 }
8843 
8844 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8845                                             SelectionDAG &DAG) const {
8846   SDLoc dl(Op);
8847   EVT VT = Op.getValueType();
8848   unsigned BitWidth = VT.getSizeInBits();
8849 
8850   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8851   SDValue X = Op.getOperand(0);
8852   SDValue Y = Op.getOperand(1);
8853   SDValue Z = Op.getOperand(2);
8854   EVT AmtVT = Z.getValueType();
8855 
8856   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8857   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8858   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8859   // on PowerPC shift by BW being well defined.
8860   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8861                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8862   SDValue SubZ =
8863       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8864   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8865   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8866   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8867 }
8868 
8869 //===----------------------------------------------------------------------===//
8870 // Vector related lowering.
8871 //
8872 
8873 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8874 /// element size of SplatSize. Cast the result to VT.
8875 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8876                                       SelectionDAG &DAG, const SDLoc &dl) {
8877   static const MVT VTys[] = { // canonical VT to use for each size.
8878     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8879   };
8880 
8881   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8882 
8883   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8884   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8885     SplatSize = 1;
8886     Val = 0xFF;
8887   }
8888 
8889   EVT CanonicalVT = VTys[SplatSize-1];
8890 
8891   // Build a canonical splat for this value.
8892   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8893 }
8894 
8895 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8896 /// specified intrinsic ID.
8897 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8898                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8899   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8900   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8901                      DAG.getConstant(IID, dl, MVT::i32), Op);
8902 }
8903 
8904 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8905 /// specified intrinsic ID.
8906 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8907                                 SelectionDAG &DAG, const SDLoc &dl,
8908                                 EVT DestVT = MVT::Other) {
8909   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8910   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8911                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8912 }
8913 
8914 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8915 /// specified intrinsic ID.
8916 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8917                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8918                                 EVT DestVT = MVT::Other) {
8919   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8920   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8921                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8922 }
8923 
8924 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8925 /// amount.  The result has the specified value type.
8926 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8927                            SelectionDAG &DAG, const SDLoc &dl) {
8928   // Force LHS/RHS to be the right type.
8929   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8930   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8931 
8932   int Ops[16];
8933   for (unsigned i = 0; i != 16; ++i)
8934     Ops[i] = i + Amt;
8935   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8936   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8937 }
8938 
8939 /// Do we have an efficient pattern in a .td file for this node?
8940 ///
8941 /// \param V - pointer to the BuildVectorSDNode being matched
8942 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8943 ///
8944 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8945 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8946 /// the opposite is true (expansion is beneficial) are:
8947 /// - The node builds a vector out of integers that are not 32 or 64-bits
8948 /// - The node builds a vector out of constants
8949 /// - The node is a "load-and-splat"
8950 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8951 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8952                                             bool HasDirectMove,
8953                                             bool HasP8Vector) {
8954   EVT VecVT = V->getValueType(0);
8955   bool RightType = VecVT == MVT::v2f64 ||
8956     (HasP8Vector && VecVT == MVT::v4f32) ||
8957     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8958   if (!RightType)
8959     return false;
8960 
8961   bool IsSplat = true;
8962   bool IsLoad = false;
8963   SDValue Op0 = V->getOperand(0);
8964 
8965   // This function is called in a block that confirms the node is not a constant
8966   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8967   // different constants.
8968   if (V->isConstant())
8969     return false;
8970   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8971     if (V->getOperand(i).isUndef())
8972       return false;
8973     // We want to expand nodes that represent load-and-splat even if the
8974     // loaded value is a floating point truncation or conversion to int.
8975     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8976         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8977          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8978         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8979          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8980         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8981          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8982       IsLoad = true;
8983     // If the operands are different or the input is not a load and has more
8984     // uses than just this BV node, then it isn't a splat.
8985     if (V->getOperand(i) != Op0 ||
8986         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8987       IsSplat = false;
8988   }
8989   return !(IsSplat && IsLoad);
8990 }
8991 
8992 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8993 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8994 
8995   SDLoc dl(Op);
8996   SDValue Op0 = Op->getOperand(0);
8997 
8998   if ((Op.getValueType() != MVT::f128) ||
8999       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9000       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9001       (Op0.getOperand(1).getValueType() != MVT::i64))
9002     return SDValue();
9003 
9004   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9005                      Op0.getOperand(1));
9006 }
9007 
9008 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9009   const SDValue *InputLoad = &Op;
9010   if (InputLoad->getOpcode() == ISD::BITCAST)
9011     InputLoad = &InputLoad->getOperand(0);
9012   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9013       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9014     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9015     InputLoad = &InputLoad->getOperand(0);
9016   }
9017   if (InputLoad->getOpcode() != ISD::LOAD)
9018     return nullptr;
9019   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9020   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9021 }
9022 
9023 // Convert the argument APFloat to a single precision APFloat if there is no
9024 // loss in information during the conversion to single precision APFloat and the
9025 // resulting number is not a denormal number. Return true if successful.
9026 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9027   APFloat APFloatToConvert = ArgAPFloat;
9028   bool LosesInfo = true;
9029   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9030                            &LosesInfo);
9031   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9032   if (Success)
9033     ArgAPFloat = APFloatToConvert;
9034   return Success;
9035 }
9036 
9037 // Bitcast the argument APInt to a double and convert it to a single precision
9038 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9039 // argument if there is no loss in information during the conversion from
9040 // double to single precision APFloat and the resulting number is not a denormal
9041 // number. Return true if successful.
9042 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9043   double DpValue = ArgAPInt.bitsToDouble();
9044   APFloat APFloatDp(DpValue);
9045   bool Success = convertToNonDenormSingle(APFloatDp);
9046   if (Success)
9047     ArgAPInt = APFloatDp.bitcastToAPInt();
9048   return Success;
9049 }
9050 
9051 // If this is a case we can't handle, return null and let the default
9052 // expansion code take care of it.  If we CAN select this case, and if it
9053 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9054 // this case more efficiently than a constant pool load, lower it to the
9055 // sequence of ops that should be used.
9056 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9057                                              SelectionDAG &DAG) const {
9058   SDLoc dl(Op);
9059   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9060   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9061 
9062   // Check if this is a splat of a constant value.
9063   APInt APSplatBits, APSplatUndef;
9064   unsigned SplatBitSize;
9065   bool HasAnyUndefs;
9066   bool BVNIsConstantSplat =
9067       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9068                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9069 
9070   // If it is a splat of a double, check if we can shrink it to a 32 bit
9071   // non-denormal float which when converted back to double gives us the same
9072   // double. This is to exploit the XXSPLTIDP instruction.
9073   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
9074       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
9075       convertToNonDenormSingle(APSplatBits)) {
9076     SDValue SplatNode = DAG.getNode(
9077         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9078         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9079     return DAG.getBitcast(Op.getValueType(), SplatNode);
9080   }
9081 
9082   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9083 
9084     bool IsPermutedLoad = false;
9085     const SDValue *InputLoad =
9086         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
9087     // Handle load-and-splat patterns as we have instructions that will do this
9088     // in one go.
9089     if (InputLoad && DAG.isSplatValue(Op, true)) {
9090       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9091 
9092       // We have handling for 4 and 8 byte elements.
9093       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
9094 
9095       // Checking for a single use of this load, we have to check for vector
9096       // width (128 bits) / ElementSize uses (since each operand of the
9097       // BUILD_VECTOR is a separate use of the value.
9098       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
9099           ((Subtarget.hasVSX() && ElementSize == 64) ||
9100            (Subtarget.hasP9Vector() && ElementSize == 32))) {
9101         SDValue Ops[] = {
9102           LD->getChain(),    // Chain
9103           LD->getBasePtr(),  // Ptr
9104           DAG.getValueType(Op.getValueType()) // VT
9105         };
9106         return
9107           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
9108                                   DAG.getVTList(Op.getValueType(), MVT::Other),
9109                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
9110       }
9111     }
9112 
9113     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
9114     // lowered to VSX instructions under certain conditions.
9115     // Without VSX, there is no pattern more efficient than expanding the node.
9116     if (Subtarget.hasVSX() &&
9117         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9118                                         Subtarget.hasP8Vector()))
9119       return Op;
9120     return SDValue();
9121   }
9122 
9123   uint64_t SplatBits = APSplatBits.getZExtValue();
9124   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9125   unsigned SplatSize = SplatBitSize / 8;
9126 
9127   // First, handle single instruction cases.
9128 
9129   // All zeros?
9130   if (SplatBits == 0) {
9131     // Canonicalize all zero vectors to be v4i32.
9132     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9133       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9134       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9135     }
9136     return Op;
9137   }
9138 
9139   // We have XXSPLTIW for constant splats four bytes wide.
9140   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9141   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9142   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9143   // turned into a 4-byte splat of 0xABABABAB.
9144   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9145     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9146                                   Op.getValueType(), DAG, dl);
9147 
9148   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9149     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9150                                   dl);
9151 
9152   // We have XXSPLTIB for constant splats one byte wide.
9153   if (Subtarget.hasP9Vector() && SplatSize == 1)
9154     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9155                                   dl);
9156 
9157   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9158   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9159                     (32-SplatBitSize));
9160   if (SextVal >= -16 && SextVal <= 15)
9161     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9162                                   dl);
9163 
9164   // Two instruction sequences.
9165 
9166   // If this value is in the range [-32,30] and is even, use:
9167   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9168   // If this value is in the range [17,31] and is odd, use:
9169   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9170   // If this value is in the range [-31,-17] and is odd, use:
9171   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9172   // Note the last two are three-instruction sequences.
9173   if (SextVal >= -32 && SextVal <= 31) {
9174     // To avoid having these optimizations undone by constant folding,
9175     // we convert to a pseudo that will be expanded later into one of
9176     // the above forms.
9177     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9178     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9179               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9180     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9181     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9182     if (VT == Op.getValueType())
9183       return RetVal;
9184     else
9185       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9186   }
9187 
9188   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9189   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9190   // for fneg/fabs.
9191   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9192     // Make -1 and vspltisw -1:
9193     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9194 
9195     // Make the VSLW intrinsic, computing 0x8000_0000.
9196     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9197                                    OnesV, DAG, dl);
9198 
9199     // xor by OnesV to invert it.
9200     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9201     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9202   }
9203 
9204   // Check to see if this is a wide variety of vsplti*, binop self cases.
9205   static const signed char SplatCsts[] = {
9206     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9207     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9208   };
9209 
9210   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9211     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9212     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9213     int i = SplatCsts[idx];
9214 
9215     // Figure out what shift amount will be used by altivec if shifted by i in
9216     // this splat size.
9217     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9218 
9219     // vsplti + shl self.
9220     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9221       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9222       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9223         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9224         Intrinsic::ppc_altivec_vslw
9225       };
9226       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9227       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9228     }
9229 
9230     // vsplti + srl self.
9231     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9232       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9233       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9234         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9235         Intrinsic::ppc_altivec_vsrw
9236       };
9237       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9238       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9239     }
9240 
9241     // vsplti + sra self.
9242     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9243       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9244       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9245         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9246         Intrinsic::ppc_altivec_vsraw
9247       };
9248       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9249       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9250     }
9251 
9252     // vsplti + rol self.
9253     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9254                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9255       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9256       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9257         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9258         Intrinsic::ppc_altivec_vrlw
9259       };
9260       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9261       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9262     }
9263 
9264     // t = vsplti c, result = vsldoi t, t, 1
9265     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9266       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9267       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9268       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9269     }
9270     // t = vsplti c, result = vsldoi t, t, 2
9271     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9272       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9273       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9274       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9275     }
9276     // t = vsplti c, result = vsldoi t, t, 3
9277     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9278       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9279       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9280       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9281     }
9282   }
9283 
9284   return SDValue();
9285 }
9286 
9287 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9288 /// the specified operations to build the shuffle.
9289 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9290                                       SDValue RHS, SelectionDAG &DAG,
9291                                       const SDLoc &dl) {
9292   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9293   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9294   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9295 
9296   enum {
9297     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9298     OP_VMRGHW,
9299     OP_VMRGLW,
9300     OP_VSPLTISW0,
9301     OP_VSPLTISW1,
9302     OP_VSPLTISW2,
9303     OP_VSPLTISW3,
9304     OP_VSLDOI4,
9305     OP_VSLDOI8,
9306     OP_VSLDOI12
9307   };
9308 
9309   if (OpNum == OP_COPY) {
9310     if (LHSID == (1*9+2)*9+3) return LHS;
9311     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9312     return RHS;
9313   }
9314 
9315   SDValue OpLHS, OpRHS;
9316   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9317   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9318 
9319   int ShufIdxs[16];
9320   switch (OpNum) {
9321   default: llvm_unreachable("Unknown i32 permute!");
9322   case OP_VMRGHW:
9323     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9324     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9325     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9326     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9327     break;
9328   case OP_VMRGLW:
9329     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9330     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9331     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9332     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9333     break;
9334   case OP_VSPLTISW0:
9335     for (unsigned i = 0; i != 16; ++i)
9336       ShufIdxs[i] = (i&3)+0;
9337     break;
9338   case OP_VSPLTISW1:
9339     for (unsigned i = 0; i != 16; ++i)
9340       ShufIdxs[i] = (i&3)+4;
9341     break;
9342   case OP_VSPLTISW2:
9343     for (unsigned i = 0; i != 16; ++i)
9344       ShufIdxs[i] = (i&3)+8;
9345     break;
9346   case OP_VSPLTISW3:
9347     for (unsigned i = 0; i != 16; ++i)
9348       ShufIdxs[i] = (i&3)+12;
9349     break;
9350   case OP_VSLDOI4:
9351     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9352   case OP_VSLDOI8:
9353     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9354   case OP_VSLDOI12:
9355     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9356   }
9357   EVT VT = OpLHS.getValueType();
9358   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9359   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9360   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9361   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9362 }
9363 
9364 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9365 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9366 /// SDValue.
9367 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9368                                            SelectionDAG &DAG) const {
9369   const unsigned BytesInVector = 16;
9370   bool IsLE = Subtarget.isLittleEndian();
9371   SDLoc dl(N);
9372   SDValue V1 = N->getOperand(0);
9373   SDValue V2 = N->getOperand(1);
9374   unsigned ShiftElts = 0, InsertAtByte = 0;
9375   bool Swap = false;
9376 
9377   // Shifts required to get the byte we want at element 7.
9378   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9379                                    0, 15, 14, 13, 12, 11, 10, 9};
9380   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9381                                 1, 2,  3,  4,  5,  6,  7,  8};
9382 
9383   ArrayRef<int> Mask = N->getMask();
9384   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9385 
9386   // For each mask element, find out if we're just inserting something
9387   // from V2 into V1 or vice versa.
9388   // Possible permutations inserting an element from V2 into V1:
9389   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9390   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9391   //   ...
9392   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9393   // Inserting from V1 into V2 will be similar, except mask range will be
9394   // [16,31].
9395 
9396   bool FoundCandidate = false;
9397   // If both vector operands for the shuffle are the same vector, the mask
9398   // will contain only elements from the first one and the second one will be
9399   // undef.
9400   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9401   // Go through the mask of half-words to find an element that's being moved
9402   // from one vector to the other.
9403   for (unsigned i = 0; i < BytesInVector; ++i) {
9404     unsigned CurrentElement = Mask[i];
9405     // If 2nd operand is undefined, we should only look for element 7 in the
9406     // Mask.
9407     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9408       continue;
9409 
9410     bool OtherElementsInOrder = true;
9411     // Examine the other elements in the Mask to see if they're in original
9412     // order.
9413     for (unsigned j = 0; j < BytesInVector; ++j) {
9414       if (j == i)
9415         continue;
9416       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9417       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9418       // in which we always assume we're always picking from the 1st operand.
9419       int MaskOffset =
9420           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9421       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9422         OtherElementsInOrder = false;
9423         break;
9424       }
9425     }
9426     // If other elements are in original order, we record the number of shifts
9427     // we need to get the element we want into element 7. Also record which byte
9428     // in the vector we should insert into.
9429     if (OtherElementsInOrder) {
9430       // If 2nd operand is undefined, we assume no shifts and no swapping.
9431       if (V2.isUndef()) {
9432         ShiftElts = 0;
9433         Swap = false;
9434       } else {
9435         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9436         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9437                          : BigEndianShifts[CurrentElement & 0xF];
9438         Swap = CurrentElement < BytesInVector;
9439       }
9440       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9441       FoundCandidate = true;
9442       break;
9443     }
9444   }
9445 
9446   if (!FoundCandidate)
9447     return SDValue();
9448 
9449   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9450   // optionally with VECSHL if shift is required.
9451   if (Swap)
9452     std::swap(V1, V2);
9453   if (V2.isUndef())
9454     V2 = V1;
9455   if (ShiftElts) {
9456     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9457                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9458     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9459                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9460   }
9461   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9462                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9463 }
9464 
9465 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9466 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9467 /// SDValue.
9468 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9469                                            SelectionDAG &DAG) const {
9470   const unsigned NumHalfWords = 8;
9471   const unsigned BytesInVector = NumHalfWords * 2;
9472   // Check that the shuffle is on half-words.
9473   if (!isNByteElemShuffleMask(N, 2, 1))
9474     return SDValue();
9475 
9476   bool IsLE = Subtarget.isLittleEndian();
9477   SDLoc dl(N);
9478   SDValue V1 = N->getOperand(0);
9479   SDValue V2 = N->getOperand(1);
9480   unsigned ShiftElts = 0, InsertAtByte = 0;
9481   bool Swap = false;
9482 
9483   // Shifts required to get the half-word we want at element 3.
9484   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9485   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9486 
9487   uint32_t Mask = 0;
9488   uint32_t OriginalOrderLow = 0x1234567;
9489   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9490   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9491   // 32-bit space, only need 4-bit nibbles per element.
9492   for (unsigned i = 0; i < NumHalfWords; ++i) {
9493     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9494     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9495   }
9496 
9497   // For each mask element, find out if we're just inserting something
9498   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9499   // from V2 into V1:
9500   //   X, 1, 2, 3, 4, 5, 6, 7
9501   //   0, X, 2, 3, 4, 5, 6, 7
9502   //   0, 1, X, 3, 4, 5, 6, 7
9503   //   0, 1, 2, X, 4, 5, 6, 7
9504   //   0, 1, 2, 3, X, 5, 6, 7
9505   //   0, 1, 2, 3, 4, X, 6, 7
9506   //   0, 1, 2, 3, 4, 5, X, 7
9507   //   0, 1, 2, 3, 4, 5, 6, X
9508   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9509 
9510   bool FoundCandidate = false;
9511   // Go through the mask of half-words to find an element that's being moved
9512   // from one vector to the other.
9513   for (unsigned i = 0; i < NumHalfWords; ++i) {
9514     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9515     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9516     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9517     uint32_t TargetOrder = 0x0;
9518 
9519     // If both vector operands for the shuffle are the same vector, the mask
9520     // will contain only elements from the first one and the second one will be
9521     // undef.
9522     if (V2.isUndef()) {
9523       ShiftElts = 0;
9524       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9525       TargetOrder = OriginalOrderLow;
9526       Swap = false;
9527       // Skip if not the correct element or mask of other elements don't equal
9528       // to our expected order.
9529       if (MaskOneElt == VINSERTHSrcElem &&
9530           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9531         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9532         FoundCandidate = true;
9533         break;
9534       }
9535     } else { // If both operands are defined.
9536       // Target order is [8,15] if the current mask is between [0,7].
9537       TargetOrder =
9538           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9539       // Skip if mask of other elements don't equal our expected order.
9540       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9541         // We only need the last 3 bits for the number of shifts.
9542         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9543                          : BigEndianShifts[MaskOneElt & 0x7];
9544         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9545         Swap = MaskOneElt < NumHalfWords;
9546         FoundCandidate = true;
9547         break;
9548       }
9549     }
9550   }
9551 
9552   if (!FoundCandidate)
9553     return SDValue();
9554 
9555   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9556   // optionally with VECSHL if shift is required.
9557   if (Swap)
9558     std::swap(V1, V2);
9559   if (V2.isUndef())
9560     V2 = V1;
9561   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9562   if (ShiftElts) {
9563     // Double ShiftElts because we're left shifting on v16i8 type.
9564     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9565                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9566     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9567     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9568                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9569     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9570   }
9571   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9572   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9573                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9574   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9575 }
9576 
9577 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9578 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9579 /// return the default SDValue.
9580 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9581                                               SelectionDAG &DAG) const {
9582   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9583   // to v16i8. Peek through the bitcasts to get the actual operands.
9584   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9585   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9586 
9587   auto ShuffleMask = SVN->getMask();
9588   SDValue VecShuffle(SVN, 0);
9589   SDLoc DL(SVN);
9590 
9591   // Check that we have a four byte shuffle.
9592   if (!isNByteElemShuffleMask(SVN, 4, 1))
9593     return SDValue();
9594 
9595   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9596   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9597     std::swap(LHS, RHS);
9598     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9599     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9600   }
9601 
9602   // Ensure that the RHS is a vector of constants.
9603   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9604   if (!BVN)
9605     return SDValue();
9606 
9607   // Check if RHS is a splat of 4-bytes (or smaller).
9608   APInt APSplatValue, APSplatUndef;
9609   unsigned SplatBitSize;
9610   bool HasAnyUndefs;
9611   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9612                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9613       SplatBitSize > 32)
9614     return SDValue();
9615 
9616   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9617   // The instruction splats a constant C into two words of the source vector
9618   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9619   // Thus we check that the shuffle mask is the equivalent  of
9620   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9621   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9622   // within each word are consecutive, so we only need to check the first byte.
9623   SDValue Index;
9624   bool IsLE = Subtarget.isLittleEndian();
9625   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9626       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9627        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9628     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9629   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9630            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9631             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9632     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9633   else
9634     return SDValue();
9635 
9636   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9637   // for XXSPLTI32DX.
9638   unsigned SplatVal = APSplatValue.getZExtValue();
9639   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9640     SplatVal |= (SplatVal << SplatBitSize);
9641 
9642   SDValue SplatNode = DAG.getNode(
9643       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9644       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9645   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9646 }
9647 
9648 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9649 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9650 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9651 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9652 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9653   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9654   assert(Op.getValueType() == MVT::v1i128 &&
9655          "Only set v1i128 as custom, other type shouldn't reach here!");
9656   SDLoc dl(Op);
9657   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9658   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9659   unsigned SHLAmt = N1.getConstantOperandVal(0);
9660   if (SHLAmt % 8 == 0) {
9661     SmallVector<int, 16> Mask(16, 0);
9662     std::iota(Mask.begin(), Mask.end(), 0);
9663     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9664     if (SDValue Shuffle =
9665             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9666                                  DAG.getUNDEF(MVT::v16i8), Mask))
9667       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9668   }
9669   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9670   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9671                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9672   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9673                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9674   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9675   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9676 }
9677 
9678 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9679 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9680 /// return the code it can be lowered into.  Worst case, it can always be
9681 /// lowered into a vperm.
9682 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9683                                                SelectionDAG &DAG) const {
9684   SDLoc dl(Op);
9685   SDValue V1 = Op.getOperand(0);
9686   SDValue V2 = Op.getOperand(1);
9687   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9688 
9689   // Any nodes that were combined in the target-independent combiner prior
9690   // to vector legalization will not be sent to the target combine. Try to
9691   // combine it here.
9692   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9693     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9694       return NewShuffle;
9695     Op = NewShuffle;
9696     SVOp = cast<ShuffleVectorSDNode>(Op);
9697     V1 = Op.getOperand(0);
9698     V2 = Op.getOperand(1);
9699   }
9700   EVT VT = Op.getValueType();
9701   bool isLittleEndian = Subtarget.isLittleEndian();
9702 
9703   unsigned ShiftElts, InsertAtByte;
9704   bool Swap = false;
9705 
9706   // If this is a load-and-splat, we can do that with a single instruction
9707   // in some cases. However if the load has multiple uses, we don't want to
9708   // combine it because that will just produce multiple loads.
9709   bool IsPermutedLoad = false;
9710   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9711   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9712       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9713       InputLoad->hasOneUse()) {
9714     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9715     int SplatIdx =
9716       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9717 
9718     // The splat index for permuted loads will be in the left half of the vector
9719     // which is strictly wider than the loaded value by 8 bytes. So we need to
9720     // adjust the splat index to point to the correct address in memory.
9721     if (IsPermutedLoad) {
9722       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9723       SplatIdx += IsFourByte ? 2 : 1;
9724       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9725              "Splat of a value outside of the loaded memory");
9726     }
9727 
9728     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9729     // For 4-byte load-and-splat, we need Power9.
9730     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9731       uint64_t Offset = 0;
9732       if (IsFourByte)
9733         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9734       else
9735         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9736 
9737       SDValue BasePtr = LD->getBasePtr();
9738       if (Offset != 0)
9739         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9740                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9741       SDValue Ops[] = {
9742         LD->getChain(),    // Chain
9743         BasePtr,           // BasePtr
9744         DAG.getValueType(Op.getValueType()) // VT
9745       };
9746       SDVTList VTL =
9747         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9748       SDValue LdSplt =
9749         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9750                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9751       if (LdSplt.getValueType() != SVOp->getValueType(0))
9752         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9753       return LdSplt;
9754     }
9755   }
9756   if (Subtarget.hasP9Vector() &&
9757       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9758                            isLittleEndian)) {
9759     if (Swap)
9760       std::swap(V1, V2);
9761     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9762     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9763     if (ShiftElts) {
9764       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9765                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9766       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9767                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9768       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9769     }
9770     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9771                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9772     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9773   }
9774 
9775   if (Subtarget.hasPrefixInstrs()) {
9776     SDValue SplatInsertNode;
9777     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9778       return SplatInsertNode;
9779   }
9780 
9781   if (Subtarget.hasP9Altivec()) {
9782     SDValue NewISDNode;
9783     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9784       return NewISDNode;
9785 
9786     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9787       return NewISDNode;
9788   }
9789 
9790   if (Subtarget.hasVSX() &&
9791       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9792     if (Swap)
9793       std::swap(V1, V2);
9794     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9795     SDValue Conv2 =
9796         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9797 
9798     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9799                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9800     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9801   }
9802 
9803   if (Subtarget.hasVSX() &&
9804     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9805     if (Swap)
9806       std::swap(V1, V2);
9807     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9808     SDValue Conv2 =
9809         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9810 
9811     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9812                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9813     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9814   }
9815 
9816   if (Subtarget.hasP9Vector()) {
9817      if (PPC::isXXBRHShuffleMask(SVOp)) {
9818       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9819       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9820       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9821     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9822       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9823       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9824       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9825     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9826       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9827       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9828       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9829     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9830       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9831       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9832       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9833     }
9834   }
9835 
9836   if (Subtarget.hasVSX()) {
9837     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9838       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9839 
9840       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9841       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9842                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9843       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9844     }
9845 
9846     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9847     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9848       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9849       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9850       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9851     }
9852   }
9853 
9854   // Cases that are handled by instructions that take permute immediates
9855   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9856   // selected by the instruction selector.
9857   if (V2.isUndef()) {
9858     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9859         PPC::isSplatShuffleMask(SVOp, 2) ||
9860         PPC::isSplatShuffleMask(SVOp, 4) ||
9861         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9862         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9863         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9864         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9865         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9866         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9867         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9868         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9869         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9870         (Subtarget.hasP8Altivec() && (
9871          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9872          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9873          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9874       return Op;
9875     }
9876   }
9877 
9878   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9879   // and produce a fixed permutation.  If any of these match, do not lower to
9880   // VPERM.
9881   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9882   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9883       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9884       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9885       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9886       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9887       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9888       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9889       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9890       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9891       (Subtarget.hasP8Altivec() && (
9892        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9893        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9894        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9895     return Op;
9896 
9897   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9898   // perfect shuffle table to emit an optimal matching sequence.
9899   ArrayRef<int> PermMask = SVOp->getMask();
9900 
9901   unsigned PFIndexes[4];
9902   bool isFourElementShuffle = true;
9903   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9904     unsigned EltNo = 8;   // Start out undef.
9905     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9906       if (PermMask[i*4+j] < 0)
9907         continue;   // Undef, ignore it.
9908 
9909       unsigned ByteSource = PermMask[i*4+j];
9910       if ((ByteSource & 3) != j) {
9911         isFourElementShuffle = false;
9912         break;
9913       }
9914 
9915       if (EltNo == 8) {
9916         EltNo = ByteSource/4;
9917       } else if (EltNo != ByteSource/4) {
9918         isFourElementShuffle = false;
9919         break;
9920       }
9921     }
9922     PFIndexes[i] = EltNo;
9923   }
9924 
9925   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9926   // perfect shuffle vector to determine if it is cost effective to do this as
9927   // discrete instructions, or whether we should use a vperm.
9928   // For now, we skip this for little endian until such time as we have a
9929   // little-endian perfect shuffle table.
9930   if (isFourElementShuffle && !isLittleEndian) {
9931     // Compute the index in the perfect shuffle table.
9932     unsigned PFTableIndex =
9933       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9934 
9935     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9936     unsigned Cost  = (PFEntry >> 30);
9937 
9938     // Determining when to avoid vperm is tricky.  Many things affect the cost
9939     // of vperm, particularly how many times the perm mask needs to be computed.
9940     // For example, if the perm mask can be hoisted out of a loop or is already
9941     // used (perhaps because there are multiple permutes with the same shuffle
9942     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9943     // the loop requires an extra register.
9944     //
9945     // As a compromise, we only emit discrete instructions if the shuffle can be
9946     // generated in 3 or fewer operations.  When we have loop information
9947     // available, if this block is within a loop, we should avoid using vperm
9948     // for 3-operation perms and use a constant pool load instead.
9949     if (Cost < 3)
9950       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9951   }
9952 
9953   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9954   // vector that will get spilled to the constant pool.
9955   if (V2.isUndef()) V2 = V1;
9956 
9957   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9958   // that it is in input element units, not in bytes.  Convert now.
9959 
9960   // For little endian, the order of the input vectors is reversed, and
9961   // the permutation mask is complemented with respect to 31.  This is
9962   // necessary to produce proper semantics with the big-endian-biased vperm
9963   // instruction.
9964   EVT EltVT = V1.getValueType().getVectorElementType();
9965   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9966 
9967   SmallVector<SDValue, 16> ResultMask;
9968   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9969     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9970 
9971     for (unsigned j = 0; j != BytesPerElement; ++j)
9972       if (isLittleEndian)
9973         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9974                                              dl, MVT::i32));
9975       else
9976         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9977                                              MVT::i32));
9978   }
9979 
9980   ShufflesHandledWithVPERM++;
9981   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9982   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9983   LLVM_DEBUG(SVOp->dump());
9984   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9985   LLVM_DEBUG(VPermMask.dump());
9986 
9987   if (isLittleEndian)
9988     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9989                        V2, V1, VPermMask);
9990   else
9991     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9992                        V1, V2, VPermMask);
9993 }
9994 
9995 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9996 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9997 /// information about the intrinsic.
9998 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9999                                  bool &isDot, const PPCSubtarget &Subtarget) {
10000   unsigned IntrinsicID =
10001       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10002   CompareOpc = -1;
10003   isDot = false;
10004   switch (IntrinsicID) {
10005   default:
10006     return false;
10007   // Comparison predicates.
10008   case Intrinsic::ppc_altivec_vcmpbfp_p:
10009     CompareOpc = 966;
10010     isDot = true;
10011     break;
10012   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10013     CompareOpc = 198;
10014     isDot = true;
10015     break;
10016   case Intrinsic::ppc_altivec_vcmpequb_p:
10017     CompareOpc = 6;
10018     isDot = true;
10019     break;
10020   case Intrinsic::ppc_altivec_vcmpequh_p:
10021     CompareOpc = 70;
10022     isDot = true;
10023     break;
10024   case Intrinsic::ppc_altivec_vcmpequw_p:
10025     CompareOpc = 134;
10026     isDot = true;
10027     break;
10028   case Intrinsic::ppc_altivec_vcmpequd_p:
10029     if (Subtarget.hasP8Altivec()) {
10030       CompareOpc = 199;
10031       isDot = true;
10032     } else
10033       return false;
10034     break;
10035   case Intrinsic::ppc_altivec_vcmpneb_p:
10036   case Intrinsic::ppc_altivec_vcmpneh_p:
10037   case Intrinsic::ppc_altivec_vcmpnew_p:
10038   case Intrinsic::ppc_altivec_vcmpnezb_p:
10039   case Intrinsic::ppc_altivec_vcmpnezh_p:
10040   case Intrinsic::ppc_altivec_vcmpnezw_p:
10041     if (Subtarget.hasP9Altivec()) {
10042       switch (IntrinsicID) {
10043       default:
10044         llvm_unreachable("Unknown comparison intrinsic.");
10045       case Intrinsic::ppc_altivec_vcmpneb_p:
10046         CompareOpc = 7;
10047         break;
10048       case Intrinsic::ppc_altivec_vcmpneh_p:
10049         CompareOpc = 71;
10050         break;
10051       case Intrinsic::ppc_altivec_vcmpnew_p:
10052         CompareOpc = 135;
10053         break;
10054       case Intrinsic::ppc_altivec_vcmpnezb_p:
10055         CompareOpc = 263;
10056         break;
10057       case Intrinsic::ppc_altivec_vcmpnezh_p:
10058         CompareOpc = 327;
10059         break;
10060       case Intrinsic::ppc_altivec_vcmpnezw_p:
10061         CompareOpc = 391;
10062         break;
10063       }
10064       isDot = true;
10065     } else
10066       return false;
10067     break;
10068   case Intrinsic::ppc_altivec_vcmpgefp_p:
10069     CompareOpc = 454;
10070     isDot = true;
10071     break;
10072   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10073     CompareOpc = 710;
10074     isDot = true;
10075     break;
10076   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10077     CompareOpc = 774;
10078     isDot = true;
10079     break;
10080   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10081     CompareOpc = 838;
10082     isDot = true;
10083     break;
10084   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10085     CompareOpc = 902;
10086     isDot = true;
10087     break;
10088   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10089     if (Subtarget.hasP8Altivec()) {
10090       CompareOpc = 967;
10091       isDot = true;
10092     } else
10093       return false;
10094     break;
10095   case Intrinsic::ppc_altivec_vcmpgtub_p:
10096     CompareOpc = 518;
10097     isDot = true;
10098     break;
10099   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10100     CompareOpc = 582;
10101     isDot = true;
10102     break;
10103   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10104     CompareOpc = 646;
10105     isDot = true;
10106     break;
10107   case Intrinsic::ppc_altivec_vcmpgtud_p:
10108     if (Subtarget.hasP8Altivec()) {
10109       CompareOpc = 711;
10110       isDot = true;
10111     } else
10112       return false;
10113     break;
10114 
10115   // VSX predicate comparisons use the same infrastructure
10116   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10117   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10118   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10119   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10120   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10121   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10122     if (Subtarget.hasVSX()) {
10123       switch (IntrinsicID) {
10124       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10125         CompareOpc = 99;
10126         break;
10127       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10128         CompareOpc = 115;
10129         break;
10130       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10131         CompareOpc = 107;
10132         break;
10133       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10134         CompareOpc = 67;
10135         break;
10136       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10137         CompareOpc = 83;
10138         break;
10139       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10140         CompareOpc = 75;
10141         break;
10142       }
10143       isDot = true;
10144     } else
10145       return false;
10146     break;
10147 
10148   // Normal Comparisons.
10149   case Intrinsic::ppc_altivec_vcmpbfp:
10150     CompareOpc = 966;
10151     break;
10152   case Intrinsic::ppc_altivec_vcmpeqfp:
10153     CompareOpc = 198;
10154     break;
10155   case Intrinsic::ppc_altivec_vcmpequb:
10156     CompareOpc = 6;
10157     break;
10158   case Intrinsic::ppc_altivec_vcmpequh:
10159     CompareOpc = 70;
10160     break;
10161   case Intrinsic::ppc_altivec_vcmpequw:
10162     CompareOpc = 134;
10163     break;
10164   case Intrinsic::ppc_altivec_vcmpequd:
10165     if (Subtarget.hasP8Altivec())
10166       CompareOpc = 199;
10167     else
10168       return false;
10169     break;
10170   case Intrinsic::ppc_altivec_vcmpneb:
10171   case Intrinsic::ppc_altivec_vcmpneh:
10172   case Intrinsic::ppc_altivec_vcmpnew:
10173   case Intrinsic::ppc_altivec_vcmpnezb:
10174   case Intrinsic::ppc_altivec_vcmpnezh:
10175   case Intrinsic::ppc_altivec_vcmpnezw:
10176     if (Subtarget.hasP9Altivec())
10177       switch (IntrinsicID) {
10178       default:
10179         llvm_unreachable("Unknown comparison intrinsic.");
10180       case Intrinsic::ppc_altivec_vcmpneb:
10181         CompareOpc = 7;
10182         break;
10183       case Intrinsic::ppc_altivec_vcmpneh:
10184         CompareOpc = 71;
10185         break;
10186       case Intrinsic::ppc_altivec_vcmpnew:
10187         CompareOpc = 135;
10188         break;
10189       case Intrinsic::ppc_altivec_vcmpnezb:
10190         CompareOpc = 263;
10191         break;
10192       case Intrinsic::ppc_altivec_vcmpnezh:
10193         CompareOpc = 327;
10194         break;
10195       case Intrinsic::ppc_altivec_vcmpnezw:
10196         CompareOpc = 391;
10197         break;
10198       }
10199     else
10200       return false;
10201     break;
10202   case Intrinsic::ppc_altivec_vcmpgefp:
10203     CompareOpc = 454;
10204     break;
10205   case Intrinsic::ppc_altivec_vcmpgtfp:
10206     CompareOpc = 710;
10207     break;
10208   case Intrinsic::ppc_altivec_vcmpgtsb:
10209     CompareOpc = 774;
10210     break;
10211   case Intrinsic::ppc_altivec_vcmpgtsh:
10212     CompareOpc = 838;
10213     break;
10214   case Intrinsic::ppc_altivec_vcmpgtsw:
10215     CompareOpc = 902;
10216     break;
10217   case Intrinsic::ppc_altivec_vcmpgtsd:
10218     if (Subtarget.hasP8Altivec())
10219       CompareOpc = 967;
10220     else
10221       return false;
10222     break;
10223   case Intrinsic::ppc_altivec_vcmpgtub:
10224     CompareOpc = 518;
10225     break;
10226   case Intrinsic::ppc_altivec_vcmpgtuh:
10227     CompareOpc = 582;
10228     break;
10229   case Intrinsic::ppc_altivec_vcmpgtuw:
10230     CompareOpc = 646;
10231     break;
10232   case Intrinsic::ppc_altivec_vcmpgtud:
10233     if (Subtarget.hasP8Altivec())
10234       CompareOpc = 711;
10235     else
10236       return false;
10237     break;
10238   }
10239   return true;
10240 }
10241 
10242 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10243 /// lower, do it, otherwise return null.
10244 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10245                                                    SelectionDAG &DAG) const {
10246   unsigned IntrinsicID =
10247     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10248 
10249   SDLoc dl(Op);
10250 
10251   if (IntrinsicID == Intrinsic::thread_pointer) {
10252     // Reads the thread pointer register, used for __builtin_thread_pointer.
10253     if (Subtarget.isPPC64())
10254       return DAG.getRegister(PPC::X13, MVT::i64);
10255     return DAG.getRegister(PPC::R2, MVT::i32);
10256   }
10257 
10258   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10259   // opcode number of the comparison.
10260   int CompareOpc;
10261   bool isDot;
10262   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10263     return SDValue();    // Don't custom lower most intrinsics.
10264 
10265   // If this is a non-dot comparison, make the VCMP node and we are done.
10266   if (!isDot) {
10267     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10268                               Op.getOperand(1), Op.getOperand(2),
10269                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10270     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10271   }
10272 
10273   // Create the PPCISD altivec 'dot' comparison node.
10274   SDValue Ops[] = {
10275     Op.getOperand(2),  // LHS
10276     Op.getOperand(3),  // RHS
10277     DAG.getConstant(CompareOpc, dl, MVT::i32)
10278   };
10279   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10280   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10281 
10282   // Now that we have the comparison, emit a copy from the CR to a GPR.
10283   // This is flagged to the above dot comparison.
10284   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10285                                 DAG.getRegister(PPC::CR6, MVT::i32),
10286                                 CompNode.getValue(1));
10287 
10288   // Unpack the result based on how the target uses it.
10289   unsigned BitNo;   // Bit # of CR6.
10290   bool InvertBit;   // Invert result?
10291   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10292   default:  // Can't happen, don't crash on invalid number though.
10293   case 0:   // Return the value of the EQ bit of CR6.
10294     BitNo = 0; InvertBit = false;
10295     break;
10296   case 1:   // Return the inverted value of the EQ bit of CR6.
10297     BitNo = 0; InvertBit = true;
10298     break;
10299   case 2:   // Return the value of the LT bit of CR6.
10300     BitNo = 2; InvertBit = false;
10301     break;
10302   case 3:   // Return the inverted value of the LT bit of CR6.
10303     BitNo = 2; InvertBit = true;
10304     break;
10305   }
10306 
10307   // Shift the bit into the low position.
10308   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10309                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10310   // Isolate the bit.
10311   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10312                       DAG.getConstant(1, dl, MVT::i32));
10313 
10314   // If we are supposed to, toggle the bit.
10315   if (InvertBit)
10316     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10317                         DAG.getConstant(1, dl, MVT::i32));
10318   return Flags;
10319 }
10320 
10321 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10322                                                SelectionDAG &DAG) const {
10323   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10324   // the beginning of the argument list.
10325   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10326   SDLoc DL(Op);
10327   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10328   case Intrinsic::ppc_cfence: {
10329     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10330     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10331     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10332                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10333                                                   Op.getOperand(ArgStart + 1)),
10334                                       Op.getOperand(0)),
10335                    0);
10336   }
10337   default:
10338     break;
10339   }
10340   return SDValue();
10341 }
10342 
10343 // Lower scalar BSWAP64 to xxbrd.
10344 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10345   SDLoc dl(Op);
10346   // MTVSRDD
10347   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10348                    Op.getOperand(0));
10349   // XXBRD
10350   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10351   // MFVSRD
10352   int VectorIndex = 0;
10353   if (Subtarget.isLittleEndian())
10354     VectorIndex = 1;
10355   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10356                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10357   return Op;
10358 }
10359 
10360 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10361 // compared to a value that is atomically loaded (atomic loads zero-extend).
10362 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10363                                                 SelectionDAG &DAG) const {
10364   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10365          "Expecting an atomic compare-and-swap here.");
10366   SDLoc dl(Op);
10367   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10368   EVT MemVT = AtomicNode->getMemoryVT();
10369   if (MemVT.getSizeInBits() >= 32)
10370     return Op;
10371 
10372   SDValue CmpOp = Op.getOperand(2);
10373   // If this is already correctly zero-extended, leave it alone.
10374   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10375   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10376     return Op;
10377 
10378   // Clear the high bits of the compare operand.
10379   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10380   SDValue NewCmpOp =
10381     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10382                 DAG.getConstant(MaskVal, dl, MVT::i32));
10383 
10384   // Replace the existing compare operand with the properly zero-extended one.
10385   SmallVector<SDValue, 4> Ops;
10386   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10387     Ops.push_back(AtomicNode->getOperand(i));
10388   Ops[2] = NewCmpOp;
10389   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10390   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10391   auto NodeTy =
10392     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10393   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10394 }
10395 
10396 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10397                                                  SelectionDAG &DAG) const {
10398   SDLoc dl(Op);
10399   // Create a stack slot that is 16-byte aligned.
10400   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10401   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10402   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10403   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10404 
10405   // Store the input value into Value#0 of the stack slot.
10406   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10407                                MachinePointerInfo());
10408   // Load it out.
10409   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10410 }
10411 
10412 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10413                                                   SelectionDAG &DAG) const {
10414   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10415          "Should only be called for ISD::INSERT_VECTOR_ELT");
10416 
10417   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10418   // We have legal lowering for constant indices but not for variable ones.
10419   if (!C)
10420     return SDValue();
10421 
10422   EVT VT = Op.getValueType();
10423   SDLoc dl(Op);
10424   SDValue V1 = Op.getOperand(0);
10425   SDValue V2 = Op.getOperand(1);
10426   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10427   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10428     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10429     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10430     unsigned InsertAtElement = C->getZExtValue();
10431     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10432     if (Subtarget.isLittleEndian()) {
10433       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10434     }
10435     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10436                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10437   }
10438   return Op;
10439 }
10440 
10441 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10442   SDLoc dl(Op);
10443   if (Op.getValueType() == MVT::v4i32) {
10444     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10445 
10446     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10447     // +16 as shift amt.
10448     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10449     SDValue RHSSwap =   // = vrlw RHS, 16
10450       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10451 
10452     // Shrinkify inputs to v8i16.
10453     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10454     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10455     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10456 
10457     // Low parts multiplied together, generating 32-bit results (we ignore the
10458     // top parts).
10459     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10460                                         LHS, RHS, DAG, dl, MVT::v4i32);
10461 
10462     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10463                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10464     // Shift the high parts up 16 bits.
10465     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10466                               Neg16, DAG, dl);
10467     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10468   } else if (Op.getValueType() == MVT::v16i8) {
10469     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10470     bool isLittleEndian = Subtarget.isLittleEndian();
10471 
10472     // Multiply the even 8-bit parts, producing 16-bit sums.
10473     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10474                                            LHS, RHS, DAG, dl, MVT::v8i16);
10475     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10476 
10477     // Multiply the odd 8-bit parts, producing 16-bit sums.
10478     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10479                                           LHS, RHS, DAG, dl, MVT::v8i16);
10480     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10481 
10482     // Merge the results together.  Because vmuleub and vmuloub are
10483     // instructions with a big-endian bias, we must reverse the
10484     // element numbering and reverse the meaning of "odd" and "even"
10485     // when generating little endian code.
10486     int Ops[16];
10487     for (unsigned i = 0; i != 8; ++i) {
10488       if (isLittleEndian) {
10489         Ops[i*2  ] = 2*i;
10490         Ops[i*2+1] = 2*i+16;
10491       } else {
10492         Ops[i*2  ] = 2*i+1;
10493         Ops[i*2+1] = 2*i+1+16;
10494       }
10495     }
10496     if (isLittleEndian)
10497       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10498     else
10499       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10500   } else {
10501     llvm_unreachable("Unknown mul to lower!");
10502   }
10503 }
10504 
10505 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10506 
10507   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10508 
10509   EVT VT = Op.getValueType();
10510   assert(VT.isVector() &&
10511          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10512   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10513           VT == MVT::v16i8) &&
10514          "Unexpected vector element type!");
10515   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10516          "Current subtarget doesn't support smax v2i64!");
10517 
10518   // For vector abs, it can be lowered to:
10519   // abs x
10520   // ==>
10521   // y = -x
10522   // smax(x, y)
10523 
10524   SDLoc dl(Op);
10525   SDValue X = Op.getOperand(0);
10526   SDValue Zero = DAG.getConstant(0, dl, VT);
10527   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10528 
10529   // SMAX patch https://reviews.llvm.org/D47332
10530   // hasn't landed yet, so use intrinsic first here.
10531   // TODO: Should use SMAX directly once SMAX patch landed
10532   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10533   if (VT == MVT::v2i64)
10534     BifID = Intrinsic::ppc_altivec_vmaxsd;
10535   else if (VT == MVT::v8i16)
10536     BifID = Intrinsic::ppc_altivec_vmaxsh;
10537   else if (VT == MVT::v16i8)
10538     BifID = Intrinsic::ppc_altivec_vmaxsb;
10539 
10540   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10541 }
10542 
10543 // Custom lowering for fpext vf32 to v2f64
10544 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10545 
10546   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10547          "Should only be called for ISD::FP_EXTEND");
10548 
10549   // FIXME: handle extends from half precision float vectors on P9.
10550   // We only want to custom lower an extend from v2f32 to v2f64.
10551   if (Op.getValueType() != MVT::v2f64 ||
10552       Op.getOperand(0).getValueType() != MVT::v2f32)
10553     return SDValue();
10554 
10555   SDLoc dl(Op);
10556   SDValue Op0 = Op.getOperand(0);
10557 
10558   switch (Op0.getOpcode()) {
10559   default:
10560     return SDValue();
10561   case ISD::EXTRACT_SUBVECTOR: {
10562     assert(Op0.getNumOperands() == 2 &&
10563            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10564            "Node should have 2 operands with second one being a constant!");
10565 
10566     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10567       return SDValue();
10568 
10569     // Custom lower is only done for high or low doubleword.
10570     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10571     if (Idx % 2 != 0)
10572       return SDValue();
10573 
10574     // Since input is v4f32, at this point Idx is either 0 or 2.
10575     // Shift to get the doubleword position we want.
10576     int DWord = Idx >> 1;
10577 
10578     // High and low word positions are different on little endian.
10579     if (Subtarget.isLittleEndian())
10580       DWord ^= 0x1;
10581 
10582     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10583                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10584   }
10585   case ISD::FADD:
10586   case ISD::FMUL:
10587   case ISD::FSUB: {
10588     SDValue NewLoad[2];
10589     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10590       // Ensure both input are loads.
10591       SDValue LdOp = Op0.getOperand(i);
10592       if (LdOp.getOpcode() != ISD::LOAD)
10593         return SDValue();
10594       // Generate new load node.
10595       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10596       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10597       NewLoad[i] = DAG.getMemIntrinsicNode(
10598           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10599           LD->getMemoryVT(), LD->getMemOperand());
10600     }
10601     SDValue NewOp =
10602         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10603                     NewLoad[1], Op0.getNode()->getFlags());
10604     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10605                        DAG.getConstant(0, dl, MVT::i32));
10606   }
10607   case ISD::LOAD: {
10608     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10609     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10610     SDValue NewLd = DAG.getMemIntrinsicNode(
10611         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10612         LD->getMemoryVT(), LD->getMemOperand());
10613     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10614                        DAG.getConstant(0, dl, MVT::i32));
10615   }
10616   }
10617   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10618 }
10619 
10620 /// LowerOperation - Provide custom lowering hooks for some operations.
10621 ///
10622 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10623   switch (Op.getOpcode()) {
10624   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10625   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10626   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10627   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10628   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10629   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10630   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10631   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10632   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10633 
10634   // Variable argument lowering.
10635   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10636   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10637   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10638 
10639   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10640   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10641   case ISD::GET_DYNAMIC_AREA_OFFSET:
10642     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10643 
10644   // Exception handling lowering.
10645   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10646   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10647   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10648 
10649   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10650   case ISD::STORE:              return LowerSTORE(Op, DAG);
10651   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10652   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10653   case ISD::STRICT_FP_TO_UINT:
10654   case ISD::STRICT_FP_TO_SINT:
10655   case ISD::FP_TO_UINT:
10656   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10657   case ISD::STRICT_UINT_TO_FP:
10658   case ISD::STRICT_SINT_TO_FP:
10659   case ISD::UINT_TO_FP:
10660   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10661   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10662 
10663   // Lower 64-bit shifts.
10664   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10665   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10666   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10667 
10668   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10669   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10670 
10671   // Vector-related lowering.
10672   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10673   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10674   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10675   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10676   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10677   case ISD::MUL:                return LowerMUL(Op, DAG);
10678   case ISD::ABS:                return LowerABS(Op, DAG);
10679   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10680   case ISD::ROTL:               return LowerROTL(Op, DAG);
10681 
10682   // For counter-based loop handling.
10683   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10684 
10685   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10686 
10687   // Frame & Return address.
10688   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10689   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10690 
10691   case ISD::INTRINSIC_VOID:
10692     return LowerINTRINSIC_VOID(Op, DAG);
10693   case ISD::BSWAP:
10694     return LowerBSWAP(Op, DAG);
10695   case ISD::ATOMIC_CMP_SWAP:
10696     return LowerATOMIC_CMP_SWAP(Op, DAG);
10697   }
10698 }
10699 
10700 void PPCTargetLowering::LowerOperationWrapper(SDNode *N,
10701                                               SmallVectorImpl<SDValue> &Results,
10702                                               SelectionDAG &DAG) const {
10703   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10704 
10705   if (!Res.getNode())
10706     return;
10707 
10708   // Take the return value as-is if original node has only one result.
10709   if (N->getNumValues() == 1) {
10710     Results.push_back(Res);
10711     return;
10712   }
10713 
10714   // New node should have the same number of results.
10715   assert((N->getNumValues() == Res->getNumValues()) &&
10716       "Lowering returned the wrong number of results!");
10717 
10718   for (unsigned i = 0; i < N->getNumValues(); ++i)
10719     Results.push_back(Res.getValue(i));
10720 }
10721 
10722 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10723                                            SmallVectorImpl<SDValue>&Results,
10724                                            SelectionDAG &DAG) const {
10725   SDLoc dl(N);
10726   switch (N->getOpcode()) {
10727   default:
10728     llvm_unreachable("Do not know how to custom type legalize this operation!");
10729   case ISD::READCYCLECOUNTER: {
10730     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10731     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10732 
10733     Results.push_back(
10734         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10735     Results.push_back(RTB.getValue(2));
10736     break;
10737   }
10738   case ISD::INTRINSIC_W_CHAIN: {
10739     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10740         Intrinsic::loop_decrement)
10741       break;
10742 
10743     assert(N->getValueType(0) == MVT::i1 &&
10744            "Unexpected result type for CTR decrement intrinsic");
10745     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10746                                  N->getValueType(0));
10747     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10748     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10749                                  N->getOperand(1));
10750 
10751     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10752     Results.push_back(NewInt.getValue(1));
10753     break;
10754   }
10755   case ISD::VAARG: {
10756     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10757       return;
10758 
10759     EVT VT = N->getValueType(0);
10760 
10761     if (VT == MVT::i64) {
10762       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10763 
10764       Results.push_back(NewNode);
10765       Results.push_back(NewNode.getValue(1));
10766     }
10767     return;
10768   }
10769   case ISD::STRICT_FP_TO_SINT:
10770   case ISD::STRICT_FP_TO_UINT:
10771   case ISD::FP_TO_SINT:
10772   case ISD::FP_TO_UINT:
10773     // LowerFP_TO_INT() can only handle f32 and f64.
10774     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10775         MVT::ppcf128)
10776       return;
10777     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10778     return;
10779   case ISD::TRUNCATE: {
10780     if (!N->getValueType(0).isVector())
10781       return;
10782     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
10783     if (Lowered)
10784       Results.push_back(Lowered);
10785     return;
10786   }
10787   case ISD::BITCAST:
10788     // Don't handle bitcast here.
10789     return;
10790   case ISD::FP_EXTEND:
10791     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10792     if (Lowered)
10793       Results.push_back(Lowered);
10794     return;
10795   }
10796 }
10797 
10798 //===----------------------------------------------------------------------===//
10799 //  Other Lowering Code
10800 //===----------------------------------------------------------------------===//
10801 
10802 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10803   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10804   Function *Func = Intrinsic::getDeclaration(M, Id);
10805   return Builder.CreateCall(Func, {});
10806 }
10807 
10808 // The mappings for emitLeading/TrailingFence is taken from
10809 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10810 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10811                                                  Instruction *Inst,
10812                                                  AtomicOrdering Ord) const {
10813   if (Ord == AtomicOrdering::SequentiallyConsistent)
10814     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10815   if (isReleaseOrStronger(Ord))
10816     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10817   return nullptr;
10818 }
10819 
10820 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10821                                                   Instruction *Inst,
10822                                                   AtomicOrdering Ord) const {
10823   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10824     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10825     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10826     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10827     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10828       return Builder.CreateCall(
10829           Intrinsic::getDeclaration(
10830               Builder.GetInsertBlock()->getParent()->getParent(),
10831               Intrinsic::ppc_cfence, {Inst->getType()}),
10832           {Inst});
10833     // FIXME: Can use isync for rmw operation.
10834     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10835   }
10836   return nullptr;
10837 }
10838 
10839 MachineBasicBlock *
10840 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10841                                     unsigned AtomicSize,
10842                                     unsigned BinOpcode,
10843                                     unsigned CmpOpcode,
10844                                     unsigned CmpPred) const {
10845   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10846   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10847 
10848   auto LoadMnemonic = PPC::LDARX;
10849   auto StoreMnemonic = PPC::STDCX;
10850   switch (AtomicSize) {
10851   default:
10852     llvm_unreachable("Unexpected size of atomic entity");
10853   case 1:
10854     LoadMnemonic = PPC::LBARX;
10855     StoreMnemonic = PPC::STBCX;
10856     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10857     break;
10858   case 2:
10859     LoadMnemonic = PPC::LHARX;
10860     StoreMnemonic = PPC::STHCX;
10861     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10862     break;
10863   case 4:
10864     LoadMnemonic = PPC::LWARX;
10865     StoreMnemonic = PPC::STWCX;
10866     break;
10867   case 8:
10868     LoadMnemonic = PPC::LDARX;
10869     StoreMnemonic = PPC::STDCX;
10870     break;
10871   }
10872 
10873   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10874   MachineFunction *F = BB->getParent();
10875   MachineFunction::iterator It = ++BB->getIterator();
10876 
10877   Register dest = MI.getOperand(0).getReg();
10878   Register ptrA = MI.getOperand(1).getReg();
10879   Register ptrB = MI.getOperand(2).getReg();
10880   Register incr = MI.getOperand(3).getReg();
10881   DebugLoc dl = MI.getDebugLoc();
10882 
10883   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10884   MachineBasicBlock *loop2MBB =
10885     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10886   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10887   F->insert(It, loopMBB);
10888   if (CmpOpcode)
10889     F->insert(It, loop2MBB);
10890   F->insert(It, exitMBB);
10891   exitMBB->splice(exitMBB->begin(), BB,
10892                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10893   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10894 
10895   MachineRegisterInfo &RegInfo = F->getRegInfo();
10896   Register TmpReg = (!BinOpcode) ? incr :
10897     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10898                                            : &PPC::GPRCRegClass);
10899 
10900   //  thisMBB:
10901   //   ...
10902   //   fallthrough --> loopMBB
10903   BB->addSuccessor(loopMBB);
10904 
10905   //  loopMBB:
10906   //   l[wd]arx dest, ptr
10907   //   add r0, dest, incr
10908   //   st[wd]cx. r0, ptr
10909   //   bne- loopMBB
10910   //   fallthrough --> exitMBB
10911 
10912   // For max/min...
10913   //  loopMBB:
10914   //   l[wd]arx dest, ptr
10915   //   cmpl?[wd] incr, dest
10916   //   bgt exitMBB
10917   //  loop2MBB:
10918   //   st[wd]cx. dest, ptr
10919   //   bne- loopMBB
10920   //   fallthrough --> exitMBB
10921 
10922   BB = loopMBB;
10923   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10924     .addReg(ptrA).addReg(ptrB);
10925   if (BinOpcode)
10926     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10927   if (CmpOpcode) {
10928     // Signed comparisons of byte or halfword values must be sign-extended.
10929     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10930       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10931       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10932               ExtReg).addReg(dest);
10933       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10934         .addReg(incr).addReg(ExtReg);
10935     } else
10936       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10937         .addReg(incr).addReg(dest);
10938 
10939     BuildMI(BB, dl, TII->get(PPC::BCC))
10940       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10941     BB->addSuccessor(loop2MBB);
10942     BB->addSuccessor(exitMBB);
10943     BB = loop2MBB;
10944   }
10945   BuildMI(BB, dl, TII->get(StoreMnemonic))
10946     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10947   BuildMI(BB, dl, TII->get(PPC::BCC))
10948     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10949   BB->addSuccessor(loopMBB);
10950   BB->addSuccessor(exitMBB);
10951 
10952   //  exitMBB:
10953   //   ...
10954   BB = exitMBB;
10955   return BB;
10956 }
10957 
10958 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10959     MachineInstr &MI, MachineBasicBlock *BB,
10960     bool is8bit, // operation
10961     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10962   // If we support part-word atomic mnemonics, just use them
10963   if (Subtarget.hasPartwordAtomics())
10964     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10965                             CmpPred);
10966 
10967   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10968   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10969   // In 64 bit mode we have to use 64 bits for addresses, even though the
10970   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10971   // registers without caring whether they're 32 or 64, but here we're
10972   // doing actual arithmetic on the addresses.
10973   bool is64bit = Subtarget.isPPC64();
10974   bool isLittleEndian = Subtarget.isLittleEndian();
10975   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10976 
10977   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10978   MachineFunction *F = BB->getParent();
10979   MachineFunction::iterator It = ++BB->getIterator();
10980 
10981   Register dest = MI.getOperand(0).getReg();
10982   Register ptrA = MI.getOperand(1).getReg();
10983   Register ptrB = MI.getOperand(2).getReg();
10984   Register incr = MI.getOperand(3).getReg();
10985   DebugLoc dl = MI.getDebugLoc();
10986 
10987   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10988   MachineBasicBlock *loop2MBB =
10989       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10990   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10991   F->insert(It, loopMBB);
10992   if (CmpOpcode)
10993     F->insert(It, loop2MBB);
10994   F->insert(It, exitMBB);
10995   exitMBB->splice(exitMBB->begin(), BB,
10996                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10997   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10998 
10999   MachineRegisterInfo &RegInfo = F->getRegInfo();
11000   const TargetRegisterClass *RC =
11001       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11002   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11003 
11004   Register PtrReg = RegInfo.createVirtualRegister(RC);
11005   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11006   Register ShiftReg =
11007       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11008   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11009   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11010   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11011   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11012   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11013   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11014   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11015   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11016   Register Ptr1Reg;
11017   Register TmpReg =
11018       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11019 
11020   //  thisMBB:
11021   //   ...
11022   //   fallthrough --> loopMBB
11023   BB->addSuccessor(loopMBB);
11024 
11025   // The 4-byte load must be aligned, while a char or short may be
11026   // anywhere in the word.  Hence all this nasty bookkeeping code.
11027   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11028   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11029   //   xori shift, shift1, 24 [16]
11030   //   rlwinm ptr, ptr1, 0, 0, 29
11031   //   slw incr2, incr, shift
11032   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11033   //   slw mask, mask2, shift
11034   //  loopMBB:
11035   //   lwarx tmpDest, ptr
11036   //   add tmp, tmpDest, incr2
11037   //   andc tmp2, tmpDest, mask
11038   //   and tmp3, tmp, mask
11039   //   or tmp4, tmp3, tmp2
11040   //   stwcx. tmp4, ptr
11041   //   bne- loopMBB
11042   //   fallthrough --> exitMBB
11043   //   srw dest, tmpDest, shift
11044   if (ptrA != ZeroReg) {
11045     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11046     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11047         .addReg(ptrA)
11048         .addReg(ptrB);
11049   } else {
11050     Ptr1Reg = ptrB;
11051   }
11052   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11053   // mode.
11054   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11055       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11056       .addImm(3)
11057       .addImm(27)
11058       .addImm(is8bit ? 28 : 27);
11059   if (!isLittleEndian)
11060     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11061         .addReg(Shift1Reg)
11062         .addImm(is8bit ? 24 : 16);
11063   if (is64bit)
11064     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11065         .addReg(Ptr1Reg)
11066         .addImm(0)
11067         .addImm(61);
11068   else
11069     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11070         .addReg(Ptr1Reg)
11071         .addImm(0)
11072         .addImm(0)
11073         .addImm(29);
11074   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11075   if (is8bit)
11076     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11077   else {
11078     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11079     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11080         .addReg(Mask3Reg)
11081         .addImm(65535);
11082   }
11083   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11084       .addReg(Mask2Reg)
11085       .addReg(ShiftReg);
11086 
11087   BB = loopMBB;
11088   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11089       .addReg(ZeroReg)
11090       .addReg(PtrReg);
11091   if (BinOpcode)
11092     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11093         .addReg(Incr2Reg)
11094         .addReg(TmpDestReg);
11095   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11096       .addReg(TmpDestReg)
11097       .addReg(MaskReg);
11098   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11099   if (CmpOpcode) {
11100     // For unsigned comparisons, we can directly compare the shifted values.
11101     // For signed comparisons we shift and sign extend.
11102     Register SReg = RegInfo.createVirtualRegister(GPRC);
11103     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11104         .addReg(TmpDestReg)
11105         .addReg(MaskReg);
11106     unsigned ValueReg = SReg;
11107     unsigned CmpReg = Incr2Reg;
11108     if (CmpOpcode == PPC::CMPW) {
11109       ValueReg = RegInfo.createVirtualRegister(GPRC);
11110       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11111           .addReg(SReg)
11112           .addReg(ShiftReg);
11113       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11114       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11115           .addReg(ValueReg);
11116       ValueReg = ValueSReg;
11117       CmpReg = incr;
11118     }
11119     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11120         .addReg(CmpReg)
11121         .addReg(ValueReg);
11122     BuildMI(BB, dl, TII->get(PPC::BCC))
11123         .addImm(CmpPred)
11124         .addReg(PPC::CR0)
11125         .addMBB(exitMBB);
11126     BB->addSuccessor(loop2MBB);
11127     BB->addSuccessor(exitMBB);
11128     BB = loop2MBB;
11129   }
11130   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11131   BuildMI(BB, dl, TII->get(PPC::STWCX))
11132       .addReg(Tmp4Reg)
11133       .addReg(ZeroReg)
11134       .addReg(PtrReg);
11135   BuildMI(BB, dl, TII->get(PPC::BCC))
11136       .addImm(PPC::PRED_NE)
11137       .addReg(PPC::CR0)
11138       .addMBB(loopMBB);
11139   BB->addSuccessor(loopMBB);
11140   BB->addSuccessor(exitMBB);
11141 
11142   //  exitMBB:
11143   //   ...
11144   BB = exitMBB;
11145   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11146       .addReg(TmpDestReg)
11147       .addReg(ShiftReg);
11148   return BB;
11149 }
11150 
11151 llvm::MachineBasicBlock *
11152 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11153                                     MachineBasicBlock *MBB) const {
11154   DebugLoc DL = MI.getDebugLoc();
11155   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11156   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11157 
11158   MachineFunction *MF = MBB->getParent();
11159   MachineRegisterInfo &MRI = MF->getRegInfo();
11160 
11161   const BasicBlock *BB = MBB->getBasicBlock();
11162   MachineFunction::iterator I = ++MBB->getIterator();
11163 
11164   Register DstReg = MI.getOperand(0).getReg();
11165   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11166   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11167   Register mainDstReg = MRI.createVirtualRegister(RC);
11168   Register restoreDstReg = MRI.createVirtualRegister(RC);
11169 
11170   MVT PVT = getPointerTy(MF->getDataLayout());
11171   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11172          "Invalid Pointer Size!");
11173   // For v = setjmp(buf), we generate
11174   //
11175   // thisMBB:
11176   //  SjLjSetup mainMBB
11177   //  bl mainMBB
11178   //  v_restore = 1
11179   //  b sinkMBB
11180   //
11181   // mainMBB:
11182   //  buf[LabelOffset] = LR
11183   //  v_main = 0
11184   //
11185   // sinkMBB:
11186   //  v = phi(main, restore)
11187   //
11188 
11189   MachineBasicBlock *thisMBB = MBB;
11190   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11191   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11192   MF->insert(I, mainMBB);
11193   MF->insert(I, sinkMBB);
11194 
11195   MachineInstrBuilder MIB;
11196 
11197   // Transfer the remainder of BB and its successor edges to sinkMBB.
11198   sinkMBB->splice(sinkMBB->begin(), MBB,
11199                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11200   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11201 
11202   // Note that the structure of the jmp_buf used here is not compatible
11203   // with that used by libc, and is not designed to be. Specifically, it
11204   // stores only those 'reserved' registers that LLVM does not otherwise
11205   // understand how to spill. Also, by convention, by the time this
11206   // intrinsic is called, Clang has already stored the frame address in the
11207   // first slot of the buffer and stack address in the third. Following the
11208   // X86 target code, we'll store the jump address in the second slot. We also
11209   // need to save the TOC pointer (R2) to handle jumps between shared
11210   // libraries, and that will be stored in the fourth slot. The thread
11211   // identifier (R13) is not affected.
11212 
11213   // thisMBB:
11214   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11215   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11216   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11217 
11218   // Prepare IP either in reg.
11219   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11220   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11221   Register BufReg = MI.getOperand(1).getReg();
11222 
11223   if (Subtarget.is64BitELFABI()) {
11224     setUsesTOCBasePtr(*MBB->getParent());
11225     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11226               .addReg(PPC::X2)
11227               .addImm(TOCOffset)
11228               .addReg(BufReg)
11229               .cloneMemRefs(MI);
11230   }
11231 
11232   // Naked functions never have a base pointer, and so we use r1. For all
11233   // other functions, this decision must be delayed until during PEI.
11234   unsigned BaseReg;
11235   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11236     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11237   else
11238     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11239 
11240   MIB = BuildMI(*thisMBB, MI, DL,
11241                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11242             .addReg(BaseReg)
11243             .addImm(BPOffset)
11244             .addReg(BufReg)
11245             .cloneMemRefs(MI);
11246 
11247   // Setup
11248   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11249   MIB.addRegMask(TRI->getNoPreservedMask());
11250 
11251   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11252 
11253   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11254           .addMBB(mainMBB);
11255   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11256 
11257   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11258   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11259 
11260   // mainMBB:
11261   //  mainDstReg = 0
11262   MIB =
11263       BuildMI(mainMBB, DL,
11264               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11265 
11266   // Store IP
11267   if (Subtarget.isPPC64()) {
11268     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11269             .addReg(LabelReg)
11270             .addImm(LabelOffset)
11271             .addReg(BufReg);
11272   } else {
11273     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11274             .addReg(LabelReg)
11275             .addImm(LabelOffset)
11276             .addReg(BufReg);
11277   }
11278   MIB.cloneMemRefs(MI);
11279 
11280   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11281   mainMBB->addSuccessor(sinkMBB);
11282 
11283   // sinkMBB:
11284   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11285           TII->get(PPC::PHI), DstReg)
11286     .addReg(mainDstReg).addMBB(mainMBB)
11287     .addReg(restoreDstReg).addMBB(thisMBB);
11288 
11289   MI.eraseFromParent();
11290   return sinkMBB;
11291 }
11292 
11293 MachineBasicBlock *
11294 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11295                                      MachineBasicBlock *MBB) const {
11296   DebugLoc DL = MI.getDebugLoc();
11297   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11298 
11299   MachineFunction *MF = MBB->getParent();
11300   MachineRegisterInfo &MRI = MF->getRegInfo();
11301 
11302   MVT PVT = getPointerTy(MF->getDataLayout());
11303   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11304          "Invalid Pointer Size!");
11305 
11306   const TargetRegisterClass *RC =
11307     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11308   Register Tmp = MRI.createVirtualRegister(RC);
11309   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11310   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11311   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11312   unsigned BP =
11313       (PVT == MVT::i64)
11314           ? PPC::X30
11315           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11316                                                               : PPC::R30);
11317 
11318   MachineInstrBuilder MIB;
11319 
11320   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11321   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11322   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11323   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11324 
11325   Register BufReg = MI.getOperand(0).getReg();
11326 
11327   // Reload FP (the jumped-to function may not have had a
11328   // frame pointer, and if so, then its r31 will be restored
11329   // as necessary).
11330   if (PVT == MVT::i64) {
11331     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11332             .addImm(0)
11333             .addReg(BufReg);
11334   } else {
11335     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11336             .addImm(0)
11337             .addReg(BufReg);
11338   }
11339   MIB.cloneMemRefs(MI);
11340 
11341   // Reload IP
11342   if (PVT == MVT::i64) {
11343     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11344             .addImm(LabelOffset)
11345             .addReg(BufReg);
11346   } else {
11347     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11348             .addImm(LabelOffset)
11349             .addReg(BufReg);
11350   }
11351   MIB.cloneMemRefs(MI);
11352 
11353   // Reload SP
11354   if (PVT == MVT::i64) {
11355     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11356             .addImm(SPOffset)
11357             .addReg(BufReg);
11358   } else {
11359     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11360             .addImm(SPOffset)
11361             .addReg(BufReg);
11362   }
11363   MIB.cloneMemRefs(MI);
11364 
11365   // Reload BP
11366   if (PVT == MVT::i64) {
11367     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11368             .addImm(BPOffset)
11369             .addReg(BufReg);
11370   } else {
11371     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11372             .addImm(BPOffset)
11373             .addReg(BufReg);
11374   }
11375   MIB.cloneMemRefs(MI);
11376 
11377   // Reload TOC
11378   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11379     setUsesTOCBasePtr(*MBB->getParent());
11380     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11381               .addImm(TOCOffset)
11382               .addReg(BufReg)
11383               .cloneMemRefs(MI);
11384   }
11385 
11386   // Jump
11387   BuildMI(*MBB, MI, DL,
11388           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11389   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11390 
11391   MI.eraseFromParent();
11392   return MBB;
11393 }
11394 
11395 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11396   // If the function specifically requests inline stack probes, emit them.
11397   if (MF.getFunction().hasFnAttribute("probe-stack"))
11398     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11399            "inline-asm";
11400   return false;
11401 }
11402 
11403 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11404   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11405   unsigned StackAlign = TFI->getStackAlignment();
11406   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11407          "Unexpected stack alignment");
11408   // The default stack probe size is 4096 if the function has no
11409   // stack-probe-size attribute.
11410   unsigned StackProbeSize = 4096;
11411   const Function &Fn = MF.getFunction();
11412   if (Fn.hasFnAttribute("stack-probe-size"))
11413     Fn.getFnAttribute("stack-probe-size")
11414         .getValueAsString()
11415         .getAsInteger(0, StackProbeSize);
11416   // Round down to the stack alignment.
11417   StackProbeSize &= ~(StackAlign - 1);
11418   return StackProbeSize ? StackProbeSize : StackAlign;
11419 }
11420 
11421 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11422 // into three phases. In the first phase, it uses pseudo instruction
11423 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11424 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11425 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11426 // MaxCallFrameSize so that it can calculate correct data area pointer.
11427 MachineBasicBlock *
11428 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11429                                     MachineBasicBlock *MBB) const {
11430   const bool isPPC64 = Subtarget.isPPC64();
11431   MachineFunction *MF = MBB->getParent();
11432   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11433   DebugLoc DL = MI.getDebugLoc();
11434   const unsigned ProbeSize = getStackProbeSize(*MF);
11435   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11436   MachineRegisterInfo &MRI = MF->getRegInfo();
11437   // The CFG of probing stack looks as
11438   //         +-----+
11439   //         | MBB |
11440   //         +--+--+
11441   //            |
11442   //       +----v----+
11443   //  +--->+ TestMBB +---+
11444   //  |    +----+----+   |
11445   //  |         |        |
11446   //  |   +-----v----+   |
11447   //  +---+ BlockMBB |   |
11448   //      +----------+   |
11449   //                     |
11450   //       +---------+   |
11451   //       | TailMBB +<--+
11452   //       +---------+
11453   // In MBB, calculate previous frame pointer and final stack pointer.
11454   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11455   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11456   // TailMBB is spliced via \p MI.
11457   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11458   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11459   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11460 
11461   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11462   MF->insert(MBBIter, TestMBB);
11463   MF->insert(MBBIter, BlockMBB);
11464   MF->insert(MBBIter, TailMBB);
11465 
11466   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11467   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11468 
11469   Register DstReg = MI.getOperand(0).getReg();
11470   Register NegSizeReg = MI.getOperand(1).getReg();
11471   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11472   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11473   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11474   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11475 
11476   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11477   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11478   // NegSize.
11479   unsigned ProbeOpc;
11480   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11481     ProbeOpc =
11482         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11483   else
11484     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11485     // and NegSizeReg will be allocated in the same phyreg to avoid
11486     // redundant copy when NegSizeReg has only one use which is current MI and
11487     // will be replaced by PREPARE_PROBED_ALLOCA then.
11488     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11489                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11490   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11491       .addDef(ActualNegSizeReg)
11492       .addReg(NegSizeReg)
11493       .add(MI.getOperand(2))
11494       .add(MI.getOperand(3));
11495 
11496   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11497   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11498           FinalStackPtr)
11499       .addReg(SPReg)
11500       .addReg(ActualNegSizeReg);
11501 
11502   // Materialize a scratch register for update.
11503   int64_t NegProbeSize = -(int64_t)ProbeSize;
11504   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11505   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11506   if (!isInt<16>(NegProbeSize)) {
11507     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11508     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11509         .addImm(NegProbeSize >> 16);
11510     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11511             ScratchReg)
11512         .addReg(TempReg)
11513         .addImm(NegProbeSize & 0xFFFF);
11514   } else
11515     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11516         .addImm(NegProbeSize);
11517 
11518   {
11519     // Probing leading residual part.
11520     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11521     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11522         .addReg(ActualNegSizeReg)
11523         .addReg(ScratchReg);
11524     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11525     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11526         .addReg(Div)
11527         .addReg(ScratchReg);
11528     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11529     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11530         .addReg(Mul)
11531         .addReg(ActualNegSizeReg);
11532     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11533         .addReg(FramePointer)
11534         .addReg(SPReg)
11535         .addReg(NegMod);
11536   }
11537 
11538   {
11539     // Remaining part should be multiple of ProbeSize.
11540     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11541     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11542         .addReg(SPReg)
11543         .addReg(FinalStackPtr);
11544     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11545         .addImm(PPC::PRED_EQ)
11546         .addReg(CmpResult)
11547         .addMBB(TailMBB);
11548     TestMBB->addSuccessor(BlockMBB);
11549     TestMBB->addSuccessor(TailMBB);
11550   }
11551 
11552   {
11553     // Touch the block.
11554     // |P...|P...|P...
11555     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11556         .addReg(FramePointer)
11557         .addReg(SPReg)
11558         .addReg(ScratchReg);
11559     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11560     BlockMBB->addSuccessor(TestMBB);
11561   }
11562 
11563   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11564   // DYNAREAOFFSET pseudo instruction to get the future result.
11565   Register MaxCallFrameSizeReg =
11566       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11567   BuildMI(TailMBB, DL,
11568           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11569           MaxCallFrameSizeReg)
11570       .add(MI.getOperand(2))
11571       .add(MI.getOperand(3));
11572   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11573       .addReg(SPReg)
11574       .addReg(MaxCallFrameSizeReg);
11575 
11576   // Splice instructions after MI to TailMBB.
11577   TailMBB->splice(TailMBB->end(), MBB,
11578                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11579   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11580   MBB->addSuccessor(TestMBB);
11581 
11582   // Delete the pseudo instruction.
11583   MI.eraseFromParent();
11584 
11585   ++NumDynamicAllocaProbed;
11586   return TailMBB;
11587 }
11588 
11589 MachineBasicBlock *
11590 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11591                                                MachineBasicBlock *BB) const {
11592   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11593       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11594     if (Subtarget.is64BitELFABI() &&
11595         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11596         !Subtarget.isUsingPCRelativeCalls()) {
11597       // Call lowering should have added an r2 operand to indicate a dependence
11598       // on the TOC base pointer value. It can't however, because there is no
11599       // way to mark the dependence as implicit there, and so the stackmap code
11600       // will confuse it with a regular operand. Instead, add the dependence
11601       // here.
11602       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11603     }
11604 
11605     return emitPatchPoint(MI, BB);
11606   }
11607 
11608   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11609       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11610     return emitEHSjLjSetJmp(MI, BB);
11611   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11612              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11613     return emitEHSjLjLongJmp(MI, BB);
11614   }
11615 
11616   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11617 
11618   // To "insert" these instructions we actually have to insert their
11619   // control-flow patterns.
11620   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11621   MachineFunction::iterator It = ++BB->getIterator();
11622 
11623   MachineFunction *F = BB->getParent();
11624 
11625   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11626       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11627       MI.getOpcode() == PPC::SELECT_I8) {
11628     SmallVector<MachineOperand, 2> Cond;
11629     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11630         MI.getOpcode() == PPC::SELECT_CC_I8)
11631       Cond.push_back(MI.getOperand(4));
11632     else
11633       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11634     Cond.push_back(MI.getOperand(1));
11635 
11636     DebugLoc dl = MI.getDebugLoc();
11637     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11638                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11639   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11640              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11641              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11642              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11643              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11644              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11645              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11646              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11647              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11648              MI.getOpcode() == PPC::SELECT_F4 ||
11649              MI.getOpcode() == PPC::SELECT_F8 ||
11650              MI.getOpcode() == PPC::SELECT_F16 ||
11651              MI.getOpcode() == PPC::SELECT_SPE ||
11652              MI.getOpcode() == PPC::SELECT_SPE4 ||
11653              MI.getOpcode() == PPC::SELECT_VRRC ||
11654              MI.getOpcode() == PPC::SELECT_VSFRC ||
11655              MI.getOpcode() == PPC::SELECT_VSSRC ||
11656              MI.getOpcode() == PPC::SELECT_VSRC) {
11657     // The incoming instruction knows the destination vreg to set, the
11658     // condition code register to branch on, the true/false values to
11659     // select between, and a branch opcode to use.
11660 
11661     //  thisMBB:
11662     //  ...
11663     //   TrueVal = ...
11664     //   cmpTY ccX, r1, r2
11665     //   bCC copy1MBB
11666     //   fallthrough --> copy0MBB
11667     MachineBasicBlock *thisMBB = BB;
11668     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11669     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11670     DebugLoc dl = MI.getDebugLoc();
11671     F->insert(It, copy0MBB);
11672     F->insert(It, sinkMBB);
11673 
11674     // Transfer the remainder of BB and its successor edges to sinkMBB.
11675     sinkMBB->splice(sinkMBB->begin(), BB,
11676                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11677     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11678 
11679     // Next, add the true and fallthrough blocks as its successors.
11680     BB->addSuccessor(copy0MBB);
11681     BB->addSuccessor(sinkMBB);
11682 
11683     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11684         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11685         MI.getOpcode() == PPC::SELECT_F16 ||
11686         MI.getOpcode() == PPC::SELECT_SPE4 ||
11687         MI.getOpcode() == PPC::SELECT_SPE ||
11688         MI.getOpcode() == PPC::SELECT_VRRC ||
11689         MI.getOpcode() == PPC::SELECT_VSFRC ||
11690         MI.getOpcode() == PPC::SELECT_VSSRC ||
11691         MI.getOpcode() == PPC::SELECT_VSRC) {
11692       BuildMI(BB, dl, TII->get(PPC::BC))
11693           .addReg(MI.getOperand(1).getReg())
11694           .addMBB(sinkMBB);
11695     } else {
11696       unsigned SelectPred = MI.getOperand(4).getImm();
11697       BuildMI(BB, dl, TII->get(PPC::BCC))
11698           .addImm(SelectPred)
11699           .addReg(MI.getOperand(1).getReg())
11700           .addMBB(sinkMBB);
11701     }
11702 
11703     //  copy0MBB:
11704     //   %FalseValue = ...
11705     //   # fallthrough to sinkMBB
11706     BB = copy0MBB;
11707 
11708     // Update machine-CFG edges
11709     BB->addSuccessor(sinkMBB);
11710 
11711     //  sinkMBB:
11712     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11713     //  ...
11714     BB = sinkMBB;
11715     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11716         .addReg(MI.getOperand(3).getReg())
11717         .addMBB(copy0MBB)
11718         .addReg(MI.getOperand(2).getReg())
11719         .addMBB(thisMBB);
11720   } else if (MI.getOpcode() == PPC::ReadTB) {
11721     // To read the 64-bit time-base register on a 32-bit target, we read the
11722     // two halves. Should the counter have wrapped while it was being read, we
11723     // need to try again.
11724     // ...
11725     // readLoop:
11726     // mfspr Rx,TBU # load from TBU
11727     // mfspr Ry,TB  # load from TB
11728     // mfspr Rz,TBU # load from TBU
11729     // cmpw crX,Rx,Rz # check if 'old'='new'
11730     // bne readLoop   # branch if they're not equal
11731     // ...
11732 
11733     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11734     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11735     DebugLoc dl = MI.getDebugLoc();
11736     F->insert(It, readMBB);
11737     F->insert(It, sinkMBB);
11738 
11739     // Transfer the remainder of BB and its successor edges to sinkMBB.
11740     sinkMBB->splice(sinkMBB->begin(), BB,
11741                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11742     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11743 
11744     BB->addSuccessor(readMBB);
11745     BB = readMBB;
11746 
11747     MachineRegisterInfo &RegInfo = F->getRegInfo();
11748     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11749     Register LoReg = MI.getOperand(0).getReg();
11750     Register HiReg = MI.getOperand(1).getReg();
11751 
11752     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11753     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11754     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11755 
11756     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11757 
11758     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11759         .addReg(HiReg)
11760         .addReg(ReadAgainReg);
11761     BuildMI(BB, dl, TII->get(PPC::BCC))
11762         .addImm(PPC::PRED_NE)
11763         .addReg(CmpReg)
11764         .addMBB(readMBB);
11765 
11766     BB->addSuccessor(readMBB);
11767     BB->addSuccessor(sinkMBB);
11768   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11769     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11770   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11771     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11772   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11773     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11774   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11775     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11776 
11777   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11778     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11779   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11780     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11781   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11782     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11783   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11784     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11785 
11786   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11787     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11788   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11789     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11790   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11791     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11792   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11793     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11794 
11795   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11796     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11797   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11798     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11799   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11800     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11801   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11802     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11803 
11804   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11805     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11806   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11807     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11808   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11809     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11810   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11811     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11812 
11813   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11814     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11815   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11816     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11817   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11818     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11819   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11820     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11821 
11822   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11823     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11824   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11825     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11826   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11827     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11828   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11829     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11830 
11831   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11832     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11833   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11834     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11835   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11836     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11837   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11838     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11839 
11840   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11841     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11842   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11843     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11844   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11845     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11846   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11847     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11848 
11849   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11850     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11851   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11852     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11853   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11854     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11855   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11856     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11857 
11858   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11859     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11860   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11861     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11862   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11863     BB = EmitAtomicBinary(MI, BB, 4, 0);
11864   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11865     BB = EmitAtomicBinary(MI, BB, 8, 0);
11866   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11867            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11868            (Subtarget.hasPartwordAtomics() &&
11869             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11870            (Subtarget.hasPartwordAtomics() &&
11871             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11872     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11873 
11874     auto LoadMnemonic = PPC::LDARX;
11875     auto StoreMnemonic = PPC::STDCX;
11876     switch (MI.getOpcode()) {
11877     default:
11878       llvm_unreachable("Compare and swap of unknown size");
11879     case PPC::ATOMIC_CMP_SWAP_I8:
11880       LoadMnemonic = PPC::LBARX;
11881       StoreMnemonic = PPC::STBCX;
11882       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11883       break;
11884     case PPC::ATOMIC_CMP_SWAP_I16:
11885       LoadMnemonic = PPC::LHARX;
11886       StoreMnemonic = PPC::STHCX;
11887       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11888       break;
11889     case PPC::ATOMIC_CMP_SWAP_I32:
11890       LoadMnemonic = PPC::LWARX;
11891       StoreMnemonic = PPC::STWCX;
11892       break;
11893     case PPC::ATOMIC_CMP_SWAP_I64:
11894       LoadMnemonic = PPC::LDARX;
11895       StoreMnemonic = PPC::STDCX;
11896       break;
11897     }
11898     Register dest = MI.getOperand(0).getReg();
11899     Register ptrA = MI.getOperand(1).getReg();
11900     Register ptrB = MI.getOperand(2).getReg();
11901     Register oldval = MI.getOperand(3).getReg();
11902     Register newval = MI.getOperand(4).getReg();
11903     DebugLoc dl = MI.getDebugLoc();
11904 
11905     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11906     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11907     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11908     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11909     F->insert(It, loop1MBB);
11910     F->insert(It, loop2MBB);
11911     F->insert(It, midMBB);
11912     F->insert(It, exitMBB);
11913     exitMBB->splice(exitMBB->begin(), BB,
11914                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11915     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11916 
11917     //  thisMBB:
11918     //   ...
11919     //   fallthrough --> loopMBB
11920     BB->addSuccessor(loop1MBB);
11921 
11922     // loop1MBB:
11923     //   l[bhwd]arx dest, ptr
11924     //   cmp[wd] dest, oldval
11925     //   bne- midMBB
11926     // loop2MBB:
11927     //   st[bhwd]cx. newval, ptr
11928     //   bne- loopMBB
11929     //   b exitBB
11930     // midMBB:
11931     //   st[bhwd]cx. dest, ptr
11932     // exitBB:
11933     BB = loop1MBB;
11934     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11935     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11936         .addReg(oldval)
11937         .addReg(dest);
11938     BuildMI(BB, dl, TII->get(PPC::BCC))
11939         .addImm(PPC::PRED_NE)
11940         .addReg(PPC::CR0)
11941         .addMBB(midMBB);
11942     BB->addSuccessor(loop2MBB);
11943     BB->addSuccessor(midMBB);
11944 
11945     BB = loop2MBB;
11946     BuildMI(BB, dl, TII->get(StoreMnemonic))
11947         .addReg(newval)
11948         .addReg(ptrA)
11949         .addReg(ptrB);
11950     BuildMI(BB, dl, TII->get(PPC::BCC))
11951         .addImm(PPC::PRED_NE)
11952         .addReg(PPC::CR0)
11953         .addMBB(loop1MBB);
11954     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11955     BB->addSuccessor(loop1MBB);
11956     BB->addSuccessor(exitMBB);
11957 
11958     BB = midMBB;
11959     BuildMI(BB, dl, TII->get(StoreMnemonic))
11960         .addReg(dest)
11961         .addReg(ptrA)
11962         .addReg(ptrB);
11963     BB->addSuccessor(exitMBB);
11964 
11965     //  exitMBB:
11966     //   ...
11967     BB = exitMBB;
11968   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11969              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11970     // We must use 64-bit registers for addresses when targeting 64-bit,
11971     // since we're actually doing arithmetic on them.  Other registers
11972     // can be 32-bit.
11973     bool is64bit = Subtarget.isPPC64();
11974     bool isLittleEndian = Subtarget.isLittleEndian();
11975     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11976 
11977     Register dest = MI.getOperand(0).getReg();
11978     Register ptrA = MI.getOperand(1).getReg();
11979     Register ptrB = MI.getOperand(2).getReg();
11980     Register oldval = MI.getOperand(3).getReg();
11981     Register newval = MI.getOperand(4).getReg();
11982     DebugLoc dl = MI.getDebugLoc();
11983 
11984     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11985     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11986     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11987     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11988     F->insert(It, loop1MBB);
11989     F->insert(It, loop2MBB);
11990     F->insert(It, midMBB);
11991     F->insert(It, exitMBB);
11992     exitMBB->splice(exitMBB->begin(), BB,
11993                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11994     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11995 
11996     MachineRegisterInfo &RegInfo = F->getRegInfo();
11997     const TargetRegisterClass *RC =
11998         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11999     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12000 
12001     Register PtrReg = RegInfo.createVirtualRegister(RC);
12002     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12003     Register ShiftReg =
12004         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12005     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12006     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12007     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12008     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12009     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12010     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12011     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12012     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12013     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12014     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12015     Register Ptr1Reg;
12016     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12017     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12018     //  thisMBB:
12019     //   ...
12020     //   fallthrough --> loopMBB
12021     BB->addSuccessor(loop1MBB);
12022 
12023     // The 4-byte load must be aligned, while a char or short may be
12024     // anywhere in the word.  Hence all this nasty bookkeeping code.
12025     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12026     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12027     //   xori shift, shift1, 24 [16]
12028     //   rlwinm ptr, ptr1, 0, 0, 29
12029     //   slw newval2, newval, shift
12030     //   slw oldval2, oldval,shift
12031     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12032     //   slw mask, mask2, shift
12033     //   and newval3, newval2, mask
12034     //   and oldval3, oldval2, mask
12035     // loop1MBB:
12036     //   lwarx tmpDest, ptr
12037     //   and tmp, tmpDest, mask
12038     //   cmpw tmp, oldval3
12039     //   bne- midMBB
12040     // loop2MBB:
12041     //   andc tmp2, tmpDest, mask
12042     //   or tmp4, tmp2, newval3
12043     //   stwcx. tmp4, ptr
12044     //   bne- loop1MBB
12045     //   b exitBB
12046     // midMBB:
12047     //   stwcx. tmpDest, ptr
12048     // exitBB:
12049     //   srw dest, tmpDest, shift
12050     if (ptrA != ZeroReg) {
12051       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12052       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12053           .addReg(ptrA)
12054           .addReg(ptrB);
12055     } else {
12056       Ptr1Reg = ptrB;
12057     }
12058 
12059     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12060     // mode.
12061     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12062         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12063         .addImm(3)
12064         .addImm(27)
12065         .addImm(is8bit ? 28 : 27);
12066     if (!isLittleEndian)
12067       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12068           .addReg(Shift1Reg)
12069           .addImm(is8bit ? 24 : 16);
12070     if (is64bit)
12071       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12072           .addReg(Ptr1Reg)
12073           .addImm(0)
12074           .addImm(61);
12075     else
12076       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12077           .addReg(Ptr1Reg)
12078           .addImm(0)
12079           .addImm(0)
12080           .addImm(29);
12081     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12082         .addReg(newval)
12083         .addReg(ShiftReg);
12084     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12085         .addReg(oldval)
12086         .addReg(ShiftReg);
12087     if (is8bit)
12088       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12089     else {
12090       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12091       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12092           .addReg(Mask3Reg)
12093           .addImm(65535);
12094     }
12095     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12096         .addReg(Mask2Reg)
12097         .addReg(ShiftReg);
12098     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12099         .addReg(NewVal2Reg)
12100         .addReg(MaskReg);
12101     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12102         .addReg(OldVal2Reg)
12103         .addReg(MaskReg);
12104 
12105     BB = loop1MBB;
12106     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12107         .addReg(ZeroReg)
12108         .addReg(PtrReg);
12109     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12110         .addReg(TmpDestReg)
12111         .addReg(MaskReg);
12112     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12113         .addReg(TmpReg)
12114         .addReg(OldVal3Reg);
12115     BuildMI(BB, dl, TII->get(PPC::BCC))
12116         .addImm(PPC::PRED_NE)
12117         .addReg(PPC::CR0)
12118         .addMBB(midMBB);
12119     BB->addSuccessor(loop2MBB);
12120     BB->addSuccessor(midMBB);
12121 
12122     BB = loop2MBB;
12123     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12124         .addReg(TmpDestReg)
12125         .addReg(MaskReg);
12126     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12127         .addReg(Tmp2Reg)
12128         .addReg(NewVal3Reg);
12129     BuildMI(BB, dl, TII->get(PPC::STWCX))
12130         .addReg(Tmp4Reg)
12131         .addReg(ZeroReg)
12132         .addReg(PtrReg);
12133     BuildMI(BB, dl, TII->get(PPC::BCC))
12134         .addImm(PPC::PRED_NE)
12135         .addReg(PPC::CR0)
12136         .addMBB(loop1MBB);
12137     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12138     BB->addSuccessor(loop1MBB);
12139     BB->addSuccessor(exitMBB);
12140 
12141     BB = midMBB;
12142     BuildMI(BB, dl, TII->get(PPC::STWCX))
12143         .addReg(TmpDestReg)
12144         .addReg(ZeroReg)
12145         .addReg(PtrReg);
12146     BB->addSuccessor(exitMBB);
12147 
12148     //  exitMBB:
12149     //   ...
12150     BB = exitMBB;
12151     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12152         .addReg(TmpReg)
12153         .addReg(ShiftReg);
12154   } else if (MI.getOpcode() == PPC::FADDrtz) {
12155     // This pseudo performs an FADD with rounding mode temporarily forced
12156     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12157     // is not modeled at the SelectionDAG level.
12158     Register Dest = MI.getOperand(0).getReg();
12159     Register Src1 = MI.getOperand(1).getReg();
12160     Register Src2 = MI.getOperand(2).getReg();
12161     DebugLoc dl = MI.getDebugLoc();
12162 
12163     MachineRegisterInfo &RegInfo = F->getRegInfo();
12164     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12165 
12166     // Save FPSCR value.
12167     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12168 
12169     // Set rounding mode to round-to-zero.
12170     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12171         .addImm(31)
12172         .addReg(PPC::RM, RegState::ImplicitDefine);
12173 
12174     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12175         .addImm(30)
12176         .addReg(PPC::RM, RegState::ImplicitDefine);
12177 
12178     // Perform addition.
12179     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12180 
12181     // Restore FPSCR value.
12182     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12183   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12184              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12185              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12186              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12187     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12188                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12189                           ? PPC::ANDI8_rec
12190                           : PPC::ANDI_rec;
12191     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12192                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12193 
12194     MachineRegisterInfo &RegInfo = F->getRegInfo();
12195     Register Dest = RegInfo.createVirtualRegister(
12196         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12197 
12198     DebugLoc Dl = MI.getDebugLoc();
12199     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12200         .addReg(MI.getOperand(1).getReg())
12201         .addImm(1);
12202     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12203             MI.getOperand(0).getReg())
12204         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12205   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12206     DebugLoc Dl = MI.getDebugLoc();
12207     MachineRegisterInfo &RegInfo = F->getRegInfo();
12208     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12209     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12210     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12211             MI.getOperand(0).getReg())
12212         .addReg(CRReg);
12213   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12214     DebugLoc Dl = MI.getDebugLoc();
12215     unsigned Imm = MI.getOperand(1).getImm();
12216     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12217     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12218             MI.getOperand(0).getReg())
12219         .addReg(PPC::CR0EQ);
12220   } else if (MI.getOpcode() == PPC::SETRNDi) {
12221     DebugLoc dl = MI.getDebugLoc();
12222     Register OldFPSCRReg = MI.getOperand(0).getReg();
12223 
12224     // Save FPSCR value.
12225     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12226 
12227     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12228     // the following settings:
12229     //   00 Round to nearest
12230     //   01 Round to 0
12231     //   10 Round to +inf
12232     //   11 Round to -inf
12233 
12234     // When the operand is immediate, using the two least significant bits of
12235     // the immediate to set the bits 62:63 of FPSCR.
12236     unsigned Mode = MI.getOperand(1).getImm();
12237     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12238         .addImm(31)
12239         .addReg(PPC::RM, RegState::ImplicitDefine);
12240 
12241     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12242         .addImm(30)
12243         .addReg(PPC::RM, RegState::ImplicitDefine);
12244   } else if (MI.getOpcode() == PPC::SETRND) {
12245     DebugLoc dl = MI.getDebugLoc();
12246 
12247     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12248     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12249     // If the target doesn't have DirectMove, we should use stack to do the
12250     // conversion, because the target doesn't have the instructions like mtvsrd
12251     // or mfvsrd to do this conversion directly.
12252     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12253       if (Subtarget.hasDirectMove()) {
12254         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12255           .addReg(SrcReg);
12256       } else {
12257         // Use stack to do the register copy.
12258         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12259         MachineRegisterInfo &RegInfo = F->getRegInfo();
12260         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12261         if (RC == &PPC::F8RCRegClass) {
12262           // Copy register from F8RCRegClass to G8RCRegclass.
12263           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12264                  "Unsupported RegClass.");
12265 
12266           StoreOp = PPC::STFD;
12267           LoadOp = PPC::LD;
12268         } else {
12269           // Copy register from G8RCRegClass to F8RCRegclass.
12270           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12271                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12272                  "Unsupported RegClass.");
12273         }
12274 
12275         MachineFrameInfo &MFI = F->getFrameInfo();
12276         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12277 
12278         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12279             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12280             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12281             MFI.getObjectAlign(FrameIdx));
12282 
12283         // Store the SrcReg into the stack.
12284         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12285           .addReg(SrcReg)
12286           .addImm(0)
12287           .addFrameIndex(FrameIdx)
12288           .addMemOperand(MMOStore);
12289 
12290         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12291             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12292             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12293             MFI.getObjectAlign(FrameIdx));
12294 
12295         // Load from the stack where SrcReg is stored, and save to DestReg,
12296         // so we have done the RegClass conversion from RegClass::SrcReg to
12297         // RegClass::DestReg.
12298         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12299           .addImm(0)
12300           .addFrameIndex(FrameIdx)
12301           .addMemOperand(MMOLoad);
12302       }
12303     };
12304 
12305     Register OldFPSCRReg = MI.getOperand(0).getReg();
12306 
12307     // Save FPSCR value.
12308     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12309 
12310     // When the operand is gprc register, use two least significant bits of the
12311     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12312     //
12313     // copy OldFPSCRTmpReg, OldFPSCRReg
12314     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12315     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12316     // copy NewFPSCRReg, NewFPSCRTmpReg
12317     // mtfsf 255, NewFPSCRReg
12318     MachineOperand SrcOp = MI.getOperand(1);
12319     MachineRegisterInfo &RegInfo = F->getRegInfo();
12320     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12321 
12322     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12323 
12324     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12325     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12326 
12327     // The first operand of INSERT_SUBREG should be a register which has
12328     // subregisters, we only care about its RegClass, so we should use an
12329     // IMPLICIT_DEF register.
12330     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12331     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12332       .addReg(ImDefReg)
12333       .add(SrcOp)
12334       .addImm(1);
12335 
12336     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12337     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12338       .addReg(OldFPSCRTmpReg)
12339       .addReg(ExtSrcReg)
12340       .addImm(0)
12341       .addImm(62);
12342 
12343     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12344     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12345 
12346     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12347     // bits of FPSCR.
12348     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12349       .addImm(255)
12350       .addReg(NewFPSCRReg)
12351       .addImm(0)
12352       .addImm(0);
12353   } else if (MI.getOpcode() == PPC::SETFLM) {
12354     DebugLoc Dl = MI.getDebugLoc();
12355 
12356     // Result of setflm is previous FPSCR content, so we need to save it first.
12357     Register OldFPSCRReg = MI.getOperand(0).getReg();
12358     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12359 
12360     // Put bits in 32:63 to FPSCR.
12361     Register NewFPSCRReg = MI.getOperand(1).getReg();
12362     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12363         .addImm(255)
12364         .addReg(NewFPSCRReg)
12365         .addImm(0)
12366         .addImm(0);
12367   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12368              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12369     return emitProbedAlloca(MI, BB);
12370   } else {
12371     llvm_unreachable("Unexpected instr type to insert");
12372   }
12373 
12374   MI.eraseFromParent(); // The pseudo instruction is gone now.
12375   return BB;
12376 }
12377 
12378 //===----------------------------------------------------------------------===//
12379 // Target Optimization Hooks
12380 //===----------------------------------------------------------------------===//
12381 
12382 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12383   // For the estimates, convergence is quadratic, so we essentially double the
12384   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12385   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12386   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12387   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12388   if (VT.getScalarType() == MVT::f64)
12389     RefinementSteps++;
12390   return RefinementSteps;
12391 }
12392 
12393 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12394                                            int Enabled, int &RefinementSteps,
12395                                            bool &UseOneConstNR,
12396                                            bool Reciprocal) const {
12397   EVT VT = Operand.getValueType();
12398   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12399       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12400       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12401       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12402     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12403       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12404 
12405     // The Newton-Raphson computation with a single constant does not provide
12406     // enough accuracy on some CPUs.
12407     UseOneConstNR = !Subtarget.needsTwoConstNR();
12408     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12409   }
12410   return SDValue();
12411 }
12412 
12413 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12414                                             int Enabled,
12415                                             int &RefinementSteps) const {
12416   EVT VT = Operand.getValueType();
12417   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12418       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12419       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12420       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12421     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12422       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12423     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12424   }
12425   return SDValue();
12426 }
12427 
12428 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12429   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12430   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12431   // enabled for division), this functionality is redundant with the default
12432   // combiner logic (once the division -> reciprocal/multiply transformation
12433   // has taken place). As a result, this matters more for older cores than for
12434   // newer ones.
12435 
12436   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12437   // reciprocal if there are two or more FDIVs (for embedded cores with only
12438   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12439   switch (Subtarget.getCPUDirective()) {
12440   default:
12441     return 3;
12442   case PPC::DIR_440:
12443   case PPC::DIR_A2:
12444   case PPC::DIR_E500:
12445   case PPC::DIR_E500mc:
12446   case PPC::DIR_E5500:
12447     return 2;
12448   }
12449 }
12450 
12451 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12452 // collapsed, and so we need to look through chains of them.
12453 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12454                                      int64_t& Offset, SelectionDAG &DAG) {
12455   if (DAG.isBaseWithConstantOffset(Loc)) {
12456     Base = Loc.getOperand(0);
12457     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12458 
12459     // The base might itself be a base plus an offset, and if so, accumulate
12460     // that as well.
12461     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12462   }
12463 }
12464 
12465 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12466                             unsigned Bytes, int Dist,
12467                             SelectionDAG &DAG) {
12468   if (VT.getSizeInBits() / 8 != Bytes)
12469     return false;
12470 
12471   SDValue BaseLoc = Base->getBasePtr();
12472   if (Loc.getOpcode() == ISD::FrameIndex) {
12473     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12474       return false;
12475     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12476     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12477     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12478     int FS  = MFI.getObjectSize(FI);
12479     int BFS = MFI.getObjectSize(BFI);
12480     if (FS != BFS || FS != (int)Bytes) return false;
12481     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12482   }
12483 
12484   SDValue Base1 = Loc, Base2 = BaseLoc;
12485   int64_t Offset1 = 0, Offset2 = 0;
12486   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12487   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12488   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12489     return true;
12490 
12491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12492   const GlobalValue *GV1 = nullptr;
12493   const GlobalValue *GV2 = nullptr;
12494   Offset1 = 0;
12495   Offset2 = 0;
12496   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12497   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12498   if (isGA1 && isGA2 && GV1 == GV2)
12499     return Offset1 == (Offset2 + Dist*Bytes);
12500   return false;
12501 }
12502 
12503 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12504 // not enforce equality of the chain operands.
12505 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12506                             unsigned Bytes, int Dist,
12507                             SelectionDAG &DAG) {
12508   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12509     EVT VT = LS->getMemoryVT();
12510     SDValue Loc = LS->getBasePtr();
12511     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12512   }
12513 
12514   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12515     EVT VT;
12516     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12517     default: return false;
12518     case Intrinsic::ppc_altivec_lvx:
12519     case Intrinsic::ppc_altivec_lvxl:
12520     case Intrinsic::ppc_vsx_lxvw4x:
12521     case Intrinsic::ppc_vsx_lxvw4x_be:
12522       VT = MVT::v4i32;
12523       break;
12524     case Intrinsic::ppc_vsx_lxvd2x:
12525     case Intrinsic::ppc_vsx_lxvd2x_be:
12526       VT = MVT::v2f64;
12527       break;
12528     case Intrinsic::ppc_altivec_lvebx:
12529       VT = MVT::i8;
12530       break;
12531     case Intrinsic::ppc_altivec_lvehx:
12532       VT = MVT::i16;
12533       break;
12534     case Intrinsic::ppc_altivec_lvewx:
12535       VT = MVT::i32;
12536       break;
12537     }
12538 
12539     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12540   }
12541 
12542   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12543     EVT VT;
12544     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12545     default: return false;
12546     case Intrinsic::ppc_altivec_stvx:
12547     case Intrinsic::ppc_altivec_stvxl:
12548     case Intrinsic::ppc_vsx_stxvw4x:
12549       VT = MVT::v4i32;
12550       break;
12551     case Intrinsic::ppc_vsx_stxvd2x:
12552       VT = MVT::v2f64;
12553       break;
12554     case Intrinsic::ppc_vsx_stxvw4x_be:
12555       VT = MVT::v4i32;
12556       break;
12557     case Intrinsic::ppc_vsx_stxvd2x_be:
12558       VT = MVT::v2f64;
12559       break;
12560     case Intrinsic::ppc_altivec_stvebx:
12561       VT = MVT::i8;
12562       break;
12563     case Intrinsic::ppc_altivec_stvehx:
12564       VT = MVT::i16;
12565       break;
12566     case Intrinsic::ppc_altivec_stvewx:
12567       VT = MVT::i32;
12568       break;
12569     }
12570 
12571     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12572   }
12573 
12574   return false;
12575 }
12576 
12577 // Return true is there is a nearyby consecutive load to the one provided
12578 // (regardless of alignment). We search up and down the chain, looking though
12579 // token factors and other loads (but nothing else). As a result, a true result
12580 // indicates that it is safe to create a new consecutive load adjacent to the
12581 // load provided.
12582 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12583   SDValue Chain = LD->getChain();
12584   EVT VT = LD->getMemoryVT();
12585 
12586   SmallSet<SDNode *, 16> LoadRoots;
12587   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12588   SmallSet<SDNode *, 16> Visited;
12589 
12590   // First, search up the chain, branching to follow all token-factor operands.
12591   // If we find a consecutive load, then we're done, otherwise, record all
12592   // nodes just above the top-level loads and token factors.
12593   while (!Queue.empty()) {
12594     SDNode *ChainNext = Queue.pop_back_val();
12595     if (!Visited.insert(ChainNext).second)
12596       continue;
12597 
12598     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12599       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12600         return true;
12601 
12602       if (!Visited.count(ChainLD->getChain().getNode()))
12603         Queue.push_back(ChainLD->getChain().getNode());
12604     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12605       for (const SDUse &O : ChainNext->ops())
12606         if (!Visited.count(O.getNode()))
12607           Queue.push_back(O.getNode());
12608     } else
12609       LoadRoots.insert(ChainNext);
12610   }
12611 
12612   // Second, search down the chain, starting from the top-level nodes recorded
12613   // in the first phase. These top-level nodes are the nodes just above all
12614   // loads and token factors. Starting with their uses, recursively look though
12615   // all loads (just the chain uses) and token factors to find a consecutive
12616   // load.
12617   Visited.clear();
12618   Queue.clear();
12619 
12620   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12621        IE = LoadRoots.end(); I != IE; ++I) {
12622     Queue.push_back(*I);
12623 
12624     while (!Queue.empty()) {
12625       SDNode *LoadRoot = Queue.pop_back_val();
12626       if (!Visited.insert(LoadRoot).second)
12627         continue;
12628 
12629       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12630         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12631           return true;
12632 
12633       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12634            UE = LoadRoot->use_end(); UI != UE; ++UI)
12635         if (((isa<MemSDNode>(*UI) &&
12636             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12637             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12638           Queue.push_back(*UI);
12639     }
12640   }
12641 
12642   return false;
12643 }
12644 
12645 /// This function is called when we have proved that a SETCC node can be replaced
12646 /// by subtraction (and other supporting instructions) so that the result of
12647 /// comparison is kept in a GPR instead of CR. This function is purely for
12648 /// codegen purposes and has some flags to guide the codegen process.
12649 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12650                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12651   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12652 
12653   // Zero extend the operands to the largest legal integer. Originally, they
12654   // must be of a strictly smaller size.
12655   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12656                          DAG.getConstant(Size, DL, MVT::i32));
12657   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12658                          DAG.getConstant(Size, DL, MVT::i32));
12659 
12660   // Swap if needed. Depends on the condition code.
12661   if (Swap)
12662     std::swap(Op0, Op1);
12663 
12664   // Subtract extended integers.
12665   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12666 
12667   // Move the sign bit to the least significant position and zero out the rest.
12668   // Now the least significant bit carries the result of original comparison.
12669   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12670                              DAG.getConstant(Size - 1, DL, MVT::i32));
12671   auto Final = Shifted;
12672 
12673   // Complement the result if needed. Based on the condition code.
12674   if (Complement)
12675     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12676                         DAG.getConstant(1, DL, MVT::i64));
12677 
12678   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12679 }
12680 
12681 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12682                                                   DAGCombinerInfo &DCI) const {
12683   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12684 
12685   SelectionDAG &DAG = DCI.DAG;
12686   SDLoc DL(N);
12687 
12688   // Size of integers being compared has a critical role in the following
12689   // analysis, so we prefer to do this when all types are legal.
12690   if (!DCI.isAfterLegalizeDAG())
12691     return SDValue();
12692 
12693   // If all users of SETCC extend its value to a legal integer type
12694   // then we replace SETCC with a subtraction
12695   for (SDNode::use_iterator UI = N->use_begin(),
12696        UE = N->use_end(); UI != UE; ++UI) {
12697     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12698       return SDValue();
12699   }
12700 
12701   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12702   auto OpSize = N->getOperand(0).getValueSizeInBits();
12703 
12704   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12705 
12706   if (OpSize < Size) {
12707     switch (CC) {
12708     default: break;
12709     case ISD::SETULT:
12710       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12711     case ISD::SETULE:
12712       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12713     case ISD::SETUGT:
12714       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12715     case ISD::SETUGE:
12716       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12717     }
12718   }
12719 
12720   return SDValue();
12721 }
12722 
12723 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12724                                                   DAGCombinerInfo &DCI) const {
12725   SelectionDAG &DAG = DCI.DAG;
12726   SDLoc dl(N);
12727 
12728   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12729   // If we're tracking CR bits, we need to be careful that we don't have:
12730   //   trunc(binary-ops(zext(x), zext(y)))
12731   // or
12732   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12733   // such that we're unnecessarily moving things into GPRs when it would be
12734   // better to keep them in CR bits.
12735 
12736   // Note that trunc here can be an actual i1 trunc, or can be the effective
12737   // truncation that comes from a setcc or select_cc.
12738   if (N->getOpcode() == ISD::TRUNCATE &&
12739       N->getValueType(0) != MVT::i1)
12740     return SDValue();
12741 
12742   if (N->getOperand(0).getValueType() != MVT::i32 &&
12743       N->getOperand(0).getValueType() != MVT::i64)
12744     return SDValue();
12745 
12746   if (N->getOpcode() == ISD::SETCC ||
12747       N->getOpcode() == ISD::SELECT_CC) {
12748     // If we're looking at a comparison, then we need to make sure that the
12749     // high bits (all except for the first) don't matter the result.
12750     ISD::CondCode CC =
12751       cast<CondCodeSDNode>(N->getOperand(
12752         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12753     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12754 
12755     if (ISD::isSignedIntSetCC(CC)) {
12756       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12757           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12758         return SDValue();
12759     } else if (ISD::isUnsignedIntSetCC(CC)) {
12760       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12761                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12762           !DAG.MaskedValueIsZero(N->getOperand(1),
12763                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12764         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12765                                              : SDValue());
12766     } else {
12767       // This is neither a signed nor an unsigned comparison, just make sure
12768       // that the high bits are equal.
12769       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12770       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12771 
12772       // We don't really care about what is known about the first bit (if
12773       // anything), so clear it in all masks prior to comparing them.
12774       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12775       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12776 
12777       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12778         return SDValue();
12779     }
12780   }
12781 
12782   // We now know that the higher-order bits are irrelevant, we just need to
12783   // make sure that all of the intermediate operations are bit operations, and
12784   // all inputs are extensions.
12785   if (N->getOperand(0).getOpcode() != ISD::AND &&
12786       N->getOperand(0).getOpcode() != ISD::OR  &&
12787       N->getOperand(0).getOpcode() != ISD::XOR &&
12788       N->getOperand(0).getOpcode() != ISD::SELECT &&
12789       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12790       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12791       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12792       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12793       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12794     return SDValue();
12795 
12796   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12797       N->getOperand(1).getOpcode() != ISD::AND &&
12798       N->getOperand(1).getOpcode() != ISD::OR  &&
12799       N->getOperand(1).getOpcode() != ISD::XOR &&
12800       N->getOperand(1).getOpcode() != ISD::SELECT &&
12801       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12802       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12803       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12804       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12805       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12806     return SDValue();
12807 
12808   SmallVector<SDValue, 4> Inputs;
12809   SmallVector<SDValue, 8> BinOps, PromOps;
12810   SmallPtrSet<SDNode *, 16> Visited;
12811 
12812   for (unsigned i = 0; i < 2; ++i) {
12813     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12814           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12815           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12816           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12817         isa<ConstantSDNode>(N->getOperand(i)))
12818       Inputs.push_back(N->getOperand(i));
12819     else
12820       BinOps.push_back(N->getOperand(i));
12821 
12822     if (N->getOpcode() == ISD::TRUNCATE)
12823       break;
12824   }
12825 
12826   // Visit all inputs, collect all binary operations (and, or, xor and
12827   // select) that are all fed by extensions.
12828   while (!BinOps.empty()) {
12829     SDValue BinOp = BinOps.back();
12830     BinOps.pop_back();
12831 
12832     if (!Visited.insert(BinOp.getNode()).second)
12833       continue;
12834 
12835     PromOps.push_back(BinOp);
12836 
12837     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12838       // The condition of the select is not promoted.
12839       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12840         continue;
12841       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12842         continue;
12843 
12844       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12845             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12846             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12847            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12848           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12849         Inputs.push_back(BinOp.getOperand(i));
12850       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12851                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12852                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12853                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12854                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12855                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12856                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12857                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12858                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12859         BinOps.push_back(BinOp.getOperand(i));
12860       } else {
12861         // We have an input that is not an extension or another binary
12862         // operation; we'll abort this transformation.
12863         return SDValue();
12864       }
12865     }
12866   }
12867 
12868   // Make sure that this is a self-contained cluster of operations (which
12869   // is not quite the same thing as saying that everything has only one
12870   // use).
12871   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12872     if (isa<ConstantSDNode>(Inputs[i]))
12873       continue;
12874 
12875     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12876                               UE = Inputs[i].getNode()->use_end();
12877          UI != UE; ++UI) {
12878       SDNode *User = *UI;
12879       if (User != N && !Visited.count(User))
12880         return SDValue();
12881 
12882       // Make sure that we're not going to promote the non-output-value
12883       // operand(s) or SELECT or SELECT_CC.
12884       // FIXME: Although we could sometimes handle this, and it does occur in
12885       // practice that one of the condition inputs to the select is also one of
12886       // the outputs, we currently can't deal with this.
12887       if (User->getOpcode() == ISD::SELECT) {
12888         if (User->getOperand(0) == Inputs[i])
12889           return SDValue();
12890       } else if (User->getOpcode() == ISD::SELECT_CC) {
12891         if (User->getOperand(0) == Inputs[i] ||
12892             User->getOperand(1) == Inputs[i])
12893           return SDValue();
12894       }
12895     }
12896   }
12897 
12898   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12899     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12900                               UE = PromOps[i].getNode()->use_end();
12901          UI != UE; ++UI) {
12902       SDNode *User = *UI;
12903       if (User != N && !Visited.count(User))
12904         return SDValue();
12905 
12906       // Make sure that we're not going to promote the non-output-value
12907       // operand(s) or SELECT or SELECT_CC.
12908       // FIXME: Although we could sometimes handle this, and it does occur in
12909       // practice that one of the condition inputs to the select is also one of
12910       // the outputs, we currently can't deal with this.
12911       if (User->getOpcode() == ISD::SELECT) {
12912         if (User->getOperand(0) == PromOps[i])
12913           return SDValue();
12914       } else if (User->getOpcode() == ISD::SELECT_CC) {
12915         if (User->getOperand(0) == PromOps[i] ||
12916             User->getOperand(1) == PromOps[i])
12917           return SDValue();
12918       }
12919     }
12920   }
12921 
12922   // Replace all inputs with the extension operand.
12923   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12924     // Constants may have users outside the cluster of to-be-promoted nodes,
12925     // and so we need to replace those as we do the promotions.
12926     if (isa<ConstantSDNode>(Inputs[i]))
12927       continue;
12928     else
12929       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12930   }
12931 
12932   std::list<HandleSDNode> PromOpHandles;
12933   for (auto &PromOp : PromOps)
12934     PromOpHandles.emplace_back(PromOp);
12935 
12936   // Replace all operations (these are all the same, but have a different
12937   // (i1) return type). DAG.getNode will validate that the types of
12938   // a binary operator match, so go through the list in reverse so that
12939   // we've likely promoted both operands first. Any intermediate truncations or
12940   // extensions disappear.
12941   while (!PromOpHandles.empty()) {
12942     SDValue PromOp = PromOpHandles.back().getValue();
12943     PromOpHandles.pop_back();
12944 
12945     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12946         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12947         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12948         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12949       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12950           PromOp.getOperand(0).getValueType() != MVT::i1) {
12951         // The operand is not yet ready (see comment below).
12952         PromOpHandles.emplace_front(PromOp);
12953         continue;
12954       }
12955 
12956       SDValue RepValue = PromOp.getOperand(0);
12957       if (isa<ConstantSDNode>(RepValue))
12958         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12959 
12960       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12961       continue;
12962     }
12963 
12964     unsigned C;
12965     switch (PromOp.getOpcode()) {
12966     default:             C = 0; break;
12967     case ISD::SELECT:    C = 1; break;
12968     case ISD::SELECT_CC: C = 2; break;
12969     }
12970 
12971     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12972          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12973         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12974          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12975       // The to-be-promoted operands of this node have not yet been
12976       // promoted (this should be rare because we're going through the
12977       // list backward, but if one of the operands has several users in
12978       // this cluster of to-be-promoted nodes, it is possible).
12979       PromOpHandles.emplace_front(PromOp);
12980       continue;
12981     }
12982 
12983     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12984                                 PromOp.getNode()->op_end());
12985 
12986     // If there are any constant inputs, make sure they're replaced now.
12987     for (unsigned i = 0; i < 2; ++i)
12988       if (isa<ConstantSDNode>(Ops[C+i]))
12989         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12990 
12991     DAG.ReplaceAllUsesOfValueWith(PromOp,
12992       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12993   }
12994 
12995   // Now we're left with the initial truncation itself.
12996   if (N->getOpcode() == ISD::TRUNCATE)
12997     return N->getOperand(0);
12998 
12999   // Otherwise, this is a comparison. The operands to be compared have just
13000   // changed type (to i1), but everything else is the same.
13001   return SDValue(N, 0);
13002 }
13003 
13004 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13005                                                   DAGCombinerInfo &DCI) const {
13006   SelectionDAG &DAG = DCI.DAG;
13007   SDLoc dl(N);
13008 
13009   // If we're tracking CR bits, we need to be careful that we don't have:
13010   //   zext(binary-ops(trunc(x), trunc(y)))
13011   // or
13012   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13013   // such that we're unnecessarily moving things into CR bits that can more
13014   // efficiently stay in GPRs. Note that if we're not certain that the high
13015   // bits are set as required by the final extension, we still may need to do
13016   // some masking to get the proper behavior.
13017 
13018   // This same functionality is important on PPC64 when dealing with
13019   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13020   // the return values of functions. Because it is so similar, it is handled
13021   // here as well.
13022 
13023   if (N->getValueType(0) != MVT::i32 &&
13024       N->getValueType(0) != MVT::i64)
13025     return SDValue();
13026 
13027   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13028         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13029     return SDValue();
13030 
13031   if (N->getOperand(0).getOpcode() != ISD::AND &&
13032       N->getOperand(0).getOpcode() != ISD::OR  &&
13033       N->getOperand(0).getOpcode() != ISD::XOR &&
13034       N->getOperand(0).getOpcode() != ISD::SELECT &&
13035       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13036     return SDValue();
13037 
13038   SmallVector<SDValue, 4> Inputs;
13039   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13040   SmallPtrSet<SDNode *, 16> Visited;
13041 
13042   // Visit all inputs, collect all binary operations (and, or, xor and
13043   // select) that are all fed by truncations.
13044   while (!BinOps.empty()) {
13045     SDValue BinOp = BinOps.back();
13046     BinOps.pop_back();
13047 
13048     if (!Visited.insert(BinOp.getNode()).second)
13049       continue;
13050 
13051     PromOps.push_back(BinOp);
13052 
13053     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13054       // The condition of the select is not promoted.
13055       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13056         continue;
13057       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13058         continue;
13059 
13060       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13061           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13062         Inputs.push_back(BinOp.getOperand(i));
13063       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13064                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13065                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13066                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13067                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13068         BinOps.push_back(BinOp.getOperand(i));
13069       } else {
13070         // We have an input that is not a truncation or another binary
13071         // operation; we'll abort this transformation.
13072         return SDValue();
13073       }
13074     }
13075   }
13076 
13077   // The operands of a select that must be truncated when the select is
13078   // promoted because the operand is actually part of the to-be-promoted set.
13079   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13080 
13081   // Make sure that this is a self-contained cluster of operations (which
13082   // is not quite the same thing as saying that everything has only one
13083   // use).
13084   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13085     if (isa<ConstantSDNode>(Inputs[i]))
13086       continue;
13087 
13088     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
13089                               UE = Inputs[i].getNode()->use_end();
13090          UI != UE; ++UI) {
13091       SDNode *User = *UI;
13092       if (User != N && !Visited.count(User))
13093         return SDValue();
13094 
13095       // If we're going to promote the non-output-value operand(s) or SELECT or
13096       // SELECT_CC, record them for truncation.
13097       if (User->getOpcode() == ISD::SELECT) {
13098         if (User->getOperand(0) == Inputs[i])
13099           SelectTruncOp[0].insert(std::make_pair(User,
13100                                     User->getOperand(0).getValueType()));
13101       } else if (User->getOpcode() == ISD::SELECT_CC) {
13102         if (User->getOperand(0) == Inputs[i])
13103           SelectTruncOp[0].insert(std::make_pair(User,
13104                                     User->getOperand(0).getValueType()));
13105         if (User->getOperand(1) == Inputs[i])
13106           SelectTruncOp[1].insert(std::make_pair(User,
13107                                     User->getOperand(1).getValueType()));
13108       }
13109     }
13110   }
13111 
13112   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13113     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
13114                               UE = PromOps[i].getNode()->use_end();
13115          UI != UE; ++UI) {
13116       SDNode *User = *UI;
13117       if (User != N && !Visited.count(User))
13118         return SDValue();
13119 
13120       // If we're going to promote the non-output-value operand(s) or SELECT or
13121       // SELECT_CC, record them for truncation.
13122       if (User->getOpcode() == ISD::SELECT) {
13123         if (User->getOperand(0) == PromOps[i])
13124           SelectTruncOp[0].insert(std::make_pair(User,
13125                                     User->getOperand(0).getValueType()));
13126       } else if (User->getOpcode() == ISD::SELECT_CC) {
13127         if (User->getOperand(0) == PromOps[i])
13128           SelectTruncOp[0].insert(std::make_pair(User,
13129                                     User->getOperand(0).getValueType()));
13130         if (User->getOperand(1) == PromOps[i])
13131           SelectTruncOp[1].insert(std::make_pair(User,
13132                                     User->getOperand(1).getValueType()));
13133       }
13134     }
13135   }
13136 
13137   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13138   bool ReallyNeedsExt = false;
13139   if (N->getOpcode() != ISD::ANY_EXTEND) {
13140     // If all of the inputs are not already sign/zero extended, then
13141     // we'll still need to do that at the end.
13142     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13143       if (isa<ConstantSDNode>(Inputs[i]))
13144         continue;
13145 
13146       unsigned OpBits =
13147         Inputs[i].getOperand(0).getValueSizeInBits();
13148       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13149 
13150       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13151            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13152                                   APInt::getHighBitsSet(OpBits,
13153                                                         OpBits-PromBits))) ||
13154           (N->getOpcode() == ISD::SIGN_EXTEND &&
13155            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13156              (OpBits-(PromBits-1)))) {
13157         ReallyNeedsExt = true;
13158         break;
13159       }
13160     }
13161   }
13162 
13163   // Replace all inputs, either with the truncation operand, or a
13164   // truncation or extension to the final output type.
13165   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13166     // Constant inputs need to be replaced with the to-be-promoted nodes that
13167     // use them because they might have users outside of the cluster of
13168     // promoted nodes.
13169     if (isa<ConstantSDNode>(Inputs[i]))
13170       continue;
13171 
13172     SDValue InSrc = Inputs[i].getOperand(0);
13173     if (Inputs[i].getValueType() == N->getValueType(0))
13174       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13175     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13176       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13177         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13178     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13179       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13180         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13181     else
13182       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13183         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13184   }
13185 
13186   std::list<HandleSDNode> PromOpHandles;
13187   for (auto &PromOp : PromOps)
13188     PromOpHandles.emplace_back(PromOp);
13189 
13190   // Replace all operations (these are all the same, but have a different
13191   // (promoted) return type). DAG.getNode will validate that the types of
13192   // a binary operator match, so go through the list in reverse so that
13193   // we've likely promoted both operands first.
13194   while (!PromOpHandles.empty()) {
13195     SDValue PromOp = PromOpHandles.back().getValue();
13196     PromOpHandles.pop_back();
13197 
13198     unsigned C;
13199     switch (PromOp.getOpcode()) {
13200     default:             C = 0; break;
13201     case ISD::SELECT:    C = 1; break;
13202     case ISD::SELECT_CC: C = 2; break;
13203     }
13204 
13205     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13206          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13207         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13208          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13209       // The to-be-promoted operands of this node have not yet been
13210       // promoted (this should be rare because we're going through the
13211       // list backward, but if one of the operands has several users in
13212       // this cluster of to-be-promoted nodes, it is possible).
13213       PromOpHandles.emplace_front(PromOp);
13214       continue;
13215     }
13216 
13217     // For SELECT and SELECT_CC nodes, we do a similar check for any
13218     // to-be-promoted comparison inputs.
13219     if (PromOp.getOpcode() == ISD::SELECT ||
13220         PromOp.getOpcode() == ISD::SELECT_CC) {
13221       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13222            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13223           (SelectTruncOp[1].count(PromOp.getNode()) &&
13224            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13225         PromOpHandles.emplace_front(PromOp);
13226         continue;
13227       }
13228     }
13229 
13230     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13231                                 PromOp.getNode()->op_end());
13232 
13233     // If this node has constant inputs, then they'll need to be promoted here.
13234     for (unsigned i = 0; i < 2; ++i) {
13235       if (!isa<ConstantSDNode>(Ops[C+i]))
13236         continue;
13237       if (Ops[C+i].getValueType() == N->getValueType(0))
13238         continue;
13239 
13240       if (N->getOpcode() == ISD::SIGN_EXTEND)
13241         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13242       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13243         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13244       else
13245         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13246     }
13247 
13248     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13249     // truncate them again to the original value type.
13250     if (PromOp.getOpcode() == ISD::SELECT ||
13251         PromOp.getOpcode() == ISD::SELECT_CC) {
13252       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13253       if (SI0 != SelectTruncOp[0].end())
13254         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13255       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13256       if (SI1 != SelectTruncOp[1].end())
13257         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13258     }
13259 
13260     DAG.ReplaceAllUsesOfValueWith(PromOp,
13261       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13262   }
13263 
13264   // Now we're left with the initial extension itself.
13265   if (!ReallyNeedsExt)
13266     return N->getOperand(0);
13267 
13268   // To zero extend, just mask off everything except for the first bit (in the
13269   // i1 case).
13270   if (N->getOpcode() == ISD::ZERO_EXTEND)
13271     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13272                        DAG.getConstant(APInt::getLowBitsSet(
13273                                          N->getValueSizeInBits(0), PromBits),
13274                                        dl, N->getValueType(0)));
13275 
13276   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13277          "Invalid extension type");
13278   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13279   SDValue ShiftCst =
13280       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13281   return DAG.getNode(
13282       ISD::SRA, dl, N->getValueType(0),
13283       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13284       ShiftCst);
13285 }
13286 
13287 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13288                                         DAGCombinerInfo &DCI) const {
13289   assert(N->getOpcode() == ISD::SETCC &&
13290          "Should be called with a SETCC node");
13291 
13292   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13293   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13294     SDValue LHS = N->getOperand(0);
13295     SDValue RHS = N->getOperand(1);
13296 
13297     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13298     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13299         LHS.hasOneUse())
13300       std::swap(LHS, RHS);
13301 
13302     // x == 0-y --> x+y == 0
13303     // x != 0-y --> x+y != 0
13304     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13305         RHS.hasOneUse()) {
13306       SDLoc DL(N);
13307       SelectionDAG &DAG = DCI.DAG;
13308       EVT VT = N->getValueType(0);
13309       EVT OpVT = LHS.getValueType();
13310       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13311       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13312     }
13313   }
13314 
13315   return DAGCombineTruncBoolExt(N, DCI);
13316 }
13317 
13318 // Is this an extending load from an f32 to an f64?
13319 static bool isFPExtLoad(SDValue Op) {
13320   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13321     return LD->getExtensionType() == ISD::EXTLOAD &&
13322       Op.getValueType() == MVT::f64;
13323   return false;
13324 }
13325 
13326 /// Reduces the number of fp-to-int conversion when building a vector.
13327 ///
13328 /// If this vector is built out of floating to integer conversions,
13329 /// transform it to a vector built out of floating point values followed by a
13330 /// single floating to integer conversion of the vector.
13331 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13332 /// becomes (fptosi (build_vector ($A, $B, ...)))
13333 SDValue PPCTargetLowering::
13334 combineElementTruncationToVectorTruncation(SDNode *N,
13335                                            DAGCombinerInfo &DCI) const {
13336   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13337          "Should be called with a BUILD_VECTOR node");
13338 
13339   SelectionDAG &DAG = DCI.DAG;
13340   SDLoc dl(N);
13341 
13342   SDValue FirstInput = N->getOperand(0);
13343   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13344          "The input operand must be an fp-to-int conversion.");
13345 
13346   // This combine happens after legalization so the fp_to_[su]i nodes are
13347   // already converted to PPCSISD nodes.
13348   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13349   if (FirstConversion == PPCISD::FCTIDZ ||
13350       FirstConversion == PPCISD::FCTIDUZ ||
13351       FirstConversion == PPCISD::FCTIWZ ||
13352       FirstConversion == PPCISD::FCTIWUZ) {
13353     bool IsSplat = true;
13354     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13355       FirstConversion == PPCISD::FCTIWUZ;
13356     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13357     SmallVector<SDValue, 4> Ops;
13358     EVT TargetVT = N->getValueType(0);
13359     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13360       SDValue NextOp = N->getOperand(i);
13361       if (NextOp.getOpcode() != PPCISD::MFVSR)
13362         return SDValue();
13363       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13364       if (NextConversion != FirstConversion)
13365         return SDValue();
13366       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13367       // This is not valid if the input was originally double precision. It is
13368       // also not profitable to do unless this is an extending load in which
13369       // case doing this combine will allow us to combine consecutive loads.
13370       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13371         return SDValue();
13372       if (N->getOperand(i) != FirstInput)
13373         IsSplat = false;
13374     }
13375 
13376     // If this is a splat, we leave it as-is since there will be only a single
13377     // fp-to-int conversion followed by a splat of the integer. This is better
13378     // for 32-bit and smaller ints and neutral for 64-bit ints.
13379     if (IsSplat)
13380       return SDValue();
13381 
13382     // Now that we know we have the right type of node, get its operands
13383     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13384       SDValue In = N->getOperand(i).getOperand(0);
13385       if (Is32Bit) {
13386         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13387         // here, we know that all inputs are extending loads so this is safe).
13388         if (In.isUndef())
13389           Ops.push_back(DAG.getUNDEF(SrcVT));
13390         else {
13391           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13392                                       MVT::f32, In.getOperand(0),
13393                                       DAG.getIntPtrConstant(1, dl));
13394           Ops.push_back(Trunc);
13395         }
13396       } else
13397         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13398     }
13399 
13400     unsigned Opcode;
13401     if (FirstConversion == PPCISD::FCTIDZ ||
13402         FirstConversion == PPCISD::FCTIWZ)
13403       Opcode = ISD::FP_TO_SINT;
13404     else
13405       Opcode = ISD::FP_TO_UINT;
13406 
13407     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13408     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13409     return DAG.getNode(Opcode, dl, TargetVT, BV);
13410   }
13411   return SDValue();
13412 }
13413 
13414 /// Reduce the number of loads when building a vector.
13415 ///
13416 /// Building a vector out of multiple loads can be converted to a load
13417 /// of the vector type if the loads are consecutive. If the loads are
13418 /// consecutive but in descending order, a shuffle is added at the end
13419 /// to reorder the vector.
13420 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13421   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13422          "Should be called with a BUILD_VECTOR node");
13423 
13424   SDLoc dl(N);
13425 
13426   // Return early for non byte-sized type, as they can't be consecutive.
13427   if (!N->getValueType(0).getVectorElementType().isByteSized())
13428     return SDValue();
13429 
13430   bool InputsAreConsecutiveLoads = true;
13431   bool InputsAreReverseConsecutive = true;
13432   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13433   SDValue FirstInput = N->getOperand(0);
13434   bool IsRoundOfExtLoad = false;
13435 
13436   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13437       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13438     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13439     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13440   }
13441   // Not a build vector of (possibly fp_rounded) loads.
13442   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13443       N->getNumOperands() == 1)
13444     return SDValue();
13445 
13446   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13447     // If any inputs are fp_round(extload), they all must be.
13448     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13449       return SDValue();
13450 
13451     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13452       N->getOperand(i);
13453     if (NextInput.getOpcode() != ISD::LOAD)
13454       return SDValue();
13455 
13456     SDValue PreviousInput =
13457       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13458     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13459     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13460 
13461     // If any inputs are fp_round(extload), they all must be.
13462     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13463       return SDValue();
13464 
13465     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13466       InputsAreConsecutiveLoads = false;
13467     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13468       InputsAreReverseConsecutive = false;
13469 
13470     // Exit early if the loads are neither consecutive nor reverse consecutive.
13471     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13472       return SDValue();
13473   }
13474 
13475   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13476          "The loads cannot be both consecutive and reverse consecutive.");
13477 
13478   SDValue FirstLoadOp =
13479     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13480   SDValue LastLoadOp =
13481     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13482                        N->getOperand(N->getNumOperands()-1);
13483 
13484   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13485   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13486   if (InputsAreConsecutiveLoads) {
13487     assert(LD1 && "Input needs to be a LoadSDNode.");
13488     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13489                        LD1->getBasePtr(), LD1->getPointerInfo(),
13490                        LD1->getAlignment());
13491   }
13492   if (InputsAreReverseConsecutive) {
13493     assert(LDL && "Input needs to be a LoadSDNode.");
13494     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13495                                LDL->getBasePtr(), LDL->getPointerInfo(),
13496                                LDL->getAlignment());
13497     SmallVector<int, 16> Ops;
13498     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13499       Ops.push_back(i);
13500 
13501     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13502                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13503   }
13504   return SDValue();
13505 }
13506 
13507 // This function adds the required vector_shuffle needed to get
13508 // the elements of the vector extract in the correct position
13509 // as specified by the CorrectElems encoding.
13510 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13511                                       SDValue Input, uint64_t Elems,
13512                                       uint64_t CorrectElems) {
13513   SDLoc dl(N);
13514 
13515   unsigned NumElems = Input.getValueType().getVectorNumElements();
13516   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13517 
13518   // Knowing the element indices being extracted from the original
13519   // vector and the order in which they're being inserted, just put
13520   // them at element indices required for the instruction.
13521   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13522     if (DAG.getDataLayout().isLittleEndian())
13523       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13524     else
13525       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13526     CorrectElems = CorrectElems >> 8;
13527     Elems = Elems >> 8;
13528   }
13529 
13530   SDValue Shuffle =
13531       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13532                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13533 
13534   EVT VT = N->getValueType(0);
13535   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13536 
13537   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13538                                Input.getValueType().getVectorElementType(),
13539                                VT.getVectorNumElements());
13540   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13541                      DAG.getValueType(ExtVT));
13542 }
13543 
13544 // Look for build vector patterns where input operands come from sign
13545 // extended vector_extract elements of specific indices. If the correct indices
13546 // aren't used, add a vector shuffle to fix up the indices and create
13547 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13548 // during instruction selection.
13549 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13550   // This array encodes the indices that the vector sign extend instructions
13551   // extract from when extending from one type to another for both BE and LE.
13552   // The right nibble of each byte corresponds to the LE incides.
13553   // and the left nibble of each byte corresponds to the BE incides.
13554   // For example: 0x3074B8FC  byte->word
13555   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13556   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13557   // For example: 0x000070F8  byte->double word
13558   // For LE: the allowed indices are: 0x0,0x8
13559   // For BE: the allowed indices are: 0x7,0xF
13560   uint64_t TargetElems[] = {
13561       0x3074B8FC, // b->w
13562       0x000070F8, // b->d
13563       0x10325476, // h->w
13564       0x00003074, // h->d
13565       0x00001032, // w->d
13566   };
13567 
13568   uint64_t Elems = 0;
13569   int Index;
13570   SDValue Input;
13571 
13572   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13573     if (!Op)
13574       return false;
13575     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13576         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13577       return false;
13578 
13579     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13580     // of the right width.
13581     SDValue Extract = Op.getOperand(0);
13582     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13583       Extract = Extract.getOperand(0);
13584     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13585       return false;
13586 
13587     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13588     if (!ExtOp)
13589       return false;
13590 
13591     Index = ExtOp->getZExtValue();
13592     if (Input && Input != Extract.getOperand(0))
13593       return false;
13594 
13595     if (!Input)
13596       Input = Extract.getOperand(0);
13597 
13598     Elems = Elems << 8;
13599     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13600     Elems |= Index;
13601 
13602     return true;
13603   };
13604 
13605   // If the build vector operands aren't sign extended vector extracts,
13606   // of the same input vector, then return.
13607   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13608     if (!isSExtOfVecExtract(N->getOperand(i))) {
13609       return SDValue();
13610     }
13611   }
13612 
13613   // If the vector extract indicies are not correct, add the appropriate
13614   // vector_shuffle.
13615   int TgtElemArrayIdx;
13616   int InputSize = Input.getValueType().getScalarSizeInBits();
13617   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13618   if (InputSize + OutputSize == 40)
13619     TgtElemArrayIdx = 0;
13620   else if (InputSize + OutputSize == 72)
13621     TgtElemArrayIdx = 1;
13622   else if (InputSize + OutputSize == 48)
13623     TgtElemArrayIdx = 2;
13624   else if (InputSize + OutputSize == 80)
13625     TgtElemArrayIdx = 3;
13626   else if (InputSize + OutputSize == 96)
13627     TgtElemArrayIdx = 4;
13628   else
13629     return SDValue();
13630 
13631   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13632   CorrectElems = DAG.getDataLayout().isLittleEndian()
13633                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13634                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13635   if (Elems != CorrectElems) {
13636     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13637   }
13638 
13639   // Regular lowering will catch cases where a shuffle is not needed.
13640   return SDValue();
13641 }
13642 
13643 // Look for the pattern of a load from a narrow width to i128, feeding
13644 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
13645 // (LXVRZX). This node represents a zero extending load that will be matched
13646 // to the Load VSX Vector Rightmost instructions.
13647 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
13648   SDLoc DL(N);
13649 
13650   // This combine is only eligible for a BUILD_VECTOR of v1i128.
13651   if (N->getValueType(0) != MVT::v1i128)
13652     return SDValue();
13653 
13654   SDValue Operand = N->getOperand(0);
13655   // Proceed with the transformation if the operand to the BUILD_VECTOR
13656   // is a load instruction.
13657   if (Operand.getOpcode() != ISD::LOAD)
13658     return SDValue();
13659 
13660   LoadSDNode *LD = dyn_cast<LoadSDNode>(Operand);
13661   EVT MemoryType = LD->getMemoryVT();
13662 
13663   // This transformation is only valid if the we are loading either a byte,
13664   // halfword, word, or doubleword.
13665   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
13666                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
13667 
13668   // Ensure that the load from the narrow width is being zero extended to i128.
13669   if (!ValidLDType ||
13670       (LD->getExtensionType() != ISD::ZEXTLOAD &&
13671        LD->getExtensionType() != ISD::EXTLOAD))
13672     return SDValue();
13673 
13674   SDValue LoadOps[] = {
13675       LD->getChain(), LD->getBasePtr(),
13676       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
13677 
13678   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
13679                                  DAG.getVTList(MVT::v1i128, MVT::Other),
13680                                  LoadOps, MemoryType, LD->getMemOperand());
13681 }
13682 
13683 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13684                                                  DAGCombinerInfo &DCI) const {
13685   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13686          "Should be called with a BUILD_VECTOR node");
13687 
13688   SelectionDAG &DAG = DCI.DAG;
13689   SDLoc dl(N);
13690 
13691   if (!Subtarget.hasVSX())
13692     return SDValue();
13693 
13694   // The target independent DAG combiner will leave a build_vector of
13695   // float-to-int conversions intact. We can generate MUCH better code for
13696   // a float-to-int conversion of a vector of floats.
13697   SDValue FirstInput = N->getOperand(0);
13698   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13699     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13700     if (Reduced)
13701       return Reduced;
13702   }
13703 
13704   // If we're building a vector out of consecutive loads, just load that
13705   // vector type.
13706   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13707   if (Reduced)
13708     return Reduced;
13709 
13710   // If we're building a vector out of extended elements from another vector
13711   // we have P9 vector integer extend instructions. The code assumes legal
13712   // input types (i.e. it can't handle things like v4i16) so do not run before
13713   // legalization.
13714   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13715     Reduced = combineBVOfVecSExt(N, DAG);
13716     if (Reduced)
13717       return Reduced;
13718   }
13719 
13720   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
13721   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
13722   // is a load from <valid narrow width> to i128.
13723   if (Subtarget.isISA3_1()) {
13724     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
13725     if (BVOfZLoad)
13726       return BVOfZLoad;
13727   }
13728 
13729   if (N->getValueType(0) != MVT::v2f64)
13730     return SDValue();
13731 
13732   // Looking for:
13733   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13734   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13735       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13736     return SDValue();
13737   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13738       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13739     return SDValue();
13740   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13741     return SDValue();
13742 
13743   SDValue Ext1 = FirstInput.getOperand(0);
13744   SDValue Ext2 = N->getOperand(1).getOperand(0);
13745   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13746      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13747     return SDValue();
13748 
13749   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13750   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13751   if (!Ext1Op || !Ext2Op)
13752     return SDValue();
13753   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13754       Ext1.getOperand(0) != Ext2.getOperand(0))
13755     return SDValue();
13756 
13757   int FirstElem = Ext1Op->getZExtValue();
13758   int SecondElem = Ext2Op->getZExtValue();
13759   int SubvecIdx;
13760   if (FirstElem == 0 && SecondElem == 1)
13761     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13762   else if (FirstElem == 2 && SecondElem == 3)
13763     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13764   else
13765     return SDValue();
13766 
13767   SDValue SrcVec = Ext1.getOperand(0);
13768   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13769     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13770   return DAG.getNode(NodeType, dl, MVT::v2f64,
13771                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13772 }
13773 
13774 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13775                                               DAGCombinerInfo &DCI) const {
13776   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13777           N->getOpcode() == ISD::UINT_TO_FP) &&
13778          "Need an int -> FP conversion node here");
13779 
13780   if (useSoftFloat() || !Subtarget.has64BitSupport())
13781     return SDValue();
13782 
13783   SelectionDAG &DAG = DCI.DAG;
13784   SDLoc dl(N);
13785   SDValue Op(N, 0);
13786 
13787   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13788   // from the hardware.
13789   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13790     return SDValue();
13791   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13792       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13793     return SDValue();
13794 
13795   SDValue FirstOperand(Op.getOperand(0));
13796   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13797     (FirstOperand.getValueType() == MVT::i8 ||
13798      FirstOperand.getValueType() == MVT::i16);
13799   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13800     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13801     bool DstDouble = Op.getValueType() == MVT::f64;
13802     unsigned ConvOp = Signed ?
13803       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13804       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13805     SDValue WidthConst =
13806       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13807                             dl, false);
13808     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13809     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13810     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13811                                          DAG.getVTList(MVT::f64, MVT::Other),
13812                                          Ops, MVT::i8, LDN->getMemOperand());
13813 
13814     // For signed conversion, we need to sign-extend the value in the VSR
13815     if (Signed) {
13816       SDValue ExtOps[] = { Ld, WidthConst };
13817       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13818       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13819     } else
13820       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13821   }
13822 
13823 
13824   // For i32 intermediate values, unfortunately, the conversion functions
13825   // leave the upper 32 bits of the value are undefined. Within the set of
13826   // scalar instructions, we have no method for zero- or sign-extending the
13827   // value. Thus, we cannot handle i32 intermediate values here.
13828   if (Op.getOperand(0).getValueType() == MVT::i32)
13829     return SDValue();
13830 
13831   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13832          "UINT_TO_FP is supported only with FPCVT");
13833 
13834   // If we have FCFIDS, then use it when converting to single-precision.
13835   // Otherwise, convert to double-precision and then round.
13836   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13837                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13838                                                             : PPCISD::FCFIDS)
13839                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13840                                                             : PPCISD::FCFID);
13841   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13842                   ? MVT::f32
13843                   : MVT::f64;
13844 
13845   // If we're converting from a float, to an int, and back to a float again,
13846   // then we don't need the store/load pair at all.
13847   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13848        Subtarget.hasFPCVT()) ||
13849       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13850     SDValue Src = Op.getOperand(0).getOperand(0);
13851     if (Src.getValueType() == MVT::f32) {
13852       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13853       DCI.AddToWorklist(Src.getNode());
13854     } else if (Src.getValueType() != MVT::f64) {
13855       // Make sure that we don't pick up a ppc_fp128 source value.
13856       return SDValue();
13857     }
13858 
13859     unsigned FCTOp =
13860       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13861                                                         PPCISD::FCTIDUZ;
13862 
13863     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13864     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13865 
13866     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13867       FP = DAG.getNode(ISD::FP_ROUND, dl,
13868                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13869       DCI.AddToWorklist(FP.getNode());
13870     }
13871 
13872     return FP;
13873   }
13874 
13875   return SDValue();
13876 }
13877 
13878 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13879 // builtins) into loads with swaps.
13880 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13881                                               DAGCombinerInfo &DCI) const {
13882   SelectionDAG &DAG = DCI.DAG;
13883   SDLoc dl(N);
13884   SDValue Chain;
13885   SDValue Base;
13886   MachineMemOperand *MMO;
13887 
13888   switch (N->getOpcode()) {
13889   default:
13890     llvm_unreachable("Unexpected opcode for little endian VSX load");
13891   case ISD::LOAD: {
13892     LoadSDNode *LD = cast<LoadSDNode>(N);
13893     Chain = LD->getChain();
13894     Base = LD->getBasePtr();
13895     MMO = LD->getMemOperand();
13896     // If the MMO suggests this isn't a load of a full vector, leave
13897     // things alone.  For a built-in, we have to make the change for
13898     // correctness, so if there is a size problem that will be a bug.
13899     if (MMO->getSize() < 16)
13900       return SDValue();
13901     break;
13902   }
13903   case ISD::INTRINSIC_W_CHAIN: {
13904     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13905     Chain = Intrin->getChain();
13906     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13907     // us what we want. Get operand 2 instead.
13908     Base = Intrin->getOperand(2);
13909     MMO = Intrin->getMemOperand();
13910     break;
13911   }
13912   }
13913 
13914   MVT VecTy = N->getValueType(0).getSimpleVT();
13915 
13916   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13917   // aligned and the type is a vector with elements up to 4 bytes
13918   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13919       VecTy.getScalarSizeInBits() <= 32) {
13920     return SDValue();
13921   }
13922 
13923   SDValue LoadOps[] = { Chain, Base };
13924   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13925                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13926                                          LoadOps, MVT::v2f64, MMO);
13927 
13928   DCI.AddToWorklist(Load.getNode());
13929   Chain = Load.getValue(1);
13930   SDValue Swap = DAG.getNode(
13931       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13932   DCI.AddToWorklist(Swap.getNode());
13933 
13934   // Add a bitcast if the resulting load type doesn't match v2f64.
13935   if (VecTy != MVT::v2f64) {
13936     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13937     DCI.AddToWorklist(N.getNode());
13938     // Package {bitcast value, swap's chain} to match Load's shape.
13939     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13940                        N, Swap.getValue(1));
13941   }
13942 
13943   return Swap;
13944 }
13945 
13946 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13947 // builtins) into stores with swaps.
13948 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13949                                                DAGCombinerInfo &DCI) const {
13950   SelectionDAG &DAG = DCI.DAG;
13951   SDLoc dl(N);
13952   SDValue Chain;
13953   SDValue Base;
13954   unsigned SrcOpnd;
13955   MachineMemOperand *MMO;
13956 
13957   switch (N->getOpcode()) {
13958   default:
13959     llvm_unreachable("Unexpected opcode for little endian VSX store");
13960   case ISD::STORE: {
13961     StoreSDNode *ST = cast<StoreSDNode>(N);
13962     Chain = ST->getChain();
13963     Base = ST->getBasePtr();
13964     MMO = ST->getMemOperand();
13965     SrcOpnd = 1;
13966     // If the MMO suggests this isn't a store of a full vector, leave
13967     // things alone.  For a built-in, we have to make the change for
13968     // correctness, so if there is a size problem that will be a bug.
13969     if (MMO->getSize() < 16)
13970       return SDValue();
13971     break;
13972   }
13973   case ISD::INTRINSIC_VOID: {
13974     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13975     Chain = Intrin->getChain();
13976     // Intrin->getBasePtr() oddly does not get what we want.
13977     Base = Intrin->getOperand(3);
13978     MMO = Intrin->getMemOperand();
13979     SrcOpnd = 2;
13980     break;
13981   }
13982   }
13983 
13984   SDValue Src = N->getOperand(SrcOpnd);
13985   MVT VecTy = Src.getValueType().getSimpleVT();
13986 
13987   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13988   // aligned and the type is a vector with elements up to 4 bytes
13989   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13990       VecTy.getScalarSizeInBits() <= 32) {
13991     return SDValue();
13992   }
13993 
13994   // All stores are done as v2f64 and possible bit cast.
13995   if (VecTy != MVT::v2f64) {
13996     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13997     DCI.AddToWorklist(Src.getNode());
13998   }
13999 
14000   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14001                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14002   DCI.AddToWorklist(Swap.getNode());
14003   Chain = Swap.getValue(1);
14004   SDValue StoreOps[] = { Chain, Swap, Base };
14005   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14006                                           DAG.getVTList(MVT::Other),
14007                                           StoreOps, VecTy, MMO);
14008   DCI.AddToWorklist(Store.getNode());
14009   return Store;
14010 }
14011 
14012 // Handle DAG combine for STORE (FP_TO_INT F).
14013 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14014                                                DAGCombinerInfo &DCI) const {
14015 
14016   SelectionDAG &DAG = DCI.DAG;
14017   SDLoc dl(N);
14018   unsigned Opcode = N->getOperand(1).getOpcode();
14019 
14020   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14021          && "Not a FP_TO_INT Instruction!");
14022 
14023   SDValue Val = N->getOperand(1).getOperand(0);
14024   EVT Op1VT = N->getOperand(1).getValueType();
14025   EVT ResVT = Val.getValueType();
14026 
14027   // Floating point types smaller than 32 bits are not legal on Power.
14028   if (ResVT.getScalarSizeInBits() < 32)
14029     return SDValue();
14030 
14031   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14032   bool ValidTypeForStoreFltAsInt =
14033         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14034          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14035 
14036   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14037       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14038     return SDValue();
14039 
14040   // Extend f32 values to f64
14041   if (ResVT.getScalarSizeInBits() == 32) {
14042     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14043     DCI.AddToWorklist(Val.getNode());
14044   }
14045 
14046   // Set signed or unsigned conversion opcode.
14047   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14048                           PPCISD::FP_TO_SINT_IN_VSR :
14049                           PPCISD::FP_TO_UINT_IN_VSR;
14050 
14051   Val = DAG.getNode(ConvOpcode,
14052                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14053   DCI.AddToWorklist(Val.getNode());
14054 
14055   // Set number of bytes being converted.
14056   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14057   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14058                     DAG.getIntPtrConstant(ByteSize, dl, false),
14059                     DAG.getValueType(Op1VT) };
14060 
14061   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14062           DAG.getVTList(MVT::Other), Ops,
14063           cast<StoreSDNode>(N)->getMemoryVT(),
14064           cast<StoreSDNode>(N)->getMemOperand());
14065 
14066   DCI.AddToWorklist(Val.getNode());
14067   return Val;
14068 }
14069 
14070 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14071   // Check that the source of the element keeps flipping
14072   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14073   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14074   for (int i = 1, e = Mask.size(); i < e; i++) {
14075     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14076       return false;
14077     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14078       return false;
14079     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14080   }
14081   return true;
14082 }
14083 
14084 static bool isSplatBV(SDValue Op) {
14085   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14086     return false;
14087   SDValue FirstOp;
14088 
14089   // Find first non-undef input.
14090   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14091     FirstOp = Op.getOperand(i);
14092     if (!FirstOp.isUndef())
14093       break;
14094   }
14095 
14096   // All inputs are undef or the same as the first non-undef input.
14097   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14098     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14099       return false;
14100   return true;
14101 }
14102 
14103 static SDValue isScalarToVec(SDValue Op) {
14104   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14105     return Op;
14106   if (Op.getOpcode() != ISD::BITCAST)
14107     return SDValue();
14108   Op = Op.getOperand(0);
14109   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14110     return Op;
14111   return SDValue();
14112 }
14113 
14114 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14115                                             int LHSMaxIdx, int RHSMinIdx,
14116                                             int RHSMaxIdx, int HalfVec) {
14117   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14118     int Idx = ShuffV[i];
14119     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14120       ShuffV[i] += HalfVec;
14121   }
14122   return;
14123 }
14124 
14125 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14126 // the original is:
14127 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14128 // In such a case, just change the shuffle mask to extract the element
14129 // from the permuted index.
14130 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
14131   SDLoc dl(OrigSToV);
14132   EVT VT = OrigSToV.getValueType();
14133   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14134          "Expecting a SCALAR_TO_VECTOR here");
14135   SDValue Input = OrigSToV.getOperand(0);
14136 
14137   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14138     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14139     SDValue OrigVector = Input.getOperand(0);
14140 
14141     // Can't handle non-const element indices or different vector types
14142     // for the input to the extract and the output of the scalar_to_vector.
14143     if (Idx && VT == OrigVector.getValueType()) {
14144       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
14145       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
14146       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14147     }
14148   }
14149   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14150                      OrigSToV.getOperand(0));
14151 }
14152 
14153 // On little endian subtargets, combine shuffles such as:
14154 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14155 // into:
14156 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14157 // because the latter can be matched to a single instruction merge.
14158 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14159 // to put the value into element zero. Adjust the shuffle mask so that the
14160 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14161 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14162                                                 SelectionDAG &DAG) const {
14163   SDValue LHS = SVN->getOperand(0);
14164   SDValue RHS = SVN->getOperand(1);
14165   auto Mask = SVN->getMask();
14166   int NumElts = LHS.getValueType().getVectorNumElements();
14167   SDValue Res(SVN, 0);
14168   SDLoc dl(SVN);
14169 
14170   // None of these combines are useful on big endian systems since the ISA
14171   // already has a big endian bias.
14172   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14173     return Res;
14174 
14175   // If this is not a shuffle of a shuffle and the first element comes from
14176   // the second vector, canonicalize to the commuted form. This will make it
14177   // more likely to match one of the single instruction patterns.
14178   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14179       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14180     std::swap(LHS, RHS);
14181     Res = DAG.getCommutedVectorShuffle(*SVN);
14182     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14183   }
14184 
14185   // Adjust the shuffle mask if either input vector comes from a
14186   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14187   // form (to prevent the need for a swap).
14188   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14189   SDValue SToVLHS = isScalarToVec(LHS);
14190   SDValue SToVRHS = isScalarToVec(RHS);
14191   if (SToVLHS || SToVRHS) {
14192     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14193                             : SToVRHS.getValueType().getVectorNumElements();
14194     int NumEltsOut = ShuffV.size();
14195 
14196     // Initially assume that neither input is permuted. These will be adjusted
14197     // accordingly if either input is.
14198     int LHSMaxIdx = -1;
14199     int RHSMinIdx = -1;
14200     int RHSMaxIdx = -1;
14201     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14202 
14203     // Get the permuted scalar to vector nodes for the source(s) that come from
14204     // ISD::SCALAR_TO_VECTOR.
14205     if (SToVLHS) {
14206       // Set up the values for the shuffle vector fixup.
14207       LHSMaxIdx = NumEltsOut / NumEltsIn;
14208       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14209       if (SToVLHS.getValueType() != LHS.getValueType())
14210         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14211       LHS = SToVLHS;
14212     }
14213     if (SToVRHS) {
14214       RHSMinIdx = NumEltsOut;
14215       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14216       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14217       if (SToVRHS.getValueType() != RHS.getValueType())
14218         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14219       RHS = SToVRHS;
14220     }
14221 
14222     // Fix up the shuffle mask to reflect where the desired element actually is.
14223     // The minimum and maximum indices that correspond to element zero for both
14224     // the LHS and RHS are computed and will control which shuffle mask entries
14225     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14226     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14227     // HalfVec to refer to the corresponding element in the permuted vector.
14228     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14229                                     HalfVec);
14230     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14231 
14232     // We may have simplified away the shuffle. We won't be able to do anything
14233     // further with it here.
14234     if (!isa<ShuffleVectorSDNode>(Res))
14235       return Res;
14236     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14237   }
14238 
14239   // The common case after we commuted the shuffle is that the RHS is a splat
14240   // and we have elements coming in from the splat at indices that are not
14241   // conducive to using a merge.
14242   // Example:
14243   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14244   if (!isSplatBV(RHS))
14245     return Res;
14246 
14247   // We are looking for a mask such that all even elements are from
14248   // one vector and all odd elements from the other.
14249   if (!isAlternatingShuffMask(Mask, NumElts))
14250     return Res;
14251 
14252   // Adjust the mask so we are pulling in the same index from the splat
14253   // as the index from the interesting vector in consecutive elements.
14254   // Example (even elements from first vector):
14255   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14256   if (Mask[0] < NumElts)
14257     for (int i = 1, e = Mask.size(); i < e; i += 2)
14258       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14259   // Example (odd elements from first vector):
14260   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14261   else
14262     for (int i = 0, e = Mask.size(); i < e; i += 2)
14263       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14264 
14265   // If the RHS has undefs, we need to remove them since we may have created
14266   // a shuffle that adds those instead of the splat value.
14267   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14268   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14269 
14270   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14271   return Res;
14272 }
14273 
14274 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14275                                                 LSBaseSDNode *LSBase,
14276                                                 DAGCombinerInfo &DCI) const {
14277   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14278         "Not a reverse memop pattern!");
14279 
14280   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14281     auto Mask = SVN->getMask();
14282     int i = 0;
14283     auto I = Mask.rbegin();
14284     auto E = Mask.rend();
14285 
14286     for (; I != E; ++I) {
14287       if (*I != i)
14288         return false;
14289       i++;
14290     }
14291     return true;
14292   };
14293 
14294   SelectionDAG &DAG = DCI.DAG;
14295   EVT VT = SVN->getValueType(0);
14296 
14297   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14298     return SDValue();
14299 
14300   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14301   // See comment in PPCVSXSwapRemoval.cpp.
14302   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14303   if (!Subtarget.hasP9Vector())
14304     return SDValue();
14305 
14306   if(!IsElementReverse(SVN))
14307     return SDValue();
14308 
14309   if (LSBase->getOpcode() == ISD::LOAD) {
14310     SDLoc dl(SVN);
14311     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14312     return DAG.getMemIntrinsicNode(
14313         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14314         LSBase->getMemoryVT(), LSBase->getMemOperand());
14315   }
14316 
14317   if (LSBase->getOpcode() == ISD::STORE) {
14318     SDLoc dl(LSBase);
14319     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14320                           LSBase->getBasePtr()};
14321     return DAG.getMemIntrinsicNode(
14322         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14323         LSBase->getMemoryVT(), LSBase->getMemOperand());
14324   }
14325 
14326   llvm_unreachable("Expected a load or store node here");
14327 }
14328 
14329 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14330                                              DAGCombinerInfo &DCI) const {
14331   SelectionDAG &DAG = DCI.DAG;
14332   SDLoc dl(N);
14333   switch (N->getOpcode()) {
14334   default: break;
14335   case ISD::ADD:
14336     return combineADD(N, DCI);
14337   case ISD::SHL:
14338     return combineSHL(N, DCI);
14339   case ISD::SRA:
14340     return combineSRA(N, DCI);
14341   case ISD::SRL:
14342     return combineSRL(N, DCI);
14343   case ISD::MUL:
14344     return combineMUL(N, DCI);
14345   case ISD::FMA:
14346   case PPCISD::FNMSUB:
14347     return combineFMALike(N, DCI);
14348   case PPCISD::SHL:
14349     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14350         return N->getOperand(0);
14351     break;
14352   case PPCISD::SRL:
14353     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14354         return N->getOperand(0);
14355     break;
14356   case PPCISD::SRA:
14357     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14358       if (C->isNullValue() ||   //  0 >>s V -> 0.
14359           C->isAllOnesValue())    // -1 >>s V -> -1.
14360         return N->getOperand(0);
14361     }
14362     break;
14363   case ISD::SIGN_EXTEND:
14364   case ISD::ZERO_EXTEND:
14365   case ISD::ANY_EXTEND:
14366     return DAGCombineExtBoolTrunc(N, DCI);
14367   case ISD::TRUNCATE:
14368     return combineTRUNCATE(N, DCI);
14369   case ISD::SETCC:
14370     if (SDValue CSCC = combineSetCC(N, DCI))
14371       return CSCC;
14372     LLVM_FALLTHROUGH;
14373   case ISD::SELECT_CC:
14374     return DAGCombineTruncBoolExt(N, DCI);
14375   case ISD::SINT_TO_FP:
14376   case ISD::UINT_TO_FP:
14377     return combineFPToIntToFP(N, DCI);
14378   case ISD::VECTOR_SHUFFLE:
14379     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14380       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14381       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14382     }
14383     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14384   case ISD::STORE: {
14385 
14386     EVT Op1VT = N->getOperand(1).getValueType();
14387     unsigned Opcode = N->getOperand(1).getOpcode();
14388 
14389     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14390       SDValue Val= combineStoreFPToInt(N, DCI);
14391       if (Val)
14392         return Val;
14393     }
14394 
14395     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14396       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14397       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14398       if (Val)
14399         return Val;
14400     }
14401 
14402     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14403     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14404         N->getOperand(1).getNode()->hasOneUse() &&
14405         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14406          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14407 
14408       // STBRX can only handle simple types and it makes no sense to store less
14409       // two bytes in byte-reversed order.
14410       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14411       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14412         break;
14413 
14414       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14415       // Do an any-extend to 32-bits if this is a half-word input.
14416       if (BSwapOp.getValueType() == MVT::i16)
14417         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14418 
14419       // If the type of BSWAP operand is wider than stored memory width
14420       // it need to be shifted to the right side before STBRX.
14421       if (Op1VT.bitsGT(mVT)) {
14422         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14423         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14424                               DAG.getConstant(Shift, dl, MVT::i32));
14425         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14426         if (Op1VT == MVT::i64)
14427           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14428       }
14429 
14430       SDValue Ops[] = {
14431         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14432       };
14433       return
14434         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14435                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14436                                 cast<StoreSDNode>(N)->getMemOperand());
14437     }
14438 
14439     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14440     // So it can increase the chance of CSE constant construction.
14441     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14442         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14443       // Need to sign-extended to 64-bits to handle negative values.
14444       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14445       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14446                                     MemVT.getSizeInBits());
14447       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14448 
14449       // DAG.getTruncStore() can't be used here because it doesn't accept
14450       // the general (base + offset) addressing mode.
14451       // So we use UpdateNodeOperands and setTruncatingStore instead.
14452       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14453                              N->getOperand(3));
14454       cast<StoreSDNode>(N)->setTruncatingStore(true);
14455       return SDValue(N, 0);
14456     }
14457 
14458     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14459     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14460     if (Op1VT.isSimple()) {
14461       MVT StoreVT = Op1VT.getSimpleVT();
14462       if (Subtarget.needsSwapsForVSXMemOps() &&
14463           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14464            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14465         return expandVSXStoreForLE(N, DCI);
14466     }
14467     break;
14468   }
14469   case ISD::LOAD: {
14470     LoadSDNode *LD = cast<LoadSDNode>(N);
14471     EVT VT = LD->getValueType(0);
14472 
14473     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14474     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14475     if (VT.isSimple()) {
14476       MVT LoadVT = VT.getSimpleVT();
14477       if (Subtarget.needsSwapsForVSXMemOps() &&
14478           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14479            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14480         return expandVSXLoadForLE(N, DCI);
14481     }
14482 
14483     // We sometimes end up with a 64-bit integer load, from which we extract
14484     // two single-precision floating-point numbers. This happens with
14485     // std::complex<float>, and other similar structures, because of the way we
14486     // canonicalize structure copies. However, if we lack direct moves,
14487     // then the final bitcasts from the extracted integer values to the
14488     // floating-point numbers turn into store/load pairs. Even with direct moves,
14489     // just loading the two floating-point numbers is likely better.
14490     auto ReplaceTwoFloatLoad = [&]() {
14491       if (VT != MVT::i64)
14492         return false;
14493 
14494       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14495           LD->isVolatile())
14496         return false;
14497 
14498       //  We're looking for a sequence like this:
14499       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14500       //      t16: i64 = srl t13, Constant:i32<32>
14501       //    t17: i32 = truncate t16
14502       //  t18: f32 = bitcast t17
14503       //    t19: i32 = truncate t13
14504       //  t20: f32 = bitcast t19
14505 
14506       if (!LD->hasNUsesOfValue(2, 0))
14507         return false;
14508 
14509       auto UI = LD->use_begin();
14510       while (UI.getUse().getResNo() != 0) ++UI;
14511       SDNode *Trunc = *UI++;
14512       while (UI.getUse().getResNo() != 0) ++UI;
14513       SDNode *RightShift = *UI;
14514       if (Trunc->getOpcode() != ISD::TRUNCATE)
14515         std::swap(Trunc, RightShift);
14516 
14517       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14518           Trunc->getValueType(0) != MVT::i32 ||
14519           !Trunc->hasOneUse())
14520         return false;
14521       if (RightShift->getOpcode() != ISD::SRL ||
14522           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14523           RightShift->getConstantOperandVal(1) != 32 ||
14524           !RightShift->hasOneUse())
14525         return false;
14526 
14527       SDNode *Trunc2 = *RightShift->use_begin();
14528       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14529           Trunc2->getValueType(0) != MVT::i32 ||
14530           !Trunc2->hasOneUse())
14531         return false;
14532 
14533       SDNode *Bitcast = *Trunc->use_begin();
14534       SDNode *Bitcast2 = *Trunc2->use_begin();
14535 
14536       if (Bitcast->getOpcode() != ISD::BITCAST ||
14537           Bitcast->getValueType(0) != MVT::f32)
14538         return false;
14539       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14540           Bitcast2->getValueType(0) != MVT::f32)
14541         return false;
14542 
14543       if (Subtarget.isLittleEndian())
14544         std::swap(Bitcast, Bitcast2);
14545 
14546       // Bitcast has the second float (in memory-layout order) and Bitcast2
14547       // has the first one.
14548 
14549       SDValue BasePtr = LD->getBasePtr();
14550       if (LD->isIndexed()) {
14551         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14552                "Non-pre-inc AM on PPC?");
14553         BasePtr =
14554           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14555                       LD->getOffset());
14556       }
14557 
14558       auto MMOFlags =
14559           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14560       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14561                                       LD->getPointerInfo(), LD->getAlignment(),
14562                                       MMOFlags, LD->getAAInfo());
14563       SDValue AddPtr =
14564         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14565                     BasePtr, DAG.getIntPtrConstant(4, dl));
14566       SDValue FloatLoad2 = DAG.getLoad(
14567           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14568           LD->getPointerInfo().getWithOffset(4),
14569           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14570 
14571       if (LD->isIndexed()) {
14572         // Note that DAGCombine should re-form any pre-increment load(s) from
14573         // what is produced here if that makes sense.
14574         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14575       }
14576 
14577       DCI.CombineTo(Bitcast2, FloatLoad);
14578       DCI.CombineTo(Bitcast, FloatLoad2);
14579 
14580       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14581                                     SDValue(FloatLoad2.getNode(), 1));
14582       return true;
14583     };
14584 
14585     if (ReplaceTwoFloatLoad())
14586       return SDValue(N, 0);
14587 
14588     EVT MemVT = LD->getMemoryVT();
14589     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14590     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14591     if (LD->isUnindexed() && VT.isVector() &&
14592         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14593           // P8 and later hardware should just use LOAD.
14594           !Subtarget.hasP8Vector() &&
14595           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14596            VT == MVT::v4f32))) &&
14597         LD->getAlign() < ABIAlignment) {
14598       // This is a type-legal unaligned Altivec load.
14599       SDValue Chain = LD->getChain();
14600       SDValue Ptr = LD->getBasePtr();
14601       bool isLittleEndian = Subtarget.isLittleEndian();
14602 
14603       // This implements the loading of unaligned vectors as described in
14604       // the venerable Apple Velocity Engine overview. Specifically:
14605       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14606       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14607       //
14608       // The general idea is to expand a sequence of one or more unaligned
14609       // loads into an alignment-based permutation-control instruction (lvsl
14610       // or lvsr), a series of regular vector loads (which always truncate
14611       // their input address to an aligned address), and a series of
14612       // permutations.  The results of these permutations are the requested
14613       // loaded values.  The trick is that the last "extra" load is not taken
14614       // from the address you might suspect (sizeof(vector) bytes after the
14615       // last requested load), but rather sizeof(vector) - 1 bytes after the
14616       // last requested vector. The point of this is to avoid a page fault if
14617       // the base address happened to be aligned. This works because if the
14618       // base address is aligned, then adding less than a full vector length
14619       // will cause the last vector in the sequence to be (re)loaded.
14620       // Otherwise, the next vector will be fetched as you might suspect was
14621       // necessary.
14622 
14623       // We might be able to reuse the permutation generation from
14624       // a different base address offset from this one by an aligned amount.
14625       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14626       // optimization later.
14627       Intrinsic::ID Intr, IntrLD, IntrPerm;
14628       MVT PermCntlTy, PermTy, LDTy;
14629       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14630                             : Intrinsic::ppc_altivec_lvsl;
14631       IntrLD = Intrinsic::ppc_altivec_lvx;
14632       IntrPerm = Intrinsic::ppc_altivec_vperm;
14633       PermCntlTy = MVT::v16i8;
14634       PermTy = MVT::v4i32;
14635       LDTy = MVT::v4i32;
14636 
14637       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14638 
14639       // Create the new MMO for the new base load. It is like the original MMO,
14640       // but represents an area in memory almost twice the vector size centered
14641       // on the original address. If the address is unaligned, we might start
14642       // reading up to (sizeof(vector)-1) bytes below the address of the
14643       // original unaligned load.
14644       MachineFunction &MF = DAG.getMachineFunction();
14645       MachineMemOperand *BaseMMO =
14646         MF.getMachineMemOperand(LD->getMemOperand(),
14647                                 -(long)MemVT.getStoreSize()+1,
14648                                 2*MemVT.getStoreSize()-1);
14649 
14650       // Create the new base load.
14651       SDValue LDXIntID =
14652           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14653       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14654       SDValue BaseLoad =
14655         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14656                                 DAG.getVTList(PermTy, MVT::Other),
14657                                 BaseLoadOps, LDTy, BaseMMO);
14658 
14659       // Note that the value of IncOffset (which is provided to the next
14660       // load's pointer info offset value, and thus used to calculate the
14661       // alignment), and the value of IncValue (which is actually used to
14662       // increment the pointer value) are different! This is because we
14663       // require the next load to appear to be aligned, even though it
14664       // is actually offset from the base pointer by a lesser amount.
14665       int IncOffset = VT.getSizeInBits() / 8;
14666       int IncValue = IncOffset;
14667 
14668       // Walk (both up and down) the chain looking for another load at the real
14669       // (aligned) offset (the alignment of the other load does not matter in
14670       // this case). If found, then do not use the offset reduction trick, as
14671       // that will prevent the loads from being later combined (as they would
14672       // otherwise be duplicates).
14673       if (!findConsecutiveLoad(LD, DAG))
14674         --IncValue;
14675 
14676       SDValue Increment =
14677           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14678       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14679 
14680       MachineMemOperand *ExtraMMO =
14681         MF.getMachineMemOperand(LD->getMemOperand(),
14682                                 1, 2*MemVT.getStoreSize()-1);
14683       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14684       SDValue ExtraLoad =
14685         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14686                                 DAG.getVTList(PermTy, MVT::Other),
14687                                 ExtraLoadOps, LDTy, ExtraMMO);
14688 
14689       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14690         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14691 
14692       // Because vperm has a big-endian bias, we must reverse the order
14693       // of the input vectors and complement the permute control vector
14694       // when generating little endian code.  We have already handled the
14695       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14696       // and ExtraLoad here.
14697       SDValue Perm;
14698       if (isLittleEndian)
14699         Perm = BuildIntrinsicOp(IntrPerm,
14700                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14701       else
14702         Perm = BuildIntrinsicOp(IntrPerm,
14703                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14704 
14705       if (VT != PermTy)
14706         Perm = Subtarget.hasAltivec()
14707                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14708                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14709                                  DAG.getTargetConstant(1, dl, MVT::i64));
14710                                // second argument is 1 because this rounding
14711                                // is always exact.
14712 
14713       // The output of the permutation is our loaded result, the TokenFactor is
14714       // our new chain.
14715       DCI.CombineTo(N, Perm, TF);
14716       return SDValue(N, 0);
14717     }
14718     }
14719     break;
14720     case ISD::INTRINSIC_WO_CHAIN: {
14721       bool isLittleEndian = Subtarget.isLittleEndian();
14722       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14723       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14724                                            : Intrinsic::ppc_altivec_lvsl);
14725       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14726         SDValue Add = N->getOperand(1);
14727 
14728         int Bits = 4 /* 16 byte alignment */;
14729 
14730         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14731                                   APInt::getAllOnesValue(Bits /* alignment */)
14732                                       .zext(Add.getScalarValueSizeInBits()))) {
14733           SDNode *BasePtr = Add->getOperand(0).getNode();
14734           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14735                                     UE = BasePtr->use_end();
14736                UI != UE; ++UI) {
14737             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14738                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14739                     IID) {
14740               // We've found another LVSL/LVSR, and this address is an aligned
14741               // multiple of that one. The results will be the same, so use the
14742               // one we've just found instead.
14743 
14744               return SDValue(*UI, 0);
14745             }
14746           }
14747         }
14748 
14749         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14750           SDNode *BasePtr = Add->getOperand(0).getNode();
14751           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14752                UE = BasePtr->use_end(); UI != UE; ++UI) {
14753             if (UI->getOpcode() == ISD::ADD &&
14754                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14755                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14756                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14757                 (1ULL << Bits) == 0) {
14758               SDNode *OtherAdd = *UI;
14759               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14760                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14761                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14762                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14763                   return SDValue(*VI, 0);
14764                 }
14765               }
14766             }
14767           }
14768         }
14769       }
14770 
14771       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14772       // Expose the vabsduw/h/b opportunity for down stream
14773       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14774           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14775            IID == Intrinsic::ppc_altivec_vmaxsh ||
14776            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14777         SDValue V1 = N->getOperand(1);
14778         SDValue V2 = N->getOperand(2);
14779         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14780              V1.getSimpleValueType() == MVT::v8i16 ||
14781              V1.getSimpleValueType() == MVT::v16i8) &&
14782             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14783           // (0-a, a)
14784           if (V1.getOpcode() == ISD::SUB &&
14785               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14786               V1.getOperand(1) == V2) {
14787             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14788           }
14789           // (a, 0-a)
14790           if (V2.getOpcode() == ISD::SUB &&
14791               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14792               V2.getOperand(1) == V1) {
14793             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14794           }
14795           // (x-y, y-x)
14796           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14797               V1.getOperand(0) == V2.getOperand(1) &&
14798               V1.getOperand(1) == V2.getOperand(0)) {
14799             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14800           }
14801         }
14802       }
14803     }
14804 
14805     break;
14806   case ISD::INTRINSIC_W_CHAIN:
14807     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14808     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14809     if (Subtarget.needsSwapsForVSXMemOps()) {
14810       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14811       default:
14812         break;
14813       case Intrinsic::ppc_vsx_lxvw4x:
14814       case Intrinsic::ppc_vsx_lxvd2x:
14815         return expandVSXLoadForLE(N, DCI);
14816       }
14817     }
14818     break;
14819   case ISD::INTRINSIC_VOID:
14820     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14821     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14822     if (Subtarget.needsSwapsForVSXMemOps()) {
14823       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14824       default:
14825         break;
14826       case Intrinsic::ppc_vsx_stxvw4x:
14827       case Intrinsic::ppc_vsx_stxvd2x:
14828         return expandVSXStoreForLE(N, DCI);
14829       }
14830     }
14831     break;
14832   case ISD::BSWAP:
14833     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14834     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14835         N->getOperand(0).hasOneUse() &&
14836         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14837          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14838           N->getValueType(0) == MVT::i64))) {
14839       SDValue Load = N->getOperand(0);
14840       LoadSDNode *LD = cast<LoadSDNode>(Load);
14841       // Create the byte-swapping load.
14842       SDValue Ops[] = {
14843         LD->getChain(),    // Chain
14844         LD->getBasePtr(),  // Ptr
14845         DAG.getValueType(N->getValueType(0)) // VT
14846       };
14847       SDValue BSLoad =
14848         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14849                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14850                                               MVT::i64 : MVT::i32, MVT::Other),
14851                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14852 
14853       // If this is an i16 load, insert the truncate.
14854       SDValue ResVal = BSLoad;
14855       if (N->getValueType(0) == MVT::i16)
14856         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14857 
14858       // First, combine the bswap away.  This makes the value produced by the
14859       // load dead.
14860       DCI.CombineTo(N, ResVal);
14861 
14862       // Next, combine the load away, we give it a bogus result value but a real
14863       // chain result.  The result value is dead because the bswap is dead.
14864       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14865 
14866       // Return N so it doesn't get rechecked!
14867       return SDValue(N, 0);
14868     }
14869     break;
14870   case PPCISD::VCMP:
14871     // If a VCMPo node already exists with exactly the same operands as this
14872     // node, use its result instead of this node (VCMPo computes both a CR6 and
14873     // a normal output).
14874     //
14875     if (!N->getOperand(0).hasOneUse() &&
14876         !N->getOperand(1).hasOneUse() &&
14877         !N->getOperand(2).hasOneUse()) {
14878 
14879       // Scan all of the users of the LHS, looking for VCMPo's that match.
14880       SDNode *VCMPoNode = nullptr;
14881 
14882       SDNode *LHSN = N->getOperand(0).getNode();
14883       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14884            UI != E; ++UI)
14885         if (UI->getOpcode() == PPCISD::VCMPo &&
14886             UI->getOperand(1) == N->getOperand(1) &&
14887             UI->getOperand(2) == N->getOperand(2) &&
14888             UI->getOperand(0) == N->getOperand(0)) {
14889           VCMPoNode = *UI;
14890           break;
14891         }
14892 
14893       // If there is no VCMPo node, or if the flag value has a single use, don't
14894       // transform this.
14895       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14896         break;
14897 
14898       // Look at the (necessarily single) use of the flag value.  If it has a
14899       // chain, this transformation is more complex.  Note that multiple things
14900       // could use the value result, which we should ignore.
14901       SDNode *FlagUser = nullptr;
14902       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14903            FlagUser == nullptr; ++UI) {
14904         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14905         SDNode *User = *UI;
14906         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14907           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14908             FlagUser = User;
14909             break;
14910           }
14911         }
14912       }
14913 
14914       // If the user is a MFOCRF instruction, we know this is safe.
14915       // Otherwise we give up for right now.
14916       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14917         return SDValue(VCMPoNode, 0);
14918     }
14919     break;
14920   case ISD::BRCOND: {
14921     SDValue Cond = N->getOperand(1);
14922     SDValue Target = N->getOperand(2);
14923 
14924     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14925         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14926           Intrinsic::loop_decrement) {
14927 
14928       // We now need to make the intrinsic dead (it cannot be instruction
14929       // selected).
14930       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14931       assert(Cond.getNode()->hasOneUse() &&
14932              "Counter decrement has more than one use");
14933 
14934       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14935                          N->getOperand(0), Target);
14936     }
14937   }
14938   break;
14939   case ISD::BR_CC: {
14940     // If this is a branch on an altivec predicate comparison, lower this so
14941     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14942     // lowering is done pre-legalize, because the legalizer lowers the predicate
14943     // compare down to code that is difficult to reassemble.
14944     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14945     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14946 
14947     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14948     // value. If so, pass-through the AND to get to the intrinsic.
14949     if (LHS.getOpcode() == ISD::AND &&
14950         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14951         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14952           Intrinsic::loop_decrement &&
14953         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14954         !isNullConstant(LHS.getOperand(1)))
14955       LHS = LHS.getOperand(0);
14956 
14957     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14958         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14959           Intrinsic::loop_decrement &&
14960         isa<ConstantSDNode>(RHS)) {
14961       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14962              "Counter decrement comparison is not EQ or NE");
14963 
14964       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14965       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14966                     (CC == ISD::SETNE && !Val);
14967 
14968       // We now need to make the intrinsic dead (it cannot be instruction
14969       // selected).
14970       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14971       assert(LHS.getNode()->hasOneUse() &&
14972              "Counter decrement has more than one use");
14973 
14974       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14975                          N->getOperand(0), N->getOperand(4));
14976     }
14977 
14978     int CompareOpc;
14979     bool isDot;
14980 
14981     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14982         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14983         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14984       assert(isDot && "Can't compare against a vector result!");
14985 
14986       // If this is a comparison against something other than 0/1, then we know
14987       // that the condition is never/always true.
14988       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14989       if (Val != 0 && Val != 1) {
14990         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14991           return N->getOperand(0);
14992         // Always !=, turn it into an unconditional branch.
14993         return DAG.getNode(ISD::BR, dl, MVT::Other,
14994                            N->getOperand(0), N->getOperand(4));
14995       }
14996 
14997       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14998 
14999       // Create the PPCISD altivec 'dot' comparison node.
15000       SDValue Ops[] = {
15001         LHS.getOperand(2),  // LHS of compare
15002         LHS.getOperand(3),  // RHS of compare
15003         DAG.getConstant(CompareOpc, dl, MVT::i32)
15004       };
15005       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15006       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
15007 
15008       // Unpack the result based on how the target uses it.
15009       PPC::Predicate CompOpc;
15010       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15011       default:  // Can't happen, don't crash on invalid number though.
15012       case 0:   // Branch on the value of the EQ bit of CR6.
15013         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15014         break;
15015       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15016         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15017         break;
15018       case 2:   // Branch on the value of the LT bit of CR6.
15019         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15020         break;
15021       case 3:   // Branch on the inverted value of the LT bit of CR6.
15022         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15023         break;
15024       }
15025 
15026       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15027                          DAG.getConstant(CompOpc, dl, MVT::i32),
15028                          DAG.getRegister(PPC::CR6, MVT::i32),
15029                          N->getOperand(4), CompNode.getValue(1));
15030     }
15031     break;
15032   }
15033   case ISD::BUILD_VECTOR:
15034     return DAGCombineBuildVector(N, DCI);
15035   case ISD::ABS:
15036     return combineABS(N, DCI);
15037   case ISD::VSELECT:
15038     return combineVSelect(N, DCI);
15039   }
15040 
15041   return SDValue();
15042 }
15043 
15044 SDValue
15045 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15046                                  SelectionDAG &DAG,
15047                                  SmallVectorImpl<SDNode *> &Created) const {
15048   // fold (sdiv X, pow2)
15049   EVT VT = N->getValueType(0);
15050   if (VT == MVT::i64 && !Subtarget.isPPC64())
15051     return SDValue();
15052   if ((VT != MVT::i32 && VT != MVT::i64) ||
15053       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
15054     return SDValue();
15055 
15056   SDLoc DL(N);
15057   SDValue N0 = N->getOperand(0);
15058 
15059   bool IsNegPow2 = (-Divisor).isPowerOf2();
15060   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15061   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15062 
15063   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15064   Created.push_back(Op.getNode());
15065 
15066   if (IsNegPow2) {
15067     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15068     Created.push_back(Op.getNode());
15069   }
15070 
15071   return Op;
15072 }
15073 
15074 //===----------------------------------------------------------------------===//
15075 // Inline Assembly Support
15076 //===----------------------------------------------------------------------===//
15077 
15078 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15079                                                       KnownBits &Known,
15080                                                       const APInt &DemandedElts,
15081                                                       const SelectionDAG &DAG,
15082                                                       unsigned Depth) const {
15083   Known.resetAll();
15084   switch (Op.getOpcode()) {
15085   default: break;
15086   case PPCISD::LBRX: {
15087     // lhbrx is known to have the top bits cleared out.
15088     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15089       Known.Zero = 0xFFFF0000;
15090     break;
15091   }
15092   case ISD::INTRINSIC_WO_CHAIN: {
15093     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15094     default: break;
15095     case Intrinsic::ppc_altivec_vcmpbfp_p:
15096     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15097     case Intrinsic::ppc_altivec_vcmpequb_p:
15098     case Intrinsic::ppc_altivec_vcmpequh_p:
15099     case Intrinsic::ppc_altivec_vcmpequw_p:
15100     case Intrinsic::ppc_altivec_vcmpequd_p:
15101     case Intrinsic::ppc_altivec_vcmpgefp_p:
15102     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15103     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15104     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15105     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15106     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15107     case Intrinsic::ppc_altivec_vcmpgtub_p:
15108     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15109     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15110     case Intrinsic::ppc_altivec_vcmpgtud_p:
15111       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15112       break;
15113     }
15114   }
15115   }
15116 }
15117 
15118 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15119   switch (Subtarget.getCPUDirective()) {
15120   default: break;
15121   case PPC::DIR_970:
15122   case PPC::DIR_PWR4:
15123   case PPC::DIR_PWR5:
15124   case PPC::DIR_PWR5X:
15125   case PPC::DIR_PWR6:
15126   case PPC::DIR_PWR6X:
15127   case PPC::DIR_PWR7:
15128   case PPC::DIR_PWR8:
15129   case PPC::DIR_PWR9:
15130   case PPC::DIR_PWR10:
15131   case PPC::DIR_PWR_FUTURE: {
15132     if (!ML)
15133       break;
15134 
15135     if (!DisableInnermostLoopAlign32) {
15136       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15137       // so that we can decrease cache misses and branch-prediction misses.
15138       // Actual alignment of the loop will depend on the hotness check and other
15139       // logic in alignBlocks.
15140       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15141         return Align(32);
15142     }
15143 
15144     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15145 
15146     // For small loops (between 5 and 8 instructions), align to a 32-byte
15147     // boundary so that the entire loop fits in one instruction-cache line.
15148     uint64_t LoopSize = 0;
15149     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15150       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15151         LoopSize += TII->getInstSizeInBytes(*J);
15152         if (LoopSize > 32)
15153           break;
15154       }
15155 
15156     if (LoopSize > 16 && LoopSize <= 32)
15157       return Align(32);
15158 
15159     break;
15160   }
15161   }
15162 
15163   return TargetLowering::getPrefLoopAlignment(ML);
15164 }
15165 
15166 /// getConstraintType - Given a constraint, return the type of
15167 /// constraint it is for this target.
15168 PPCTargetLowering::ConstraintType
15169 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15170   if (Constraint.size() == 1) {
15171     switch (Constraint[0]) {
15172     default: break;
15173     case 'b':
15174     case 'r':
15175     case 'f':
15176     case 'd':
15177     case 'v':
15178     case 'y':
15179       return C_RegisterClass;
15180     case 'Z':
15181       // FIXME: While Z does indicate a memory constraint, it specifically
15182       // indicates an r+r address (used in conjunction with the 'y' modifier
15183       // in the replacement string). Currently, we're forcing the base
15184       // register to be r0 in the asm printer (which is interpreted as zero)
15185       // and forming the complete address in the second register. This is
15186       // suboptimal.
15187       return C_Memory;
15188     }
15189   } else if (Constraint == "wc") { // individual CR bits.
15190     return C_RegisterClass;
15191   } else if (Constraint == "wa" || Constraint == "wd" ||
15192              Constraint == "wf" || Constraint == "ws" ||
15193              Constraint == "wi" || Constraint == "ww") {
15194     return C_RegisterClass; // VSX registers.
15195   }
15196   return TargetLowering::getConstraintType(Constraint);
15197 }
15198 
15199 /// Examine constraint type and operand type and determine a weight value.
15200 /// This object must already have been set up with the operand type
15201 /// and the current alternative constraint selected.
15202 TargetLowering::ConstraintWeight
15203 PPCTargetLowering::getSingleConstraintMatchWeight(
15204     AsmOperandInfo &info, const char *constraint) const {
15205   ConstraintWeight weight = CW_Invalid;
15206   Value *CallOperandVal = info.CallOperandVal;
15207     // If we don't have a value, we can't do a match,
15208     // but allow it at the lowest weight.
15209   if (!CallOperandVal)
15210     return CW_Default;
15211   Type *type = CallOperandVal->getType();
15212 
15213   // Look at the constraint type.
15214   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15215     return CW_Register; // an individual CR bit.
15216   else if ((StringRef(constraint) == "wa" ||
15217             StringRef(constraint) == "wd" ||
15218             StringRef(constraint) == "wf") &&
15219            type->isVectorTy())
15220     return CW_Register;
15221   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15222     return CW_Register; // just hold 64-bit integers data.
15223   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15224     return CW_Register;
15225   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15226     return CW_Register;
15227 
15228   switch (*constraint) {
15229   default:
15230     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15231     break;
15232   case 'b':
15233     if (type->isIntegerTy())
15234       weight = CW_Register;
15235     break;
15236   case 'f':
15237     if (type->isFloatTy())
15238       weight = CW_Register;
15239     break;
15240   case 'd':
15241     if (type->isDoubleTy())
15242       weight = CW_Register;
15243     break;
15244   case 'v':
15245     if (type->isVectorTy())
15246       weight = CW_Register;
15247     break;
15248   case 'y':
15249     weight = CW_Register;
15250     break;
15251   case 'Z':
15252     weight = CW_Memory;
15253     break;
15254   }
15255   return weight;
15256 }
15257 
15258 std::pair<unsigned, const TargetRegisterClass *>
15259 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15260                                                 StringRef Constraint,
15261                                                 MVT VT) const {
15262   if (Constraint.size() == 1) {
15263     // GCC RS6000 Constraint Letters
15264     switch (Constraint[0]) {
15265     case 'b':   // R1-R31
15266       if (VT == MVT::i64 && Subtarget.isPPC64())
15267         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15268       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15269     case 'r':   // R0-R31
15270       if (VT == MVT::i64 && Subtarget.isPPC64())
15271         return std::make_pair(0U, &PPC::G8RCRegClass);
15272       return std::make_pair(0U, &PPC::GPRCRegClass);
15273     // 'd' and 'f' constraints are both defined to be "the floating point
15274     // registers", where one is for 32-bit and the other for 64-bit. We don't
15275     // really care overly much here so just give them all the same reg classes.
15276     case 'd':
15277     case 'f':
15278       if (Subtarget.hasSPE()) {
15279         if (VT == MVT::f32 || VT == MVT::i32)
15280           return std::make_pair(0U, &PPC::GPRCRegClass);
15281         if (VT == MVT::f64 || VT == MVT::i64)
15282           return std::make_pair(0U, &PPC::SPERCRegClass);
15283       } else {
15284         if (VT == MVT::f32 || VT == MVT::i32)
15285           return std::make_pair(0U, &PPC::F4RCRegClass);
15286         if (VT == MVT::f64 || VT == MVT::i64)
15287           return std::make_pair(0U, &PPC::F8RCRegClass);
15288       }
15289       break;
15290     case 'v':
15291       if (Subtarget.hasAltivec())
15292         return std::make_pair(0U, &PPC::VRRCRegClass);
15293       break;
15294     case 'y':   // crrc
15295       return std::make_pair(0U, &PPC::CRRCRegClass);
15296     }
15297   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15298     // An individual CR bit.
15299     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15300   } else if ((Constraint == "wa" || Constraint == "wd" ||
15301              Constraint == "wf" || Constraint == "wi") &&
15302              Subtarget.hasVSX()) {
15303     return std::make_pair(0U, &PPC::VSRCRegClass);
15304   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15305     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15306       return std::make_pair(0U, &PPC::VSSRCRegClass);
15307     else
15308       return std::make_pair(0U, &PPC::VSFRCRegClass);
15309   }
15310 
15311   // If we name a VSX register, we can't defer to the base class because it
15312   // will not recognize the correct register (their names will be VSL{0-31}
15313   // and V{0-31} so they won't match). So we match them here.
15314   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15315     int VSNum = atoi(Constraint.data() + 3);
15316     assert(VSNum >= 0 && VSNum <= 63 &&
15317            "Attempted to access a vsr out of range");
15318     if (VSNum < 32)
15319       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15320     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15321   }
15322   std::pair<unsigned, const TargetRegisterClass *> R =
15323       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15324 
15325   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15326   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15327   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15328   // register.
15329   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15330   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15331   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15332       PPC::GPRCRegClass.contains(R.first))
15333     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15334                             PPC::sub_32, &PPC::G8RCRegClass),
15335                           &PPC::G8RCRegClass);
15336 
15337   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15338   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15339     R.first = PPC::CR0;
15340     R.second = &PPC::CRRCRegClass;
15341   }
15342 
15343   return R;
15344 }
15345 
15346 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15347 /// vector.  If it is invalid, don't add anything to Ops.
15348 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15349                                                      std::string &Constraint,
15350                                                      std::vector<SDValue>&Ops,
15351                                                      SelectionDAG &DAG) const {
15352   SDValue Result;
15353 
15354   // Only support length 1 constraints.
15355   if (Constraint.length() > 1) return;
15356 
15357   char Letter = Constraint[0];
15358   switch (Letter) {
15359   default: break;
15360   case 'I':
15361   case 'J':
15362   case 'K':
15363   case 'L':
15364   case 'M':
15365   case 'N':
15366   case 'O':
15367   case 'P': {
15368     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15369     if (!CST) return; // Must be an immediate to match.
15370     SDLoc dl(Op);
15371     int64_t Value = CST->getSExtValue();
15372     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15373                          // numbers are printed as such.
15374     switch (Letter) {
15375     default: llvm_unreachable("Unknown constraint letter!");
15376     case 'I':  // "I" is a signed 16-bit constant.
15377       if (isInt<16>(Value))
15378         Result = DAG.getTargetConstant(Value, dl, TCVT);
15379       break;
15380     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15381       if (isShiftedUInt<16, 16>(Value))
15382         Result = DAG.getTargetConstant(Value, dl, TCVT);
15383       break;
15384     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15385       if (isShiftedInt<16, 16>(Value))
15386         Result = DAG.getTargetConstant(Value, dl, TCVT);
15387       break;
15388     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15389       if (isUInt<16>(Value))
15390         Result = DAG.getTargetConstant(Value, dl, TCVT);
15391       break;
15392     case 'M':  // "M" is a constant that is greater than 31.
15393       if (Value > 31)
15394         Result = DAG.getTargetConstant(Value, dl, TCVT);
15395       break;
15396     case 'N':  // "N" is a positive constant that is an exact power of two.
15397       if (Value > 0 && isPowerOf2_64(Value))
15398         Result = DAG.getTargetConstant(Value, dl, TCVT);
15399       break;
15400     case 'O':  // "O" is the constant zero.
15401       if (Value == 0)
15402         Result = DAG.getTargetConstant(Value, dl, TCVT);
15403       break;
15404     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15405       if (isInt<16>(-Value))
15406         Result = DAG.getTargetConstant(Value, dl, TCVT);
15407       break;
15408     }
15409     break;
15410   }
15411   }
15412 
15413   if (Result.getNode()) {
15414     Ops.push_back(Result);
15415     return;
15416   }
15417 
15418   // Handle standard constraint letters.
15419   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15420 }
15421 
15422 // isLegalAddressingMode - Return true if the addressing mode represented
15423 // by AM is legal for this target, for a load/store of the specified type.
15424 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15425                                               const AddrMode &AM, Type *Ty,
15426                                               unsigned AS,
15427                                               Instruction *I) const {
15428   // Vector type r+i form is supported since power9 as DQ form. We don't check
15429   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15430   // imm form is preferred and the offset can be adjusted to use imm form later
15431   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15432   // max offset to check legal addressing mode, we should be a little aggressive
15433   // to contain other offsets for that LSRUse.
15434   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15435     return false;
15436 
15437   // PPC allows a sign-extended 16-bit immediate field.
15438   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15439     return false;
15440 
15441   // No global is ever allowed as a base.
15442   if (AM.BaseGV)
15443     return false;
15444 
15445   // PPC only support r+r,
15446   switch (AM.Scale) {
15447   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15448     break;
15449   case 1:
15450     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15451       return false;
15452     // Otherwise we have r+r or r+i.
15453     break;
15454   case 2:
15455     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15456       return false;
15457     // Allow 2*r as r+r.
15458     break;
15459   default:
15460     // No other scales are supported.
15461     return false;
15462   }
15463 
15464   return true;
15465 }
15466 
15467 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15468                                            SelectionDAG &DAG) const {
15469   MachineFunction &MF = DAG.getMachineFunction();
15470   MachineFrameInfo &MFI = MF.getFrameInfo();
15471   MFI.setReturnAddressIsTaken(true);
15472 
15473   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15474     return SDValue();
15475 
15476   SDLoc dl(Op);
15477   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15478 
15479   // Make sure the function does not optimize away the store of the RA to
15480   // the stack.
15481   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15482   FuncInfo->setLRStoreRequired();
15483   bool isPPC64 = Subtarget.isPPC64();
15484   auto PtrVT = getPointerTy(MF.getDataLayout());
15485 
15486   if (Depth > 0) {
15487     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15488     SDValue Offset =
15489         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15490                         isPPC64 ? MVT::i64 : MVT::i32);
15491     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15492                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15493                        MachinePointerInfo());
15494   }
15495 
15496   // Just load the return address off the stack.
15497   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15498   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15499                      MachinePointerInfo());
15500 }
15501 
15502 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15503                                           SelectionDAG &DAG) const {
15504   SDLoc dl(Op);
15505   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15506 
15507   MachineFunction &MF = DAG.getMachineFunction();
15508   MachineFrameInfo &MFI = MF.getFrameInfo();
15509   MFI.setFrameAddressIsTaken(true);
15510 
15511   EVT PtrVT = getPointerTy(MF.getDataLayout());
15512   bool isPPC64 = PtrVT == MVT::i64;
15513 
15514   // Naked functions never have a frame pointer, and so we use r1. For all
15515   // other functions, this decision must be delayed until during PEI.
15516   unsigned FrameReg;
15517   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15518     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15519   else
15520     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15521 
15522   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15523                                          PtrVT);
15524   while (Depth--)
15525     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15526                             FrameAddr, MachinePointerInfo());
15527   return FrameAddr;
15528 }
15529 
15530 // FIXME? Maybe this could be a TableGen attribute on some registers and
15531 // this table could be generated automatically from RegInfo.
15532 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15533                                               const MachineFunction &MF) const {
15534   bool isPPC64 = Subtarget.isPPC64();
15535 
15536   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15537   if (!is64Bit && VT != LLT::scalar(32))
15538     report_fatal_error("Invalid register global variable type");
15539 
15540   Register Reg = StringSwitch<Register>(RegName)
15541                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15542                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15543                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15544                      .Default(Register());
15545 
15546   if (Reg)
15547     return Reg;
15548   report_fatal_error("Invalid register name global variable");
15549 }
15550 
15551 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15552   // 32-bit SVR4 ABI access everything as got-indirect.
15553   if (Subtarget.is32BitELFABI())
15554     return true;
15555 
15556   // AIX accesses everything indirectly through the TOC, which is similar to
15557   // the GOT.
15558   if (Subtarget.isAIXABI())
15559     return true;
15560 
15561   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15562   // If it is small or large code model, module locals are accessed
15563   // indirectly by loading their address from .toc/.got.
15564   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15565     return true;
15566 
15567   // JumpTable and BlockAddress are accessed as got-indirect.
15568   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15569     return true;
15570 
15571   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15572     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15573 
15574   return false;
15575 }
15576 
15577 bool
15578 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15579   // The PowerPC target isn't yet aware of offsets.
15580   return false;
15581 }
15582 
15583 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15584                                            const CallInst &I,
15585                                            MachineFunction &MF,
15586                                            unsigned Intrinsic) const {
15587   switch (Intrinsic) {
15588   case Intrinsic::ppc_altivec_lvx:
15589   case Intrinsic::ppc_altivec_lvxl:
15590   case Intrinsic::ppc_altivec_lvebx:
15591   case Intrinsic::ppc_altivec_lvehx:
15592   case Intrinsic::ppc_altivec_lvewx:
15593   case Intrinsic::ppc_vsx_lxvd2x:
15594   case Intrinsic::ppc_vsx_lxvw4x: {
15595     EVT VT;
15596     switch (Intrinsic) {
15597     case Intrinsic::ppc_altivec_lvebx:
15598       VT = MVT::i8;
15599       break;
15600     case Intrinsic::ppc_altivec_lvehx:
15601       VT = MVT::i16;
15602       break;
15603     case Intrinsic::ppc_altivec_lvewx:
15604       VT = MVT::i32;
15605       break;
15606     case Intrinsic::ppc_vsx_lxvd2x:
15607       VT = MVT::v2f64;
15608       break;
15609     default:
15610       VT = MVT::v4i32;
15611       break;
15612     }
15613 
15614     Info.opc = ISD::INTRINSIC_W_CHAIN;
15615     Info.memVT = VT;
15616     Info.ptrVal = I.getArgOperand(0);
15617     Info.offset = -VT.getStoreSize()+1;
15618     Info.size = 2*VT.getStoreSize()-1;
15619     Info.align = Align(1);
15620     Info.flags = MachineMemOperand::MOLoad;
15621     return true;
15622   }
15623   case Intrinsic::ppc_altivec_stvx:
15624   case Intrinsic::ppc_altivec_stvxl:
15625   case Intrinsic::ppc_altivec_stvebx:
15626   case Intrinsic::ppc_altivec_stvehx:
15627   case Intrinsic::ppc_altivec_stvewx:
15628   case Intrinsic::ppc_vsx_stxvd2x:
15629   case Intrinsic::ppc_vsx_stxvw4x: {
15630     EVT VT;
15631     switch (Intrinsic) {
15632     case Intrinsic::ppc_altivec_stvebx:
15633       VT = MVT::i8;
15634       break;
15635     case Intrinsic::ppc_altivec_stvehx:
15636       VT = MVT::i16;
15637       break;
15638     case Intrinsic::ppc_altivec_stvewx:
15639       VT = MVT::i32;
15640       break;
15641     case Intrinsic::ppc_vsx_stxvd2x:
15642       VT = MVT::v2f64;
15643       break;
15644     default:
15645       VT = MVT::v4i32;
15646       break;
15647     }
15648 
15649     Info.opc = ISD::INTRINSIC_VOID;
15650     Info.memVT = VT;
15651     Info.ptrVal = I.getArgOperand(1);
15652     Info.offset = -VT.getStoreSize()+1;
15653     Info.size = 2*VT.getStoreSize()-1;
15654     Info.align = Align(1);
15655     Info.flags = MachineMemOperand::MOStore;
15656     return true;
15657   }
15658   default:
15659     break;
15660   }
15661 
15662   return false;
15663 }
15664 
15665 /// It returns EVT::Other if the type should be determined using generic
15666 /// target-independent logic.
15667 EVT PPCTargetLowering::getOptimalMemOpType(
15668     const MemOp &Op, const AttributeList &FuncAttributes) const {
15669   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15670     // We should use Altivec/VSX loads and stores when available. For unaligned
15671     // addresses, unaligned VSX loads are only fast starting with the P8.
15672     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15673         (Op.isAligned(Align(16)) ||
15674          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15675       return MVT::v4i32;
15676   }
15677 
15678   if (Subtarget.isPPC64()) {
15679     return MVT::i64;
15680   }
15681 
15682   return MVT::i32;
15683 }
15684 
15685 /// Returns true if it is beneficial to convert a load of a constant
15686 /// to just the constant itself.
15687 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15688                                                           Type *Ty) const {
15689   assert(Ty->isIntegerTy());
15690 
15691   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15692   return !(BitSize == 0 || BitSize > 64);
15693 }
15694 
15695 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15696   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15697     return false;
15698   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15699   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15700   return NumBits1 == 64 && NumBits2 == 32;
15701 }
15702 
15703 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15704   if (!VT1.isInteger() || !VT2.isInteger())
15705     return false;
15706   unsigned NumBits1 = VT1.getSizeInBits();
15707   unsigned NumBits2 = VT2.getSizeInBits();
15708   return NumBits1 == 64 && NumBits2 == 32;
15709 }
15710 
15711 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15712   // Generally speaking, zexts are not free, but they are free when they can be
15713   // folded with other operations.
15714   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15715     EVT MemVT = LD->getMemoryVT();
15716     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15717          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15718         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15719          LD->getExtensionType() == ISD::ZEXTLOAD))
15720       return true;
15721   }
15722 
15723   // FIXME: Add other cases...
15724   //  - 32-bit shifts with a zext to i64
15725   //  - zext after ctlz, bswap, etc.
15726   //  - zext after and by a constant mask
15727 
15728   return TargetLowering::isZExtFree(Val, VT2);
15729 }
15730 
15731 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15732   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15733          "invalid fpext types");
15734   // Extending to float128 is not free.
15735   if (DestVT == MVT::f128)
15736     return false;
15737   return true;
15738 }
15739 
15740 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15741   return isInt<16>(Imm) || isUInt<16>(Imm);
15742 }
15743 
15744 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15745   return isInt<16>(Imm) || isUInt<16>(Imm);
15746 }
15747 
15748 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15749                                                        unsigned,
15750                                                        unsigned,
15751                                                        MachineMemOperand::Flags,
15752                                                        bool *Fast) const {
15753   if (DisablePPCUnaligned)
15754     return false;
15755 
15756   // PowerPC supports unaligned memory access for simple non-vector types.
15757   // Although accessing unaligned addresses is not as efficient as accessing
15758   // aligned addresses, it is generally more efficient than manual expansion,
15759   // and generally only traps for software emulation when crossing page
15760   // boundaries.
15761 
15762   if (!VT.isSimple())
15763     return false;
15764 
15765   if (VT.isFloatingPoint() && !VT.isVector() &&
15766       !Subtarget.allowsUnalignedFPAccess())
15767     return false;
15768 
15769   if (VT.getSimpleVT().isVector()) {
15770     if (Subtarget.hasVSX()) {
15771       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15772           VT != MVT::v4f32 && VT != MVT::v4i32)
15773         return false;
15774     } else {
15775       return false;
15776     }
15777   }
15778 
15779   if (VT == MVT::ppcf128)
15780     return false;
15781 
15782   if (Fast)
15783     *Fast = true;
15784 
15785   return true;
15786 }
15787 
15788 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15789                                                    EVT VT) const {
15790   return isFMAFasterThanFMulAndFAdd(
15791       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15792 }
15793 
15794 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15795                                                    Type *Ty) const {
15796   switch (Ty->getScalarType()->getTypeID()) {
15797   case Type::FloatTyID:
15798   case Type::DoubleTyID:
15799     return true;
15800   case Type::FP128TyID:
15801     return Subtarget.hasP9Vector();
15802   default:
15803     return false;
15804   }
15805 }
15806 
15807 // FIXME: add more patterns which are not profitable to hoist.
15808 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15809   if (!I->hasOneUse())
15810     return true;
15811 
15812   Instruction *User = I->user_back();
15813   assert(User && "A single use instruction with no uses.");
15814 
15815   switch (I->getOpcode()) {
15816   case Instruction::FMul: {
15817     // Don't break FMA, PowerPC prefers FMA.
15818     if (User->getOpcode() != Instruction::FSub &&
15819         User->getOpcode() != Instruction::FAdd)
15820       return true;
15821 
15822     const TargetOptions &Options = getTargetMachine().Options;
15823     const Function *F = I->getFunction();
15824     const DataLayout &DL = F->getParent()->getDataLayout();
15825     Type *Ty = User->getOperand(0)->getType();
15826 
15827     return !(
15828         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15829         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15830         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15831   }
15832   case Instruction::Load: {
15833     // Don't break "store (load float*)" pattern, this pattern will be combined
15834     // to "store (load int32)" in later InstCombine pass. See function
15835     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15836     // cycles than loading a 32 bit integer.
15837     LoadInst *LI = cast<LoadInst>(I);
15838     // For the loads that combineLoadToOperationType does nothing, like
15839     // ordered load, it should be profitable to hoist them.
15840     // For swifterror load, it can only be used for pointer to pointer type, so
15841     // later type check should get rid of this case.
15842     if (!LI->isUnordered())
15843       return true;
15844 
15845     if (User->getOpcode() != Instruction::Store)
15846       return true;
15847 
15848     if (I->getType()->getTypeID() != Type::FloatTyID)
15849       return true;
15850 
15851     return false;
15852   }
15853   default:
15854     return true;
15855   }
15856   return true;
15857 }
15858 
15859 const MCPhysReg *
15860 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15861   // LR is a callee-save register, but we must treat it as clobbered by any call
15862   // site. Hence we include LR in the scratch registers, which are in turn added
15863   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15864   // to CTR, which is used by any indirect call.
15865   static const MCPhysReg ScratchRegs[] = {
15866     PPC::X12, PPC::LR8, PPC::CTR8, 0
15867   };
15868 
15869   return ScratchRegs;
15870 }
15871 
15872 Register PPCTargetLowering::getExceptionPointerRegister(
15873     const Constant *PersonalityFn) const {
15874   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15875 }
15876 
15877 Register PPCTargetLowering::getExceptionSelectorRegister(
15878     const Constant *PersonalityFn) const {
15879   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15880 }
15881 
15882 bool
15883 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15884                      EVT VT , unsigned DefinedValues) const {
15885   if (VT == MVT::v2i64)
15886     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15887 
15888   if (Subtarget.hasVSX())
15889     return true;
15890 
15891   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15892 }
15893 
15894 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15895   if (DisableILPPref || Subtarget.enableMachineScheduler())
15896     return TargetLowering::getSchedulingPreference(N);
15897 
15898   return Sched::ILP;
15899 }
15900 
15901 // Create a fast isel object.
15902 FastISel *
15903 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15904                                   const TargetLibraryInfo *LibInfo) const {
15905   return PPC::createFastISel(FuncInfo, LibInfo);
15906 }
15907 
15908 // 'Inverted' means the FMA opcode after negating one multiplicand.
15909 // For example, (fma -a b c) = (fnmsub a b c)
15910 static unsigned invertFMAOpcode(unsigned Opc) {
15911   switch (Opc) {
15912   default:
15913     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15914   case ISD::FMA:
15915     return PPCISD::FNMSUB;
15916   case PPCISD::FNMSUB:
15917     return ISD::FMA;
15918   }
15919 }
15920 
15921 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15922                                                 bool LegalOps, bool OptForSize,
15923                                                 NegatibleCost &Cost,
15924                                                 unsigned Depth) const {
15925   if (Depth > SelectionDAG::MaxRecursionDepth)
15926     return SDValue();
15927 
15928   unsigned Opc = Op.getOpcode();
15929   EVT VT = Op.getValueType();
15930   SDNodeFlags Flags = Op.getNode()->getFlags();
15931 
15932   switch (Opc) {
15933   case PPCISD::FNMSUB:
15934     if (!Op.hasOneUse() || !isTypeLegal(VT))
15935       break;
15936 
15937     const TargetOptions &Options = getTargetMachine().Options;
15938     SDValue N0 = Op.getOperand(0);
15939     SDValue N1 = Op.getOperand(1);
15940     SDValue N2 = Op.getOperand(2);
15941     SDLoc Loc(Op);
15942 
15943     NegatibleCost N2Cost = NegatibleCost::Expensive;
15944     SDValue NegN2 =
15945         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15946 
15947     if (!NegN2)
15948       return SDValue();
15949 
15950     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15951     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15952     // These transformations may change sign of zeroes. For example,
15953     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15954     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15955       // Try and choose the cheaper one to negate.
15956       NegatibleCost N0Cost = NegatibleCost::Expensive;
15957       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15958                                            N0Cost, Depth + 1);
15959 
15960       NegatibleCost N1Cost = NegatibleCost::Expensive;
15961       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15962                                            N1Cost, Depth + 1);
15963 
15964       if (NegN0 && N0Cost <= N1Cost) {
15965         Cost = std::min(N0Cost, N2Cost);
15966         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15967       } else if (NegN1) {
15968         Cost = std::min(N1Cost, N2Cost);
15969         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15970       }
15971     }
15972 
15973     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15974     if (isOperationLegal(ISD::FMA, VT)) {
15975       Cost = N2Cost;
15976       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15977     }
15978 
15979     break;
15980   }
15981 
15982   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15983                                               Cost, Depth);
15984 }
15985 
15986 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15987 bool PPCTargetLowering::useLoadStackGuardNode() const {
15988   if (!Subtarget.isTargetLinux())
15989     return TargetLowering::useLoadStackGuardNode();
15990   return true;
15991 }
15992 
15993 // Override to disable global variable loading on Linux.
15994 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15995   if (!Subtarget.isTargetLinux())
15996     return TargetLowering::insertSSPDeclarations(M);
15997 }
15998 
15999 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16000                                      bool ForCodeSize) const {
16001   if (!VT.isSimple() || !Subtarget.hasVSX())
16002     return false;
16003 
16004   switch(VT.getSimpleVT().SimpleTy) {
16005   default:
16006     // For FP types that are currently not supported by PPC backend, return
16007     // false. Examples: f16, f80.
16008     return false;
16009   case MVT::f32:
16010   case MVT::f64:
16011     if (Subtarget.hasPrefixInstrs()) {
16012       // With prefixed instructions, we can materialize anything that can be
16013       // represented with a 32-bit immediate, not just positive zero.
16014       APFloat APFloatOfImm = Imm;
16015       return convertToNonDenormSingle(APFloatOfImm);
16016     }
16017     LLVM_FALLTHROUGH;
16018   case MVT::ppcf128:
16019     return Imm.isPosZero();
16020   }
16021 }
16022 
16023 // For vector shift operation op, fold
16024 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16025 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16026                                   SelectionDAG &DAG) {
16027   SDValue N0 = N->getOperand(0);
16028   SDValue N1 = N->getOperand(1);
16029   EVT VT = N0.getValueType();
16030   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16031   unsigned Opcode = N->getOpcode();
16032   unsigned TargetOpcode;
16033 
16034   switch (Opcode) {
16035   default:
16036     llvm_unreachable("Unexpected shift operation");
16037   case ISD::SHL:
16038     TargetOpcode = PPCISD::SHL;
16039     break;
16040   case ISD::SRL:
16041     TargetOpcode = PPCISD::SRL;
16042     break;
16043   case ISD::SRA:
16044     TargetOpcode = PPCISD::SRA;
16045     break;
16046   }
16047 
16048   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16049       N1->getOpcode() == ISD::AND)
16050     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16051       if (Mask->getZExtValue() == OpSizeInBits - 1)
16052         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16053 
16054   return SDValue();
16055 }
16056 
16057 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16058   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16059     return Value;
16060 
16061   SDValue N0 = N->getOperand(0);
16062   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16063   if (!Subtarget.isISA3_0() ||
16064       N0.getOpcode() != ISD::SIGN_EXTEND ||
16065       N0.getOperand(0).getValueType() != MVT::i32 ||
16066       CN1 == nullptr || N->getValueType(0) != MVT::i64)
16067     return SDValue();
16068 
16069   // We can't save an operation here if the value is already extended, and
16070   // the existing shift is easier to combine.
16071   SDValue ExtsSrc = N0.getOperand(0);
16072   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16073       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16074     return SDValue();
16075 
16076   SDLoc DL(N0);
16077   SDValue ShiftBy = SDValue(CN1, 0);
16078   // We want the shift amount to be i32 on the extswli, but the shift could
16079   // have an i64.
16080   if (ShiftBy.getValueType() == MVT::i64)
16081     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16082 
16083   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16084                          ShiftBy);
16085 }
16086 
16087 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16088   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16089     return Value;
16090 
16091   return SDValue();
16092 }
16093 
16094 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16095   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16096     return Value;
16097 
16098   return SDValue();
16099 }
16100 
16101 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16102 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16103 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16104 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16105 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16106                                  const PPCSubtarget &Subtarget) {
16107   if (!Subtarget.isPPC64())
16108     return SDValue();
16109 
16110   SDValue LHS = N->getOperand(0);
16111   SDValue RHS = N->getOperand(1);
16112 
16113   auto isZextOfCompareWithConstant = [](SDValue Op) {
16114     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
16115         Op.getValueType() != MVT::i64)
16116       return false;
16117 
16118     SDValue Cmp = Op.getOperand(0);
16119     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
16120         Cmp.getOperand(0).getValueType() != MVT::i64)
16121       return false;
16122 
16123     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
16124       int64_t NegConstant = 0 - Constant->getSExtValue();
16125       // Due to the limitations of the addi instruction,
16126       // -C is required to be [-32768, 32767].
16127       return isInt<16>(NegConstant);
16128     }
16129 
16130     return false;
16131   };
16132 
16133   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
16134   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
16135 
16136   // If there is a pattern, canonicalize a zext operand to the RHS.
16137   if (LHSHasPattern && !RHSHasPattern)
16138     std::swap(LHS, RHS);
16139   else if (!LHSHasPattern && !RHSHasPattern)
16140     return SDValue();
16141 
16142   SDLoc DL(N);
16143   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
16144   SDValue Cmp = RHS.getOperand(0);
16145   SDValue Z = Cmp.getOperand(0);
16146   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
16147 
16148   assert(Constant && "Constant Should not be a null pointer.");
16149   int64_t NegConstant = 0 - Constant->getSExtValue();
16150 
16151   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
16152   default: break;
16153   case ISD::SETNE: {
16154     //                                 when C == 0
16155     //                             --> addze X, (addic Z, -1).carry
16156     //                            /
16157     // add X, (zext(setne Z, C))--
16158     //                            \    when -32768 <= -C <= 32767 && C != 0
16159     //                             --> addze X, (addic (addi Z, -C), -1).carry
16160     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16161                               DAG.getConstant(NegConstant, DL, MVT::i64));
16162     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16163     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16164                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
16165     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16166                        SDValue(Addc.getNode(), 1));
16167     }
16168   case ISD::SETEQ: {
16169     //                                 when C == 0
16170     //                             --> addze X, (subfic Z, 0).carry
16171     //                            /
16172     // add X, (zext(sete  Z, C))--
16173     //                            \    when -32768 <= -C <= 32767 && C != 0
16174     //                             --> addze X, (subfic (addi Z, -C), 0).carry
16175     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
16176                               DAG.getConstant(NegConstant, DL, MVT::i64));
16177     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
16178     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
16179                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
16180     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
16181                        SDValue(Subc.getNode(), 1));
16182     }
16183   }
16184 
16185   return SDValue();
16186 }
16187 
16188 // Transform
16189 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
16190 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
16191 // In this case both C1 and C2 must be known constants.
16192 // C1+C2 must fit into a 34 bit signed integer.
16193 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
16194                                           const PPCSubtarget &Subtarget) {
16195   if (!Subtarget.isUsingPCRelativeCalls())
16196     return SDValue();
16197 
16198   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
16199   // If we find that node try to cast the Global Address and the Constant.
16200   SDValue LHS = N->getOperand(0);
16201   SDValue RHS = N->getOperand(1);
16202 
16203   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16204     std::swap(LHS, RHS);
16205 
16206   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16207     return SDValue();
16208 
16209   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16210   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16211   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16212 
16213   // Check that both casts succeeded.
16214   if (!GSDN || !ConstNode)
16215     return SDValue();
16216 
16217   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16218   SDLoc DL(GSDN);
16219 
16220   // The signed int offset needs to fit in 34 bits.
16221   if (!isInt<34>(NewOffset))
16222     return SDValue();
16223 
16224   // The new global address is a copy of the old global address except
16225   // that it has the updated Offset.
16226   SDValue GA =
16227       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16228                                  NewOffset, GSDN->getTargetFlags());
16229   SDValue MatPCRel =
16230       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16231   return MatPCRel;
16232 }
16233 
16234 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16235   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16236     return Value;
16237 
16238   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16239     return Value;
16240 
16241   return SDValue();
16242 }
16243 
16244 // Detect TRUNCATE operations on bitcasts of float128 values.
16245 // What we are looking for here is the situtation where we extract a subset
16246 // of bits from a 128 bit float.
16247 // This can be of two forms:
16248 // 1) BITCAST of f128 feeding TRUNCATE
16249 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16250 // The reason this is required is because we do not have a legal i128 type
16251 // and so we want to prevent having to store the f128 and then reload part
16252 // of it.
16253 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16254                                            DAGCombinerInfo &DCI) const {
16255   // If we are using CRBits then try that first.
16256   if (Subtarget.useCRBits()) {
16257     // Check if CRBits did anything and return that if it did.
16258     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16259       return CRTruncValue;
16260   }
16261 
16262   SDLoc dl(N);
16263   SDValue Op0 = N->getOperand(0);
16264 
16265   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16266   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16267     EVT VT = N->getValueType(0);
16268     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16269       return SDValue();
16270     SDValue Sub = Op0.getOperand(0);
16271     if (Sub.getOpcode() == ISD::SUB) {
16272       SDValue SubOp0 = Sub.getOperand(0);
16273       SDValue SubOp1 = Sub.getOperand(1);
16274       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16275           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16276         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16277                                SubOp1.getOperand(0),
16278                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16279       }
16280     }
16281   }
16282 
16283   // Looking for a truncate of i128 to i64.
16284   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16285     return SDValue();
16286 
16287   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16288 
16289   // SRL feeding TRUNCATE.
16290   if (Op0.getOpcode() == ISD::SRL) {
16291     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16292     // The right shift has to be by 64 bits.
16293     if (!ConstNode || ConstNode->getZExtValue() != 64)
16294       return SDValue();
16295 
16296     // Switch the element number to extract.
16297     EltToExtract = EltToExtract ? 0 : 1;
16298     // Update Op0 past the SRL.
16299     Op0 = Op0.getOperand(0);
16300   }
16301 
16302   // BITCAST feeding a TRUNCATE possibly via SRL.
16303   if (Op0.getOpcode() == ISD::BITCAST &&
16304       Op0.getValueType() == MVT::i128 &&
16305       Op0.getOperand(0).getValueType() == MVT::f128) {
16306     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16307     return DCI.DAG.getNode(
16308         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16309         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16310   }
16311   return SDValue();
16312 }
16313 
16314 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16315   SelectionDAG &DAG = DCI.DAG;
16316 
16317   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16318   if (!ConstOpOrElement)
16319     return SDValue();
16320 
16321   // An imul is usually smaller than the alternative sequence for legal type.
16322   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16323       isOperationLegal(ISD::MUL, N->getValueType(0)))
16324     return SDValue();
16325 
16326   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16327     switch (this->Subtarget.getCPUDirective()) {
16328     default:
16329       // TODO: enhance the condition for subtarget before pwr8
16330       return false;
16331     case PPC::DIR_PWR8:
16332       //  type        mul     add    shl
16333       // scalar        4       1      1
16334       // vector        7       2      2
16335       return true;
16336     case PPC::DIR_PWR9:
16337     case PPC::DIR_PWR10:
16338     case PPC::DIR_PWR_FUTURE:
16339       //  type        mul     add    shl
16340       // scalar        5       2      2
16341       // vector        7       2      2
16342 
16343       // The cycle RATIO of related operations are showed as a table above.
16344       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16345       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16346       // are 4, it is always profitable; but for 3 instrs patterns
16347       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16348       // So we should only do it for vector type.
16349       return IsAddOne && IsNeg ? VT.isVector() : true;
16350     }
16351   };
16352 
16353   EVT VT = N->getValueType(0);
16354   SDLoc DL(N);
16355 
16356   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16357   bool IsNeg = MulAmt.isNegative();
16358   APInt MulAmtAbs = MulAmt.abs();
16359 
16360   if ((MulAmtAbs - 1).isPowerOf2()) {
16361     // (mul x, 2^N + 1) => (add (shl x, N), x)
16362     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16363 
16364     if (!IsProfitable(IsNeg, true, VT))
16365       return SDValue();
16366 
16367     SDValue Op0 = N->getOperand(0);
16368     SDValue Op1 =
16369         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16370                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16371     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16372 
16373     if (!IsNeg)
16374       return Res;
16375 
16376     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16377   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16378     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16379     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16380 
16381     if (!IsProfitable(IsNeg, false, VT))
16382       return SDValue();
16383 
16384     SDValue Op0 = N->getOperand(0);
16385     SDValue Op1 =
16386         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16387                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16388 
16389     if (!IsNeg)
16390       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16391     else
16392       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16393 
16394   } else {
16395     return SDValue();
16396   }
16397 }
16398 
16399 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16400 // in combiner since we need to check SD flags and other subtarget features.
16401 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16402                                           DAGCombinerInfo &DCI) const {
16403   SDValue N0 = N->getOperand(0);
16404   SDValue N1 = N->getOperand(1);
16405   SDValue N2 = N->getOperand(2);
16406   SDNodeFlags Flags = N->getFlags();
16407   EVT VT = N->getValueType(0);
16408   SelectionDAG &DAG = DCI.DAG;
16409   const TargetOptions &Options = getTargetMachine().Options;
16410   unsigned Opc = N->getOpcode();
16411   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16412   bool LegalOps = !DCI.isBeforeLegalizeOps();
16413   SDLoc Loc(N);
16414 
16415   if (!isOperationLegal(ISD::FMA, VT))
16416     return SDValue();
16417 
16418   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16419   // since (fnmsub a b c)=-0 while c-ab=+0.
16420   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16421     return SDValue();
16422 
16423   // (fma (fneg a) b c) => (fnmsub a b c)
16424   // (fnmsub (fneg a) b c) => (fma a b c)
16425   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16426     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16427 
16428   // (fma a (fneg b) c) => (fnmsub a b c)
16429   // (fnmsub a (fneg b) c) => (fma a b c)
16430   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16431     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16432 
16433   return SDValue();
16434 }
16435 
16436 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16437   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16438   if (!Subtarget.is64BitELFABI())
16439     return false;
16440 
16441   // If not a tail call then no need to proceed.
16442   if (!CI->isTailCall())
16443     return false;
16444 
16445   // If sibling calls have been disabled and tail-calls aren't guaranteed
16446   // there is no reason to duplicate.
16447   auto &TM = getTargetMachine();
16448   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16449     return false;
16450 
16451   // Can't tail call a function called indirectly, or if it has variadic args.
16452   const Function *Callee = CI->getCalledFunction();
16453   if (!Callee || Callee->isVarArg())
16454     return false;
16455 
16456   // Make sure the callee and caller calling conventions are eligible for tco.
16457   const Function *Caller = CI->getParent()->getParent();
16458   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16459                                            CI->getCallingConv()))
16460       return false;
16461 
16462   // If the function is local then we have a good chance at tail-calling it
16463   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16464 }
16465 
16466 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16467   if (!Subtarget.hasVSX())
16468     return false;
16469   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16470     return true;
16471   return VT == MVT::f32 || VT == MVT::f64 ||
16472     VT == MVT::v4f32 || VT == MVT::v2f64;
16473 }
16474 
16475 bool PPCTargetLowering::
16476 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16477   const Value *Mask = AndI.getOperand(1);
16478   // If the mask is suitable for andi. or andis. we should sink the and.
16479   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16480     // Can't handle constants wider than 64-bits.
16481     if (CI->getBitWidth() > 64)
16482       return false;
16483     int64_t ConstVal = CI->getZExtValue();
16484     return isUInt<16>(ConstVal) ||
16485       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16486   }
16487 
16488   // For non-constant masks, we can always use the record-form and.
16489   return true;
16490 }
16491 
16492 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16493 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16494 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16495 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16496 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16497 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16498   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16499   assert(Subtarget.hasP9Altivec() &&
16500          "Only combine this when P9 altivec supported!");
16501   EVT VT = N->getValueType(0);
16502   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16503     return SDValue();
16504 
16505   SelectionDAG &DAG = DCI.DAG;
16506   SDLoc dl(N);
16507   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16508     // Even for signed integers, if it's known to be positive (as signed
16509     // integer) due to zero-extended inputs.
16510     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16511     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16512     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16513          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16514         (SubOpcd1 == ISD::ZERO_EXTEND ||
16515          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16516       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16517                          N->getOperand(0)->getOperand(0),
16518                          N->getOperand(0)->getOperand(1),
16519                          DAG.getTargetConstant(0, dl, MVT::i32));
16520     }
16521 
16522     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16523     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16524         N->getOperand(0).hasOneUse()) {
16525       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16526                          N->getOperand(0)->getOperand(0),
16527                          N->getOperand(0)->getOperand(1),
16528                          DAG.getTargetConstant(1, dl, MVT::i32));
16529     }
16530   }
16531 
16532   return SDValue();
16533 }
16534 
16535 // For type v4i32/v8ii16/v16i8, transform
16536 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16537 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16538 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16539 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16540 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16541                                           DAGCombinerInfo &DCI) const {
16542   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16543   assert(Subtarget.hasP9Altivec() &&
16544          "Only combine this when P9 altivec supported!");
16545 
16546   SelectionDAG &DAG = DCI.DAG;
16547   SDLoc dl(N);
16548   SDValue Cond = N->getOperand(0);
16549   SDValue TrueOpnd = N->getOperand(1);
16550   SDValue FalseOpnd = N->getOperand(2);
16551   EVT VT = N->getOperand(1).getValueType();
16552 
16553   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16554       FalseOpnd.getOpcode() != ISD::SUB)
16555     return SDValue();
16556 
16557   // ABSD only available for type v4i32/v8i16/v16i8
16558   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16559     return SDValue();
16560 
16561   // At least to save one more dependent computation
16562   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16563     return SDValue();
16564 
16565   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16566 
16567   // Can only handle unsigned comparison here
16568   switch (CC) {
16569   default:
16570     return SDValue();
16571   case ISD::SETUGT:
16572   case ISD::SETUGE:
16573     break;
16574   case ISD::SETULT:
16575   case ISD::SETULE:
16576     std::swap(TrueOpnd, FalseOpnd);
16577     break;
16578   }
16579 
16580   SDValue CmpOpnd1 = Cond.getOperand(0);
16581   SDValue CmpOpnd2 = Cond.getOperand(1);
16582 
16583   // SETCC CmpOpnd1 CmpOpnd2 cond
16584   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16585   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16586   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16587       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16588       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16589       FalseOpnd.getOperand(1) == CmpOpnd1) {
16590     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16591                        CmpOpnd1, CmpOpnd2,
16592                        DAG.getTargetConstant(0, dl, MVT::i32));
16593   }
16594 
16595   return SDValue();
16596 }
16597