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> EnableQuadwordAtomics(
125     "ppc-quadword-atomics",
126     cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127     cl::Hidden);
128 
129 static cl::opt<bool>
130     DisablePerfectShuffle("ppc-disable-perfect-shuffle",
131                           cl::desc("disable vector permute decomposition"),
132                           cl::init(false), cl::Hidden);
133 
134 STATISTIC(NumTailCalls, "Number of tail calls");
135 STATISTIC(NumSiblingCalls, "Number of sibling calls");
136 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
137 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
138 
139 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
140 
141 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
142 
143 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
144 
145 // FIXME: Remove this once the bug has been fixed!
146 extern cl::opt<bool> ANDIGlueBug;
147 
148 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
149                                      const PPCSubtarget &STI)
150     : TargetLowering(TM), Subtarget(STI) {
151   // Initialize map that relates the PPC addressing modes to the computed flags
152   // of a load/store instruction. The map is used to determine the optimal
153   // addressing mode when selecting load and stores.
154   initializeAddrModeMap();
155   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
156   // arguments are at least 4/8 bytes aligned.
157   bool isPPC64 = Subtarget.isPPC64();
158   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
159 
160   // Set up the register classes.
161   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
162   if (!useSoftFloat()) {
163     if (hasSPE()) {
164       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
165       // EFPU2 APU only supports f32
166       if (!Subtarget.hasEFPU2())
167         addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
168     } else {
169       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
170       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
171     }
172   }
173 
174   // Match BITREVERSE to customized fast code sequence in the td file.
175   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
176   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
177 
178   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
179   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
180 
181   // Custom lower inline assembly to check for special registers.
182   setOperationAction(ISD::INLINEASM, MVT::Other, Custom);
183   setOperationAction(ISD::INLINEASM_BR, MVT::Other, Custom);
184 
185   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
186   for (MVT VT : MVT::integer_valuetypes()) {
187     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
189   }
190 
191   if (Subtarget.isISA3_0()) {
192     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
193     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
194     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
195     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
196   } else {
197     // No extending loads from f16 or HW conversions back and forth.
198     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
199     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
200     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
201     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
202     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
203     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
204     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
205     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
206   }
207 
208   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
209 
210   // PowerPC has pre-inc load and store's.
211   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
212   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
213   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
214   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
215   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
216   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
217   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
218   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
219   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
220   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
221   if (!Subtarget.hasSPE()) {
222     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
223     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
224     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
225     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
226   }
227 
228   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
229   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
230   for (MVT VT : ScalarIntVTs) {
231     setOperationAction(ISD::ADDC, VT, Legal);
232     setOperationAction(ISD::ADDE, VT, Legal);
233     setOperationAction(ISD::SUBC, VT, Legal);
234     setOperationAction(ISD::SUBE, VT, Legal);
235   }
236 
237   if (Subtarget.useCRBits()) {
238     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
239 
240     if (isPPC64 || Subtarget.hasFPCVT()) {
241       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Promote);
242       AddPromotedToType(ISD::STRICT_SINT_TO_FP, MVT::i1,
243                         isPPC64 ? MVT::i64 : MVT::i32);
244       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Promote);
245       AddPromotedToType(ISD::STRICT_UINT_TO_FP, MVT::i1,
246                         isPPC64 ? MVT::i64 : MVT::i32);
247 
248       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
249       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
250                          isPPC64 ? MVT::i64 : MVT::i32);
251       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
252       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
253                         isPPC64 ? MVT::i64 : MVT::i32);
254 
255       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i1, Promote);
256       AddPromotedToType(ISD::STRICT_FP_TO_SINT, MVT::i1,
257                         isPPC64 ? MVT::i64 : MVT::i32);
258       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i1, Promote);
259       AddPromotedToType(ISD::STRICT_FP_TO_UINT, MVT::i1,
260                         isPPC64 ? MVT::i64 : MVT::i32);
261 
262       setOperationAction(ISD::FP_TO_SINT, MVT::i1, Promote);
263       AddPromotedToType(ISD::FP_TO_SINT, MVT::i1,
264                         isPPC64 ? MVT::i64 : MVT::i32);
265       setOperationAction(ISD::FP_TO_UINT, MVT::i1, Promote);
266       AddPromotedToType(ISD::FP_TO_UINT, MVT::i1,
267                         isPPC64 ? MVT::i64 : MVT::i32);
268     } else {
269       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i1, Custom);
270       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i1, Custom);
271       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
272       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
273     }
274 
275     // PowerPC does not support direct load/store of condition registers.
276     setOperationAction(ISD::LOAD, MVT::i1, Custom);
277     setOperationAction(ISD::STORE, MVT::i1, Custom);
278 
279     // FIXME: Remove this once the ANDI glue bug is fixed:
280     if (ANDIGlueBug)
281       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
282 
283     for (MVT VT : MVT::integer_valuetypes()) {
284       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
285       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
286       setTruncStoreAction(VT, MVT::i1, Expand);
287     }
288 
289     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
290   }
291 
292   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
293   // PPC (the libcall is not available).
294   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
295   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
296   setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::ppcf128, Custom);
297   setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::ppcf128, Custom);
298 
299   // We do not currently implement these libm ops for PowerPC.
300   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
301   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
302   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
303   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
304   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
305   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
306 
307   // PowerPC has no SREM/UREM instructions unless we are on P9
308   // On P9 we may use a hardware instruction to compute the remainder.
309   // When the result of both the remainder and the division is required it is
310   // more efficient to compute the remainder from the result of the division
311   // rather than use the remainder instruction. The instructions are legalized
312   // directly because the DivRemPairsPass performs the transformation at the IR
313   // level.
314   if (Subtarget.isISA3_0()) {
315     setOperationAction(ISD::SREM, MVT::i32, Legal);
316     setOperationAction(ISD::UREM, MVT::i32, Legal);
317     setOperationAction(ISD::SREM, MVT::i64, Legal);
318     setOperationAction(ISD::UREM, MVT::i64, Legal);
319   } else {
320     setOperationAction(ISD::SREM, MVT::i32, Expand);
321     setOperationAction(ISD::UREM, MVT::i32, Expand);
322     setOperationAction(ISD::SREM, MVT::i64, Expand);
323     setOperationAction(ISD::UREM, MVT::i64, Expand);
324   }
325 
326   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
327   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
328   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
329   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
330   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
331   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
332   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
333   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
334   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
335 
336   // Handle constrained floating-point operations of scalar.
337   // TODO: Handle SPE specific operation.
338   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
339   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
340   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
341   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
342   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
343 
344   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
345   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
346   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
347   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
348 
349   if (!Subtarget.hasSPE()) {
350     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
352   }
353 
354   if (Subtarget.hasVSX()) {
355     setOperationAction(ISD::STRICT_FRINT, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FRINT, MVT::f64, Legal);
357   }
358 
359   if (Subtarget.hasFSQRT()) {
360     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
361     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
362   }
363 
364   if (Subtarget.hasFPRND()) {
365     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
366     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
367     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
368     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
369 
370     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
371     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
372     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
373     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
374   }
375 
376   // We don't support sin/cos/sqrt/fmod/pow
377   setOperationAction(ISD::FSIN , MVT::f64, Expand);
378   setOperationAction(ISD::FCOS , MVT::f64, Expand);
379   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
380   setOperationAction(ISD::FREM , MVT::f64, Expand);
381   setOperationAction(ISD::FPOW , MVT::f64, Expand);
382   setOperationAction(ISD::FSIN , MVT::f32, Expand);
383   setOperationAction(ISD::FCOS , MVT::f32, Expand);
384   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
385   setOperationAction(ISD::FREM , MVT::f32, Expand);
386   setOperationAction(ISD::FPOW , MVT::f32, Expand);
387 
388   // MASS transformation for LLVM intrinsics with replicating fast-math flag
389   // to be consistent to PPCGenScalarMASSEntries pass
390   if (TM.getOptLevel() == CodeGenOpt::Aggressive &&
391       TM.Options.PPCGenScalarMASSEntries) {
392     setOperationAction(ISD::FSIN , MVT::f64, Custom);
393     setOperationAction(ISD::FCOS , MVT::f64, Custom);
394     setOperationAction(ISD::FPOW , MVT::f64, Custom);
395     setOperationAction(ISD::FLOG, MVT::f64, Custom);
396     setOperationAction(ISD::FLOG10, MVT::f64, Custom);
397     setOperationAction(ISD::FEXP, MVT::f64, Custom);
398     setOperationAction(ISD::FSIN , MVT::f32, Custom);
399     setOperationAction(ISD::FCOS , MVT::f32, Custom);
400     setOperationAction(ISD::FPOW , MVT::f32, Custom);
401     setOperationAction(ISD::FLOG, MVT::f32, Custom);
402     setOperationAction(ISD::FLOG10, MVT::f32, Custom);
403     setOperationAction(ISD::FEXP, MVT::f32, Custom);
404   }
405 
406   if (Subtarget.hasSPE()) {
407     setOperationAction(ISD::FMA  , MVT::f64, Expand);
408     setOperationAction(ISD::FMA  , MVT::f32, Expand);
409   } else {
410     setOperationAction(ISD::FMA  , MVT::f64, Legal);
411     setOperationAction(ISD::FMA  , MVT::f32, Legal);
412   }
413 
414   if (Subtarget.hasSPE())
415     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
416 
417   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
418 
419   // If we're enabling GP optimizations, use hardware square root
420   if (!Subtarget.hasFSQRT() &&
421       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
422         Subtarget.hasFRE()))
423     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
424 
425   if (!Subtarget.hasFSQRT() &&
426       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
427         Subtarget.hasFRES()))
428     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
429 
430   if (Subtarget.hasFCPSGN()) {
431     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
432     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
433   } else {
434     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
435     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
436   }
437 
438   if (Subtarget.hasFPRND()) {
439     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
440     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
441     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
442     setOperationAction(ISD::FROUND, MVT::f64, Legal);
443 
444     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
445     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
446     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
447     setOperationAction(ISD::FROUND, MVT::f32, Legal);
448   }
449 
450   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
451   // to speed up scalar BSWAP64.
452   // CTPOP or CTTZ were introduced in P8/P9 respectively
453   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
454   if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
455     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
456   else
457     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
458   if (Subtarget.isISA3_0()) {
459     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
460     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
461   } else {
462     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
463     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
464   }
465 
466   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
467     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
468     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
469   } else {
470     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
471     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
472   }
473 
474   // PowerPC does not have ROTR
475   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
476   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
477 
478   if (!Subtarget.useCRBits()) {
479     // PowerPC does not have Select
480     setOperationAction(ISD::SELECT, MVT::i32, Expand);
481     setOperationAction(ISD::SELECT, MVT::i64, Expand);
482     setOperationAction(ISD::SELECT, MVT::f32, Expand);
483     setOperationAction(ISD::SELECT, MVT::f64, Expand);
484   }
485 
486   // PowerPC wants to turn select_cc of FP into fsel when possible.
487   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
488   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
489 
490   // PowerPC wants to optimize integer setcc a bit
491   if (!Subtarget.useCRBits())
492     setOperationAction(ISD::SETCC, MVT::i32, Custom);
493 
494   if (Subtarget.hasFPU()) {
495     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
496     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
497     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
498 
499     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
500     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
501     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
502   }
503 
504   // PowerPC does not have BRCOND which requires SetCC
505   if (!Subtarget.useCRBits())
506     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
507 
508   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
509 
510   if (Subtarget.hasSPE()) {
511     // SPE has built-in conversions
512     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
513     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
514     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
515     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
516     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
517     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
518 
519     // SPE supports signaling compare of f32/f64.
520     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
521     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
522   } else {
523     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
524     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
525     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
526 
527     // PowerPC does not have [U|S]INT_TO_FP
528     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Expand);
529     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Expand);
530     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
531     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
532   }
533 
534   if (Subtarget.hasDirectMove() && isPPC64) {
535     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
536     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
537     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
538     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
539     if (TM.Options.UnsafeFPMath) {
540       setOperationAction(ISD::LRINT, MVT::f64, Legal);
541       setOperationAction(ISD::LRINT, MVT::f32, Legal);
542       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
543       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
544       setOperationAction(ISD::LROUND, MVT::f64, Legal);
545       setOperationAction(ISD::LROUND, MVT::f32, Legal);
546       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
547       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
548     }
549   } else {
550     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
551     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
552     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
553     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
554   }
555 
556   // We cannot sextinreg(i1).  Expand to shifts.
557   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
558 
559   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
560   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
561   // support continuation, user-level threading, and etc.. As a result, no
562   // other SjLj exception interfaces are implemented and please don't build
563   // your own exception handling based on them.
564   // LLVM/Clang supports zero-cost DWARF exception handling.
565   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
566   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
567 
568   // We want to legalize GlobalAddress and ConstantPool nodes into the
569   // appropriate instructions to materialize the address.
570   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
571   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
572   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
573   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
574   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
575   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
576   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
578   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
579   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
580 
581   // TRAP is legal.
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583 
584   // TRAMPOLINE is custom lowered.
585   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
586   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
587 
588   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
589   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
590 
591   if (Subtarget.is64BitELFABI()) {
592     // VAARG always uses double-word chunks, so promote anything smaller.
593     setOperationAction(ISD::VAARG, MVT::i1, Promote);
594     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
595     setOperationAction(ISD::VAARG, MVT::i8, Promote);
596     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
597     setOperationAction(ISD::VAARG, MVT::i16, Promote);
598     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
599     setOperationAction(ISD::VAARG, MVT::i32, Promote);
600     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
601     setOperationAction(ISD::VAARG, MVT::Other, Expand);
602   } else if (Subtarget.is32BitELFABI()) {
603     // VAARG is custom lowered with the 32-bit SVR4 ABI.
604     setOperationAction(ISD::VAARG, MVT::Other, Custom);
605     setOperationAction(ISD::VAARG, MVT::i64, Custom);
606   } else
607     setOperationAction(ISD::VAARG, MVT::Other, Expand);
608 
609   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
610   if (Subtarget.is32BitELFABI())
611     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
612   else
613     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
614 
615   // Use the default implementation.
616   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
617   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
618   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
619   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
620   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
621   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
622   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
623   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
624   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
625 
626   // We want to custom lower some of our intrinsics.
627   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
628   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f64, Custom);
629   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::ppcf128, Custom);
630   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
631   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f64, Custom);
632 
633   // To handle counter-based loop conditions.
634   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
635 
636   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
637   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
638   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
639   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
640 
641   // Comparisons that require checking two conditions.
642   if (Subtarget.hasSPE()) {
643     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
644     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
645     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
646     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
647   }
648   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
649   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
650   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
651   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
652   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
653   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
654   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
655   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
656   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
657   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
658   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
659   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
660 
661   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
662   setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
663 
664   if (Subtarget.has64BitSupport()) {
665     // They also have instructions for converting between i64 and fp.
666     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
667     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
668     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
669     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Expand);
670     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
671     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
672     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
673     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
674     // This is just the low 32 bits of a (signed) fp->i64 conversion.
675     // We cannot do this with Promote because i64 is not a legal type.
676     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
677     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
678 
679     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
680       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
681       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
682     }
683   } else {
684     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
685     if (Subtarget.hasSPE()) {
686       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
687       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
688     } else {
689       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
690       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
691     }
692   }
693 
694   // With the instructions enabled under FPCVT, we can do everything.
695   if (Subtarget.hasFPCVT()) {
696     if (Subtarget.has64BitSupport()) {
697       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
698       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
699       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
700       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
701       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
702       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
703       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
704       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
705     }
706 
707     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
708     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
709     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
710     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
711     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
712     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
713     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
714     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
715   }
716 
717   if (Subtarget.use64BitRegs()) {
718     // 64-bit PowerPC implementations can support i64 types directly
719     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
720     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
721     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
722     // 64-bit PowerPC wants to expand i128 shifts itself.
723     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
724     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
725     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
726   } else {
727     // 32-bit PowerPC wants to expand i64 shifts itself.
728     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
729     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
730     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
731   }
732 
733   // PowerPC has better expansions for funnel shifts than the generic
734   // TargetLowering::expandFunnelShift.
735   if (Subtarget.has64BitSupport()) {
736     setOperationAction(ISD::FSHL, MVT::i64, Custom);
737     setOperationAction(ISD::FSHR, MVT::i64, Custom);
738   }
739   setOperationAction(ISD::FSHL, MVT::i32, Custom);
740   setOperationAction(ISD::FSHR, MVT::i32, Custom);
741 
742   if (Subtarget.hasVSX()) {
743     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
744     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
745     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
746     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
747   }
748 
749   if (Subtarget.hasAltivec()) {
750     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
751       setOperationAction(ISD::SADDSAT, VT, Legal);
752       setOperationAction(ISD::SSUBSAT, VT, Legal);
753       setOperationAction(ISD::UADDSAT, VT, Legal);
754       setOperationAction(ISD::USUBSAT, VT, Legal);
755     }
756     // First set operation action for all vector types to expand. Then we
757     // will selectively turn on ones that can be effectively codegen'd.
758     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
759       // add/sub are legal for all supported vector VT's.
760       setOperationAction(ISD::ADD, VT, Legal);
761       setOperationAction(ISD::SUB, VT, Legal);
762 
763       // For v2i64, these are only valid with P8Vector. This is corrected after
764       // the loop.
765       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
766         setOperationAction(ISD::SMAX, VT, Legal);
767         setOperationAction(ISD::SMIN, VT, Legal);
768         setOperationAction(ISD::UMAX, VT, Legal);
769         setOperationAction(ISD::UMIN, VT, Legal);
770       }
771       else {
772         setOperationAction(ISD::SMAX, VT, Expand);
773         setOperationAction(ISD::SMIN, VT, Expand);
774         setOperationAction(ISD::UMAX, VT, Expand);
775         setOperationAction(ISD::UMIN, VT, Expand);
776       }
777 
778       if (Subtarget.hasVSX()) {
779         setOperationAction(ISD::FMAXNUM, VT, Legal);
780         setOperationAction(ISD::FMINNUM, VT, Legal);
781       }
782 
783       // Vector instructions introduced in P8
784       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
785         setOperationAction(ISD::CTPOP, VT, Legal);
786         setOperationAction(ISD::CTLZ, VT, Legal);
787       }
788       else {
789         setOperationAction(ISD::CTPOP, VT, Expand);
790         setOperationAction(ISD::CTLZ, VT, Expand);
791       }
792 
793       // Vector instructions introduced in P9
794       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
795         setOperationAction(ISD::CTTZ, VT, Legal);
796       else
797         setOperationAction(ISD::CTTZ, VT, Expand);
798 
799       // We promote all shuffles to v16i8.
800       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
801       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
802 
803       // We promote all non-typed operations to v4i32.
804       setOperationAction(ISD::AND   , VT, Promote);
805       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
806       setOperationAction(ISD::OR    , VT, Promote);
807       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
808       setOperationAction(ISD::XOR   , VT, Promote);
809       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
810       setOperationAction(ISD::LOAD  , VT, Promote);
811       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
812       setOperationAction(ISD::SELECT, VT, Promote);
813       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
814       setOperationAction(ISD::VSELECT, VT, Legal);
815       setOperationAction(ISD::SELECT_CC, VT, Promote);
816       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
817       setOperationAction(ISD::STORE, VT, Promote);
818       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
819 
820       // No other operations are legal.
821       setOperationAction(ISD::MUL , VT, Expand);
822       setOperationAction(ISD::SDIV, VT, Expand);
823       setOperationAction(ISD::SREM, VT, Expand);
824       setOperationAction(ISD::UDIV, VT, Expand);
825       setOperationAction(ISD::UREM, VT, Expand);
826       setOperationAction(ISD::FDIV, VT, Expand);
827       setOperationAction(ISD::FREM, VT, Expand);
828       setOperationAction(ISD::FNEG, VT, Expand);
829       setOperationAction(ISD::FSQRT, VT, Expand);
830       setOperationAction(ISD::FLOG, VT, Expand);
831       setOperationAction(ISD::FLOG10, VT, Expand);
832       setOperationAction(ISD::FLOG2, VT, Expand);
833       setOperationAction(ISD::FEXP, VT, Expand);
834       setOperationAction(ISD::FEXP2, VT, Expand);
835       setOperationAction(ISD::FSIN, VT, Expand);
836       setOperationAction(ISD::FCOS, VT, Expand);
837       setOperationAction(ISD::FABS, VT, Expand);
838       setOperationAction(ISD::FFLOOR, VT, Expand);
839       setOperationAction(ISD::FCEIL,  VT, Expand);
840       setOperationAction(ISD::FTRUNC, VT, Expand);
841       setOperationAction(ISD::FRINT,  VT, Expand);
842       setOperationAction(ISD::FNEARBYINT, VT, Expand);
843       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
844       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
845       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
846       setOperationAction(ISD::MULHU, VT, Expand);
847       setOperationAction(ISD::MULHS, VT, Expand);
848       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
849       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
850       setOperationAction(ISD::UDIVREM, VT, Expand);
851       setOperationAction(ISD::SDIVREM, VT, Expand);
852       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
853       setOperationAction(ISD::FPOW, VT, Expand);
854       setOperationAction(ISD::BSWAP, VT, Expand);
855       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
856       setOperationAction(ISD::ROTL, VT, Expand);
857       setOperationAction(ISD::ROTR, VT, Expand);
858 
859       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
860         setTruncStoreAction(VT, InnerVT, Expand);
861         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
862         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
863         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
864       }
865     }
866     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
867     if (!Subtarget.hasP8Vector()) {
868       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
869       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
870       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
871       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
872     }
873 
874     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
875     // with merges, splats, etc.
876     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
877 
878     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
879     // are cheap, so handle them before they get expanded to scalar.
880     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
881     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
882     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
883     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
884     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
885 
886     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
887     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
888     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
889     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
890     setOperationAction(ISD::SELECT, MVT::v4i32,
891                        Subtarget.useCRBits() ? Legal : Expand);
892     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
893     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v4i32, Legal);
894     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v4i32, Legal);
895     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i32, Legal);
896     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i32, Legal);
897     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
898     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
899     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
900     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
901     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
902     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
903     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
904     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
905 
906     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
907     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
908     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
909     if (Subtarget.hasAltivec())
910       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
911         setOperationAction(ISD::ROTL, VT, Legal);
912     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
913     if (Subtarget.hasP8Altivec())
914       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
915 
916     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
917     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
918     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
919     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
920 
921     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
922     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
923 
924     if (Subtarget.hasVSX()) {
925       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
926       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
927       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
928     }
929 
930     if (Subtarget.hasP8Altivec())
931       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
932     else
933       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
934 
935     if (Subtarget.isISA3_1()) {
936       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
937       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
938       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
939       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
940       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
941       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
942       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
943       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
944       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
945       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
946       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
947       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
948       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
949       setOperationAction(ISD::UREM, MVT::v1i128, Legal);
950       setOperationAction(ISD::SREM, MVT::v1i128, Legal);
951       setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
952       setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
953       setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
954     }
955 
956     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
957     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
958 
959     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
960     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
961 
962     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
963     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
964     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
965     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
966 
967     // Altivec does not contain unordered floating-point compare instructions
968     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
969     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
970     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
971     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
972 
973     if (Subtarget.hasVSX()) {
974       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
975       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
976       if (Subtarget.hasP8Vector()) {
977         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
978         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
979       }
980       if (Subtarget.hasDirectMove() && isPPC64) {
981         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
982         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
983         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
984         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
985         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
986         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
987         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
988         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
989       }
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
991 
992       // The nearbyint variants are not allowed to raise the inexact exception
993       // so we can only code-gen them with unsafe math.
994       if (TM.Options.UnsafeFPMath) {
995         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
996         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
997       }
998 
999       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1000       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1001       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1002       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1003       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1004       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1005       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1006       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1007 
1008       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1009       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1010       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1011       setOperationAction(ISD::FROUND, MVT::f32, Legal);
1012       setOperationAction(ISD::FRINT, MVT::f32, Legal);
1013 
1014       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1015       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1016 
1017       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1018       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1019 
1020       // Share the Altivec comparison restrictions.
1021       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1022       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1023       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
1024       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1025 
1026       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1027       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1028 
1029       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
1030 
1031       if (Subtarget.hasP8Vector())
1032         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1033 
1034       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1035 
1036       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1037       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1038       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1039 
1040       if (Subtarget.hasP8Altivec()) {
1041         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1042         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1043         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1044 
1045         // 128 bit shifts can be accomplished via 3 instructions for SHL and
1046         // SRL, but not for SRA because of the instructions available:
1047         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1048         // doing
1049         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1050         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1051         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1052 
1053         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1054       }
1055       else {
1056         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1057         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1058         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1059 
1060         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1061 
1062         // VSX v2i64 only supports non-arithmetic operations.
1063         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1064         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1065       }
1066 
1067       if (Subtarget.isISA3_1())
1068         setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1069       else
1070         setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1071 
1072       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1073       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1074       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
1075       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1076 
1077       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
1078 
1079       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i64, Legal);
1080       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i64, Legal);
1081       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::v2i64, Legal);
1082       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::v2i64, Legal);
1083       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
1084       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
1085       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
1086       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
1087 
1088       // Custom handling for partial vectors of integers converted to
1089       // floating point. We already have optimal handling for v2i32 through
1090       // the DAG combine, so those aren't necessary.
1091       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i8, Custom);
1092       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i8, Custom);
1093       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v2i16, Custom);
1094       setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::v4i16, Custom);
1095       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i8, Custom);
1096       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i8, Custom);
1097       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v2i16, Custom);
1098       setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::v4i16, Custom);
1099       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
1100       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1101       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
1102       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1103       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
1104       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1105       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1106       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1107 
1108       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1109       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1110       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1111       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1112       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1113       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1114 
1115       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1116       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1117 
1118       // Handle constrained floating-point operations of vector.
1119       // The predictor is `hasVSX` because altivec instruction has
1120       // no exception but VSX vector instruction has.
1121       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1122       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1123       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1124       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1125       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1126       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1127       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1128       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1129       setOperationAction(ISD::STRICT_FRINT, MVT::v4f32, Legal);
1130       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1131       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1132       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1133       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1134 
1135       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1136       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1137       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1138       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1139       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1140       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1141       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1142       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1143       setOperationAction(ISD::STRICT_FRINT, MVT::v2f64, Legal);
1144       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1145       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1146       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1147       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1148 
1149       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1150       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1151 
1152       for (MVT FPT : MVT::fp_valuetypes())
1153         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1154 
1155       // Expand the SELECT to SELECT_CC
1156       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1157 
1158       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1159       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1160 
1161       // No implementation for these ops for PowerPC.
1162       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1163       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1164       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1165       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1166       setOperationAction(ISD::FREM, MVT::f128, Expand);
1167     }
1168 
1169     if (Subtarget.hasP8Altivec()) {
1170       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1171       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1172     }
1173 
1174     if (Subtarget.hasP9Vector()) {
1175       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1176       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1177 
1178       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1179       // SRL, but not for SRA because of the instructions available:
1180       // VS{RL} and VS{RL}O.
1181       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1182       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1183       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1184 
1185       setOperationAction(ISD::FADD, MVT::f128, Legal);
1186       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1187       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1188       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1189       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1190 
1191       setOperationAction(ISD::FMA, MVT::f128, Legal);
1192       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1193       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1194       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1195       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1196       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1197       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1198 
1199       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1200       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1201       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1202       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1203       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1204       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1205 
1206       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1207       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1208       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1209 
1210       // Handle constrained floating-point operations of fp128
1211       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1212       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1213       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1214       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1215       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1216       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1217       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1218       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1219       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1220       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1221       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1222       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1223       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1224       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1225       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1226       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1227       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1228       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1229       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1230       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1231     } else if (Subtarget.hasVSX()) {
1232       setOperationAction(ISD::LOAD, MVT::f128, Promote);
1233       setOperationAction(ISD::STORE, MVT::f128, Promote);
1234 
1235       AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1236       AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1237 
1238       // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1239       // fp_to_uint and int_to_fp.
1240       setOperationAction(ISD::FADD, MVT::f128, LibCall);
1241       setOperationAction(ISD::FSUB, MVT::f128, LibCall);
1242 
1243       setOperationAction(ISD::FMUL, MVT::f128, Expand);
1244       setOperationAction(ISD::FDIV, MVT::f128, Expand);
1245       setOperationAction(ISD::FNEG, MVT::f128, Expand);
1246       setOperationAction(ISD::FABS, MVT::f128, Expand);
1247       setOperationAction(ISD::FSQRT, MVT::f128, Expand);
1248       setOperationAction(ISD::FMA, MVT::f128, Expand);
1249       setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
1250 
1251       // Expand the fp_extend if the target type is fp128.
1252       setOperationAction(ISD::FP_EXTEND, MVT::f128, Expand);
1253       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Expand);
1254 
1255       // Expand the fp_round if the source type is fp128.
1256       for (MVT VT : {MVT::f32, MVT::f64}) {
1257         setOperationAction(ISD::FP_ROUND, VT, Custom);
1258         setOperationAction(ISD::STRICT_FP_ROUND, VT, Custom);
1259       }
1260 
1261       setOperationAction(ISD::SETCC, MVT::f128, Custom);
1262       setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
1263       setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
1264       setOperationAction(ISD::BR_CC, MVT::f128, Expand);
1265 
1266       // Lower following f128 select_cc pattern:
1267       // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1268       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1269 
1270       // We need to handle f128 SELECT_CC with integer result type.
1271       setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1272       setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1273     }
1274 
1275     if (Subtarget.hasP9Altivec()) {
1276       if (Subtarget.isISA3_1()) {
1277         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
1278         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Legal);
1279         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Legal);
1280         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
1281       } else {
1282         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1283         setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1284       }
1285       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1286       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1287       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1288       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1289       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1290       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1291       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1292     }
1293 
1294     if (Subtarget.hasP10Vector()) {
1295       setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
1296     }
1297   }
1298 
1299   if (Subtarget.pairedVectorMemops()) {
1300     addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1301     setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1302     setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1303   }
1304   if (Subtarget.hasMMA()) {
1305     addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1306     setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1307     setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1308     setOperationAction(ISD::BUILD_VECTOR, MVT::v512i1, Custom);
1309   }
1310 
1311   if (Subtarget.has64BitSupport())
1312     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1313 
1314   if (Subtarget.isISA3_1())
1315     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1316 
1317   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1318 
1319   if (!isPPC64) {
1320     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1321     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1322   }
1323 
1324   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1325     setMaxAtomicSizeInBitsSupported(128);
1326     setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
1327     setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
1328     setOperationAction(ISD::INTRINSIC_VOID, MVT::i128, Custom);
1329   }
1330 
1331   setBooleanContents(ZeroOrOneBooleanContent);
1332 
1333   if (Subtarget.hasAltivec()) {
1334     // Altivec instructions set fields to all zeros or all ones.
1335     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1336   }
1337 
1338   if (!isPPC64) {
1339     // These libcalls are not available in 32-bit.
1340     setLibcallName(RTLIB::SHL_I128, nullptr);
1341     setLibcallName(RTLIB::SRL_I128, nullptr);
1342     setLibcallName(RTLIB::SRA_I128, nullptr);
1343     setLibcallName(RTLIB::MULO_I64, nullptr);
1344   }
1345 
1346   if (!isPPC64)
1347     setMaxAtomicSizeInBitsSupported(32);
1348 
1349   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1350 
1351   // We have target-specific dag combine patterns for the following nodes:
1352   setTargetDAGCombine(ISD::ADD);
1353   setTargetDAGCombine(ISD::SHL);
1354   setTargetDAGCombine(ISD::SRA);
1355   setTargetDAGCombine(ISD::SRL);
1356   setTargetDAGCombine(ISD::MUL);
1357   setTargetDAGCombine(ISD::FMA);
1358   setTargetDAGCombine(ISD::SINT_TO_FP);
1359   setTargetDAGCombine(ISD::BUILD_VECTOR);
1360   if (Subtarget.hasFPCVT())
1361     setTargetDAGCombine(ISD::UINT_TO_FP);
1362   setTargetDAGCombine(ISD::LOAD);
1363   setTargetDAGCombine(ISD::STORE);
1364   setTargetDAGCombine(ISD::BR_CC);
1365   if (Subtarget.useCRBits())
1366     setTargetDAGCombine(ISD::BRCOND);
1367   setTargetDAGCombine(ISD::BSWAP);
1368   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1369   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1370   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1371 
1372   setTargetDAGCombine(ISD::SIGN_EXTEND);
1373   setTargetDAGCombine(ISD::ZERO_EXTEND);
1374   setTargetDAGCombine(ISD::ANY_EXTEND);
1375 
1376   setTargetDAGCombine(ISD::TRUNCATE);
1377   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1378 
1379 
1380   if (Subtarget.useCRBits()) {
1381     setTargetDAGCombine(ISD::TRUNCATE);
1382     setTargetDAGCombine(ISD::SETCC);
1383     setTargetDAGCombine(ISD::SELECT_CC);
1384   }
1385 
1386   if (Subtarget.hasP9Altivec()) {
1387     setTargetDAGCombine(ISD::ABS);
1388     setTargetDAGCombine(ISD::VSELECT);
1389   }
1390 
1391   setLibcallName(RTLIB::LOG_F128, "logf128");
1392   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1393   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1394   setLibcallName(RTLIB::EXP_F128, "expf128");
1395   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1396   setLibcallName(RTLIB::SIN_F128, "sinf128");
1397   setLibcallName(RTLIB::COS_F128, "cosf128");
1398   setLibcallName(RTLIB::POW_F128, "powf128");
1399   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1400   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1401   setLibcallName(RTLIB::REM_F128, "fmodf128");
1402   setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1403   setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1404   setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1405   setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1406   setLibcallName(RTLIB::ROUND_F128, "roundf128");
1407   setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1408   setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1409   setLibcallName(RTLIB::RINT_F128, "rintf128");
1410   setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1411   setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1412   setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1413   setLibcallName(RTLIB::FMA_F128, "fmaf128");
1414 
1415   // With 32 condition bits, we don't need to sink (and duplicate) compares
1416   // aggressively in CodeGenPrep.
1417   if (Subtarget.useCRBits()) {
1418     setHasMultipleConditionRegisters();
1419     setJumpIsExpensive();
1420   }
1421 
1422   setMinFunctionAlignment(Align(4));
1423 
1424   switch (Subtarget.getCPUDirective()) {
1425   default: break;
1426   case PPC::DIR_970:
1427   case PPC::DIR_A2:
1428   case PPC::DIR_E500:
1429   case PPC::DIR_E500mc:
1430   case PPC::DIR_E5500:
1431   case PPC::DIR_PWR4:
1432   case PPC::DIR_PWR5:
1433   case PPC::DIR_PWR5X:
1434   case PPC::DIR_PWR6:
1435   case PPC::DIR_PWR6X:
1436   case PPC::DIR_PWR7:
1437   case PPC::DIR_PWR8:
1438   case PPC::DIR_PWR9:
1439   case PPC::DIR_PWR10:
1440   case PPC::DIR_PWR_FUTURE:
1441     setPrefLoopAlignment(Align(16));
1442     setPrefFunctionAlignment(Align(16));
1443     break;
1444   }
1445 
1446   if (Subtarget.enableMachineScheduler())
1447     setSchedulingPreference(Sched::Source);
1448   else
1449     setSchedulingPreference(Sched::Hybrid);
1450 
1451   computeRegisterProperties(STI.getRegisterInfo());
1452 
1453   // The Freescale cores do better with aggressive inlining of memcpy and
1454   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1455   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1456       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1457     MaxStoresPerMemset = 32;
1458     MaxStoresPerMemsetOptSize = 16;
1459     MaxStoresPerMemcpy = 32;
1460     MaxStoresPerMemcpyOptSize = 8;
1461     MaxStoresPerMemmove = 32;
1462     MaxStoresPerMemmoveOptSize = 8;
1463   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1464     // The A2 also benefits from (very) aggressive inlining of memcpy and
1465     // friends. The overhead of a the function call, even when warm, can be
1466     // over one hundred cycles.
1467     MaxStoresPerMemset = 128;
1468     MaxStoresPerMemcpy = 128;
1469     MaxStoresPerMemmove = 128;
1470     MaxLoadsPerMemcmp = 128;
1471   } else {
1472     MaxLoadsPerMemcmp = 8;
1473     MaxLoadsPerMemcmpOptSize = 4;
1474   }
1475 
1476   IsStrictFPEnabled = true;
1477 
1478   // Let the subtarget (CPU) decide if a predictable select is more expensive
1479   // than the corresponding branch. This information is used in CGP to decide
1480   // when to convert selects into branches.
1481   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1482 }
1483 
1484 // *********************************** NOTE ************************************
1485 // For selecting load and store instructions, the addressing modes are defined
1486 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1487 // patterns to match the load the store instructions.
1488 //
1489 // The TD definitions for the addressing modes correspond to their respective
1490 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1491 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1492 // address mode flags of a particular node. Afterwards, the computed address
1493 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1494 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1495 // accordingly, based on the preferred addressing mode.
1496 //
1497 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1498 // MemOpFlags contains all the possible flags that can be used to compute the
1499 // optimal addressing mode for load and store instructions.
1500 // AddrMode contains all the possible load and store addressing modes available
1501 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1502 //
1503 // When adding new load and store instructions, it is possible that new address
1504 // flags may need to be added into MemOpFlags, and a new addressing mode will
1505 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1506 // of the minimal and main distinguishing address flags for the new load/store
1507 // instructions) will need to be added into initializeAddrModeMap() below.
1508 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1509 // need to be updated to account for selecting the optimal addressing mode.
1510 // *****************************************************************************
1511 /// Initialize the map that relates the different addressing modes of the load
1512 /// and store instructions to a set of flags. This ensures the load/store
1513 /// instruction is correctly matched during instruction selection.
1514 void PPCTargetLowering::initializeAddrModeMap() {
1515   AddrModesMap[PPC::AM_DForm] = {
1516       // LWZ, STW
1517       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_WordInt,
1518       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_WordInt,
1519       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1520       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1521       // LBZ, LHZ, STB, STH
1522       PPC::MOF_ZExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1523       PPC::MOF_ZExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1524       PPC::MOF_ZExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1525       PPC::MOF_ZExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1526       // LHA
1527       PPC::MOF_SExt | PPC::MOF_RPlusSImm16 | PPC::MOF_SubWordInt,
1528       PPC::MOF_SExt | PPC::MOF_RPlusLo | PPC::MOF_SubWordInt,
1529       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_SubWordInt,
1530       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubWordInt,
1531       // LFS, LFD, STFS, STFD
1532       PPC::MOF_RPlusSImm16 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1533       PPC::MOF_RPlusLo | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1534       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1535       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetBeforeP9,
1536   };
1537   AddrModesMap[PPC::AM_DSForm] = {
1538       // LWA
1539       PPC::MOF_SExt | PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_WordInt,
1540       PPC::MOF_SExt | PPC::MOF_NotAddNorCst | PPC::MOF_WordInt,
1541       PPC::MOF_SExt | PPC::MOF_AddrIsSImm32 | PPC::MOF_WordInt,
1542       // LD, STD
1543       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_DoubleWordInt,
1544       PPC::MOF_NotAddNorCst | PPC::MOF_DoubleWordInt,
1545       PPC::MOF_AddrIsSImm32 | PPC::MOF_DoubleWordInt,
1546       // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1547       PPC::MOF_RPlusSImm16Mult4 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1548       PPC::MOF_NotAddNorCst | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1549       PPC::MOF_AddrIsSImm32 | PPC::MOF_ScalarFloat | PPC::MOF_SubtargetP9,
1550   };
1551   AddrModesMap[PPC::AM_DQForm] = {
1552       // LXV, STXV
1553       PPC::MOF_RPlusSImm16Mult16 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1554       PPC::MOF_NotAddNorCst | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1555       PPC::MOF_AddrIsSImm32 | PPC::MOF_Vector | PPC::MOF_SubtargetP9,
1556   };
1557   AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1558                                        PPC::MOF_SubtargetP10};
1559   // TODO: Add mapping for quadword load/store.
1560 }
1561 
1562 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1563 /// the desired ByVal argument alignment.
1564 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1565   if (MaxAlign == MaxMaxAlign)
1566     return;
1567   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1568     if (MaxMaxAlign >= 32 &&
1569         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1570       MaxAlign = Align(32);
1571     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1572              MaxAlign < 16)
1573       MaxAlign = Align(16);
1574   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1575     Align EltAlign;
1576     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1577     if (EltAlign > MaxAlign)
1578       MaxAlign = EltAlign;
1579   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1580     for (auto *EltTy : STy->elements()) {
1581       Align EltAlign;
1582       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1583       if (EltAlign > MaxAlign)
1584         MaxAlign = EltAlign;
1585       if (MaxAlign == MaxMaxAlign)
1586         break;
1587     }
1588   }
1589 }
1590 
1591 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1592 /// function arguments in the caller parameter area.
1593 uint64_t PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1594                                                   const DataLayout &DL) const {
1595   // 16byte and wider vectors are passed on 16byte boundary.
1596   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1597   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1598   if (Subtarget.hasAltivec())
1599     getMaxByValAlign(Ty, Alignment, Align(16));
1600   return Alignment.value();
1601 }
1602 
1603 bool PPCTargetLowering::useSoftFloat() const {
1604   return Subtarget.useSoftFloat();
1605 }
1606 
1607 bool PPCTargetLowering::hasSPE() const {
1608   return Subtarget.hasSPE();
1609 }
1610 
1611 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1612   return VT.isScalarInteger();
1613 }
1614 
1615 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1616   switch ((PPCISD::NodeType)Opcode) {
1617   case PPCISD::FIRST_NUMBER:    break;
1618   case PPCISD::FSEL:            return "PPCISD::FSEL";
1619   case PPCISD::XSMAXC:          return "PPCISD::XSMAXC";
1620   case PPCISD::XSMINC:          return "PPCISD::XSMINC";
1621   case PPCISD::FCFID:           return "PPCISD::FCFID";
1622   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1623   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1624   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1625   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1626   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1627   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1628   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1629   case PPCISD::FP_TO_UINT_IN_VSR:
1630                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1631   case PPCISD::FP_TO_SINT_IN_VSR:
1632                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1633   case PPCISD::FRE:             return "PPCISD::FRE";
1634   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1635   case PPCISD::FTSQRT:
1636     return "PPCISD::FTSQRT";
1637   case PPCISD::FSQRT:
1638     return "PPCISD::FSQRT";
1639   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1640   case PPCISD::VPERM:           return "PPCISD::VPERM";
1641   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1642   case PPCISD::XXSPLTI_SP_TO_DP:
1643     return "PPCISD::XXSPLTI_SP_TO_DP";
1644   case PPCISD::XXSPLTI32DX:
1645     return "PPCISD::XXSPLTI32DX";
1646   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1647   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1648   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1649   case PPCISD::CMPB:            return "PPCISD::CMPB";
1650   case PPCISD::Hi:              return "PPCISD::Hi";
1651   case PPCISD::Lo:              return "PPCISD::Lo";
1652   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1653   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1654   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1655   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1656   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1657   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1658   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1659   case PPCISD::SRL:             return "PPCISD::SRL";
1660   case PPCISD::SRA:             return "PPCISD::SRA";
1661   case PPCISD::SHL:             return "PPCISD::SHL";
1662   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1663   case PPCISD::CALL:            return "PPCISD::CALL";
1664   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1665   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1666   case PPCISD::CALL_RM:
1667     return "PPCISD::CALL_RM";
1668   case PPCISD::CALL_NOP_RM:
1669     return "PPCISD::CALL_NOP_RM";
1670   case PPCISD::CALL_NOTOC_RM:
1671     return "PPCISD::CALL_NOTOC_RM";
1672   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1673   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1674   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1675   case PPCISD::BCTRL_RM:
1676     return "PPCISD::BCTRL_RM";
1677   case PPCISD::BCTRL_LOAD_TOC_RM:
1678     return "PPCISD::BCTRL_LOAD_TOC_RM";
1679   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1680   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1681   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1682   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1683   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1684   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1685   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1686   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1687   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1688   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1689   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1690     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1691   case PPCISD::ANDI_rec_1_EQ_BIT:
1692     return "PPCISD::ANDI_rec_1_EQ_BIT";
1693   case PPCISD::ANDI_rec_1_GT_BIT:
1694     return "PPCISD::ANDI_rec_1_GT_BIT";
1695   case PPCISD::VCMP:            return "PPCISD::VCMP";
1696   case PPCISD::VCMP_rec:        return "PPCISD::VCMP_rec";
1697   case PPCISD::LBRX:            return "PPCISD::LBRX";
1698   case PPCISD::STBRX:           return "PPCISD::STBRX";
1699   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1700   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1701   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1702   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1703   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1704   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1705   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1706   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1707   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1708   case PPCISD::ST_VSR_SCAL_INT:
1709                                 return "PPCISD::ST_VSR_SCAL_INT";
1710   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1711   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1712   case PPCISD::BDZ:             return "PPCISD::BDZ";
1713   case PPCISD::MFFS:            return "PPCISD::MFFS";
1714   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1715   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1716   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1717   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1718   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1719   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1720   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1721   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1722   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1723   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1724   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1725   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1726   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1727   case PPCISD::TLSGD_AIX:       return "PPCISD::TLSGD_AIX";
1728   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1729   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1730   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1731   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1732   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1733   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1734   case PPCISD::PADDI_DTPREL:
1735     return "PPCISD::PADDI_DTPREL";
1736   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1737   case PPCISD::SC:              return "PPCISD::SC";
1738   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1739   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1740   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1741   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1742   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1743   case PPCISD::VABSD:           return "PPCISD::VABSD";
1744   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1745   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1746   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1747   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1748   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1749   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1750   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1751   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1752     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1753   case PPCISD::TLS_LOCAL_EXEC_MAT_ADDR:
1754     return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1755   case PPCISD::ACC_BUILD:       return "PPCISD::ACC_BUILD";
1756   case PPCISD::PAIR_BUILD:      return "PPCISD::PAIR_BUILD";
1757   case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1758   case PPCISD::XXMFACC:         return "PPCISD::XXMFACC";
1759   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1760   case PPCISD::ZEXT_LD_SPLAT:   return "PPCISD::ZEXT_LD_SPLAT";
1761   case PPCISD::SEXT_LD_SPLAT:   return "PPCISD::SEXT_LD_SPLAT";
1762   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1763   case PPCISD::STRICT_FADDRTZ:
1764     return "PPCISD::STRICT_FADDRTZ";
1765   case PPCISD::STRICT_FCTIDZ:
1766     return "PPCISD::STRICT_FCTIDZ";
1767   case PPCISD::STRICT_FCTIWZ:
1768     return "PPCISD::STRICT_FCTIWZ";
1769   case PPCISD::STRICT_FCTIDUZ:
1770     return "PPCISD::STRICT_FCTIDUZ";
1771   case PPCISD::STRICT_FCTIWUZ:
1772     return "PPCISD::STRICT_FCTIWUZ";
1773   case PPCISD::STRICT_FCFID:
1774     return "PPCISD::STRICT_FCFID";
1775   case PPCISD::STRICT_FCFIDU:
1776     return "PPCISD::STRICT_FCFIDU";
1777   case PPCISD::STRICT_FCFIDS:
1778     return "PPCISD::STRICT_FCFIDS";
1779   case PPCISD::STRICT_FCFIDUS:
1780     return "PPCISD::STRICT_FCFIDUS";
1781   case PPCISD::LXVRZX:          return "PPCISD::LXVRZX";
1782   }
1783   return nullptr;
1784 }
1785 
1786 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1787                                           EVT VT) const {
1788   if (!VT.isVector())
1789     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1790 
1791   return VT.changeVectorElementTypeToInteger();
1792 }
1793 
1794 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1795   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1796   return true;
1797 }
1798 
1799 //===----------------------------------------------------------------------===//
1800 // Node matching predicates, for use by the tblgen matching code.
1801 //===----------------------------------------------------------------------===//
1802 
1803 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1804 static bool isFloatingPointZero(SDValue Op) {
1805   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1806     return CFP->getValueAPF().isZero();
1807   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1808     // Maybe this has already been legalized into the constant pool?
1809     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1810       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1811         return CFP->getValueAPF().isZero();
1812   }
1813   return false;
1814 }
1815 
1816 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1817 /// true if Op is undef or if it matches the specified value.
1818 static bool isConstantOrUndef(int Op, int Val) {
1819   return Op < 0 || Op == Val;
1820 }
1821 
1822 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1823 /// VPKUHUM instruction.
1824 /// The ShuffleKind distinguishes between big-endian operations with
1825 /// two different inputs (0), either-endian operations with two identical
1826 /// inputs (1), and little-endian operations with two different inputs (2).
1827 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1828 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1829                                SelectionDAG &DAG) {
1830   bool IsLE = DAG.getDataLayout().isLittleEndian();
1831   if (ShuffleKind == 0) {
1832     if (IsLE)
1833       return false;
1834     for (unsigned i = 0; i != 16; ++i)
1835       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1836         return false;
1837   } else if (ShuffleKind == 2) {
1838     if (!IsLE)
1839       return false;
1840     for (unsigned i = 0; i != 16; ++i)
1841       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1842         return false;
1843   } else if (ShuffleKind == 1) {
1844     unsigned j = IsLE ? 0 : 1;
1845     for (unsigned i = 0; i != 8; ++i)
1846       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1847           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1848         return false;
1849   }
1850   return true;
1851 }
1852 
1853 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1854 /// VPKUWUM instruction.
1855 /// The ShuffleKind distinguishes between big-endian operations with
1856 /// two different inputs (0), either-endian operations with two identical
1857 /// inputs (1), and little-endian operations with two different inputs (2).
1858 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1859 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1860                                SelectionDAG &DAG) {
1861   bool IsLE = DAG.getDataLayout().isLittleEndian();
1862   if (ShuffleKind == 0) {
1863     if (IsLE)
1864       return false;
1865     for (unsigned i = 0; i != 16; i += 2)
1866       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1867           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1868         return false;
1869   } else if (ShuffleKind == 2) {
1870     if (!IsLE)
1871       return false;
1872     for (unsigned i = 0; i != 16; i += 2)
1873       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1874           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1875         return false;
1876   } else if (ShuffleKind == 1) {
1877     unsigned j = IsLE ? 0 : 2;
1878     for (unsigned i = 0; i != 8; i += 2)
1879       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1880           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1881           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1882           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1883         return false;
1884   }
1885   return true;
1886 }
1887 
1888 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1889 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1890 /// current subtarget.
1891 ///
1892 /// The ShuffleKind distinguishes between big-endian operations with
1893 /// two different inputs (0), either-endian operations with two identical
1894 /// inputs (1), and little-endian operations with two different inputs (2).
1895 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1896 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1897                                SelectionDAG &DAG) {
1898   const PPCSubtarget& Subtarget =
1899       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1900   if (!Subtarget.hasP8Vector())
1901     return false;
1902 
1903   bool IsLE = DAG.getDataLayout().isLittleEndian();
1904   if (ShuffleKind == 0) {
1905     if (IsLE)
1906       return false;
1907     for (unsigned i = 0; i != 16; i += 4)
1908       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1909           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1910           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1911           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1912         return false;
1913   } else if (ShuffleKind == 2) {
1914     if (!IsLE)
1915       return false;
1916     for (unsigned i = 0; i != 16; i += 4)
1917       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1918           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1919           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1920           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1921         return false;
1922   } else if (ShuffleKind == 1) {
1923     unsigned j = IsLE ? 0 : 4;
1924     for (unsigned i = 0; i != 8; i += 4)
1925       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1926           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1927           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1928           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1929           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1930           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1931           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1932           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1933         return false;
1934   }
1935   return true;
1936 }
1937 
1938 /// isVMerge - Common function, used to match vmrg* shuffles.
1939 ///
1940 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1941                      unsigned LHSStart, unsigned RHSStart) {
1942   if (N->getValueType(0) != MVT::v16i8)
1943     return false;
1944   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1945          "Unsupported merge size!");
1946 
1947   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1948     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1949       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1950                              LHSStart+j+i*UnitSize) ||
1951           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1952                              RHSStart+j+i*UnitSize))
1953         return false;
1954     }
1955   return true;
1956 }
1957 
1958 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1959 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1960 /// The ShuffleKind distinguishes between big-endian merges with two
1961 /// different inputs (0), either-endian merges with two identical inputs (1),
1962 /// and little-endian merges with two different inputs (2).  For the latter,
1963 /// the input operands are swapped (see PPCInstrAltivec.td).
1964 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1965                              unsigned ShuffleKind, SelectionDAG &DAG) {
1966   if (DAG.getDataLayout().isLittleEndian()) {
1967     if (ShuffleKind == 1) // unary
1968       return isVMerge(N, UnitSize, 0, 0);
1969     else if (ShuffleKind == 2) // swapped
1970       return isVMerge(N, UnitSize, 0, 16);
1971     else
1972       return false;
1973   } else {
1974     if (ShuffleKind == 1) // unary
1975       return isVMerge(N, UnitSize, 8, 8);
1976     else if (ShuffleKind == 0) // normal
1977       return isVMerge(N, UnitSize, 8, 24);
1978     else
1979       return false;
1980   }
1981 }
1982 
1983 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1984 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1985 /// The ShuffleKind distinguishes between big-endian merges with two
1986 /// different inputs (0), either-endian merges with two identical inputs (1),
1987 /// and little-endian merges with two different inputs (2).  For the latter,
1988 /// the input operands are swapped (see PPCInstrAltivec.td).
1989 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1990                              unsigned ShuffleKind, SelectionDAG &DAG) {
1991   if (DAG.getDataLayout().isLittleEndian()) {
1992     if (ShuffleKind == 1) // unary
1993       return isVMerge(N, UnitSize, 8, 8);
1994     else if (ShuffleKind == 2) // swapped
1995       return isVMerge(N, UnitSize, 8, 24);
1996     else
1997       return false;
1998   } else {
1999     if (ShuffleKind == 1) // unary
2000       return isVMerge(N, UnitSize, 0, 0);
2001     else if (ShuffleKind == 0) // normal
2002       return isVMerge(N, UnitSize, 0, 16);
2003     else
2004       return false;
2005   }
2006 }
2007 
2008 /**
2009  * Common function used to match vmrgew and vmrgow shuffles
2010  *
2011  * The indexOffset determines whether to look for even or odd words in
2012  * the shuffle mask. This is based on the of the endianness of the target
2013  * machine.
2014  *   - Little Endian:
2015  *     - Use offset of 0 to check for odd elements
2016  *     - Use offset of 4 to check for even elements
2017  *   - Big Endian:
2018  *     - Use offset of 0 to check for even elements
2019  *     - Use offset of 4 to check for odd elements
2020  * A detailed description of the vector element ordering for little endian and
2021  * big endian can be found at
2022  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2023  * Targeting your applications - what little endian and big endian IBM XL C/C++
2024  * compiler differences mean to you
2025  *
2026  * The mask to the shuffle vector instruction specifies the indices of the
2027  * elements from the two input vectors to place in the result. The elements are
2028  * numbered in array-access order, starting with the first vector. These vectors
2029  * are always of type v16i8, thus each vector will contain 16 elements of size
2030  * 8. More info on the shuffle vector can be found in the
2031  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2032  * Language Reference.
2033  *
2034  * The RHSStartValue indicates whether the same input vectors are used (unary)
2035  * or two different input vectors are used, based on the following:
2036  *   - If the instruction uses the same vector for both inputs, the range of the
2037  *     indices will be 0 to 15. In this case, the RHSStart value passed should
2038  *     be 0.
2039  *   - If the instruction has two different vectors then the range of the
2040  *     indices will be 0 to 31. In this case, the RHSStart value passed should
2041  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
2042  *     to 31 specify elements in the second vector).
2043  *
2044  * \param[in] N The shuffle vector SD Node to analyze
2045  * \param[in] IndexOffset Specifies whether to look for even or odd elements
2046  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2047  * vector to the shuffle_vector instruction
2048  * \return true iff this shuffle vector represents an even or odd word merge
2049  */
2050 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2051                      unsigned RHSStartValue) {
2052   if (N->getValueType(0) != MVT::v16i8)
2053     return false;
2054 
2055   for (unsigned i = 0; i < 2; ++i)
2056     for (unsigned j = 0; j < 4; ++j)
2057       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2058                              i*RHSStartValue+j+IndexOffset) ||
2059           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2060                              i*RHSStartValue+j+IndexOffset+8))
2061         return false;
2062   return true;
2063 }
2064 
2065 /**
2066  * Determine if the specified shuffle mask is suitable for the vmrgew or
2067  * vmrgow instructions.
2068  *
2069  * \param[in] N The shuffle vector SD Node to analyze
2070  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2071  * \param[in] ShuffleKind Identify the type of merge:
2072  *   - 0 = big-endian merge with two different inputs;
2073  *   - 1 = either-endian merge with two identical inputs;
2074  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
2075  *     little-endian merges).
2076  * \param[in] DAG The current SelectionDAG
2077  * \return true iff this shuffle mask
2078  */
2079 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
2080                               unsigned ShuffleKind, SelectionDAG &DAG) {
2081   if (DAG.getDataLayout().isLittleEndian()) {
2082     unsigned indexOffset = CheckEven ? 4 : 0;
2083     if (ShuffleKind == 1) // Unary
2084       return isVMerge(N, indexOffset, 0);
2085     else if (ShuffleKind == 2) // swapped
2086       return isVMerge(N, indexOffset, 16);
2087     else
2088       return false;
2089   }
2090   else {
2091     unsigned indexOffset = CheckEven ? 0 : 4;
2092     if (ShuffleKind == 1) // Unary
2093       return isVMerge(N, indexOffset, 0);
2094     else if (ShuffleKind == 0) // Normal
2095       return isVMerge(N, indexOffset, 16);
2096     else
2097       return false;
2098   }
2099   return false;
2100 }
2101 
2102 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2103 /// amount, otherwise return -1.
2104 /// The ShuffleKind distinguishes between big-endian operations with two
2105 /// different inputs (0), either-endian operations with two identical inputs
2106 /// (1), and little-endian operations with two different inputs (2).  For the
2107 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2108 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2109                              SelectionDAG &DAG) {
2110   if (N->getValueType(0) != MVT::v16i8)
2111     return -1;
2112 
2113   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2114 
2115   // Find the first non-undef value in the shuffle mask.
2116   unsigned i;
2117   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2118     /*search*/;
2119 
2120   if (i == 16) return -1;  // all undef.
2121 
2122   // Otherwise, check to see if the rest of the elements are consecutively
2123   // numbered from this value.
2124   unsigned ShiftAmt = SVOp->getMaskElt(i);
2125   if (ShiftAmt < i) return -1;
2126 
2127   ShiftAmt -= i;
2128   bool isLE = DAG.getDataLayout().isLittleEndian();
2129 
2130   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2131     // Check the rest of the elements to see if they are consecutive.
2132     for (++i; i != 16; ++i)
2133       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2134         return -1;
2135   } else if (ShuffleKind == 1) {
2136     // Check the rest of the elements to see if they are consecutive.
2137     for (++i; i != 16; ++i)
2138       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2139         return -1;
2140   } else
2141     return -1;
2142 
2143   if (isLE)
2144     ShiftAmt = 16 - ShiftAmt;
2145 
2146   return ShiftAmt;
2147 }
2148 
2149 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2150 /// specifies a splat of a single element that is suitable for input to
2151 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2152 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
2153   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2154          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2155 
2156   // The consecutive indices need to specify an element, not part of two
2157   // different elements.  So abandon ship early if this isn't the case.
2158   if (N->getMaskElt(0) % EltSize != 0)
2159     return false;
2160 
2161   // This is a splat operation if each element of the permute is the same, and
2162   // if the value doesn't reference the second vector.
2163   unsigned ElementBase = N->getMaskElt(0);
2164 
2165   // FIXME: Handle UNDEF elements too!
2166   if (ElementBase >= 16)
2167     return false;
2168 
2169   // Check that the indices are consecutive, in the case of a multi-byte element
2170   // splatted with a v16i8 mask.
2171   for (unsigned i = 1; i != EltSize; ++i)
2172     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2173       return false;
2174 
2175   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2176     if (N->getMaskElt(i) < 0) continue;
2177     for (unsigned j = 0; j != EltSize; ++j)
2178       if (N->getMaskElt(i+j) != N->getMaskElt(j))
2179         return false;
2180   }
2181   return true;
2182 }
2183 
2184 /// Check that the mask is shuffling N byte elements. Within each N byte
2185 /// element of the mask, the indices could be either in increasing or
2186 /// decreasing order as long as they are consecutive.
2187 /// \param[in] N the shuffle vector SD Node to analyze
2188 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2189 /// Word/DoubleWord/QuadWord).
2190 /// \param[in] StepLen the delta indices number among the N byte element, if
2191 /// the mask is in increasing/decreasing order then it is 1/-1.
2192 /// \return true iff the mask is shuffling N byte elements.
2193 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2194                                    int StepLen) {
2195   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2196          "Unexpected element width.");
2197   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2198 
2199   unsigned NumOfElem = 16 / Width;
2200   unsigned MaskVal[16]; //  Width is never greater than 16
2201   for (unsigned i = 0; i < NumOfElem; ++i) {
2202     MaskVal[0] = N->getMaskElt(i * Width);
2203     if ((StepLen == 1) && (MaskVal[0] % Width)) {
2204       return false;
2205     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2206       return false;
2207     }
2208 
2209     for (unsigned int j = 1; j < Width; ++j) {
2210       MaskVal[j] = N->getMaskElt(i * Width + j);
2211       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2212         return false;
2213       }
2214     }
2215   }
2216 
2217   return true;
2218 }
2219 
2220 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2221                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2222   if (!isNByteElemShuffleMask(N, 4, 1))
2223     return false;
2224 
2225   // Now we look at mask elements 0,4,8,12
2226   unsigned M0 = N->getMaskElt(0) / 4;
2227   unsigned M1 = N->getMaskElt(4) / 4;
2228   unsigned M2 = N->getMaskElt(8) / 4;
2229   unsigned M3 = N->getMaskElt(12) / 4;
2230   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2231   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2232 
2233   // Below, let H and L be arbitrary elements of the shuffle mask
2234   // where H is in the range [4,7] and L is in the range [0,3].
2235   // H, 1, 2, 3 or L, 5, 6, 7
2236   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2237       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2238     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2239     InsertAtByte = IsLE ? 12 : 0;
2240     Swap = M0 < 4;
2241     return true;
2242   }
2243   // 0, H, 2, 3 or 4, L, 6, 7
2244   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2245       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2246     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2247     InsertAtByte = IsLE ? 8 : 4;
2248     Swap = M1 < 4;
2249     return true;
2250   }
2251   // 0, 1, H, 3 or 4, 5, L, 7
2252   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2253       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2254     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2255     InsertAtByte = IsLE ? 4 : 8;
2256     Swap = M2 < 4;
2257     return true;
2258   }
2259   // 0, 1, 2, H or 4, 5, 6, L
2260   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2261       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2262     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2263     InsertAtByte = IsLE ? 0 : 12;
2264     Swap = M3 < 4;
2265     return true;
2266   }
2267 
2268   // If both vector operands for the shuffle are the same vector, the mask will
2269   // contain only elements from the first one and the second one will be undef.
2270   if (N->getOperand(1).isUndef()) {
2271     ShiftElts = 0;
2272     Swap = true;
2273     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2274     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2275       InsertAtByte = IsLE ? 12 : 0;
2276       return true;
2277     }
2278     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2279       InsertAtByte = IsLE ? 8 : 4;
2280       return true;
2281     }
2282     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2283       InsertAtByte = IsLE ? 4 : 8;
2284       return true;
2285     }
2286     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2287       InsertAtByte = IsLE ? 0 : 12;
2288       return true;
2289     }
2290   }
2291 
2292   return false;
2293 }
2294 
2295 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2296                                bool &Swap, bool IsLE) {
2297   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2298   // Ensure each byte index of the word is consecutive.
2299   if (!isNByteElemShuffleMask(N, 4, 1))
2300     return false;
2301 
2302   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2303   unsigned M0 = N->getMaskElt(0) / 4;
2304   unsigned M1 = N->getMaskElt(4) / 4;
2305   unsigned M2 = N->getMaskElt(8) / 4;
2306   unsigned M3 = N->getMaskElt(12) / 4;
2307 
2308   // If both vector operands for the shuffle are the same vector, the mask will
2309   // contain only elements from the first one and the second one will be undef.
2310   if (N->getOperand(1).isUndef()) {
2311     assert(M0 < 4 && "Indexing into an undef vector?");
2312     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2313       return false;
2314 
2315     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2316     Swap = false;
2317     return true;
2318   }
2319 
2320   // Ensure each word index of the ShuffleVector Mask is consecutive.
2321   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2322     return false;
2323 
2324   if (IsLE) {
2325     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2326       // Input vectors don't need to be swapped if the leading element
2327       // of the result is one of the 3 left elements of the second vector
2328       // (or if there is no shift to be done at all).
2329       Swap = false;
2330       ShiftElts = (8 - M0) % 8;
2331     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2332       // Input vectors need to be swapped if the leading element
2333       // of the result is one of the 3 left elements of the first vector
2334       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2335       Swap = true;
2336       ShiftElts = (4 - M0) % 4;
2337     }
2338 
2339     return true;
2340   } else {                                          // BE
2341     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2342       // Input vectors don't need to be swapped if the leading element
2343       // of the result is one of the 4 elements of the first vector.
2344       Swap = false;
2345       ShiftElts = M0;
2346     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2347       // Input vectors need to be swapped if the leading element
2348       // of the result is one of the 4 elements of the right vector.
2349       Swap = true;
2350       ShiftElts = M0 - 4;
2351     }
2352 
2353     return true;
2354   }
2355 }
2356 
2357 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2358   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2359 
2360   if (!isNByteElemShuffleMask(N, Width, -1))
2361     return false;
2362 
2363   for (int i = 0; i < 16; i += Width)
2364     if (N->getMaskElt(i) != i + Width - 1)
2365       return false;
2366 
2367   return true;
2368 }
2369 
2370 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2371   return isXXBRShuffleMaskHelper(N, 2);
2372 }
2373 
2374 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2375   return isXXBRShuffleMaskHelper(N, 4);
2376 }
2377 
2378 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2379   return isXXBRShuffleMaskHelper(N, 8);
2380 }
2381 
2382 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2383   return isXXBRShuffleMaskHelper(N, 16);
2384 }
2385 
2386 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2387 /// if the inputs to the instruction should be swapped and set \p DM to the
2388 /// value for the immediate.
2389 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2390 /// AND element 0 of the result comes from the first input (LE) or second input
2391 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2392 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2393 /// mask.
2394 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2395                                bool &Swap, bool IsLE) {
2396   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2397 
2398   // Ensure each byte index of the double word is consecutive.
2399   if (!isNByteElemShuffleMask(N, 8, 1))
2400     return false;
2401 
2402   unsigned M0 = N->getMaskElt(0) / 8;
2403   unsigned M1 = N->getMaskElt(8) / 8;
2404   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2405 
2406   // If both vector operands for the shuffle are the same vector, the mask will
2407   // contain only elements from the first one and the second one will be undef.
2408   if (N->getOperand(1).isUndef()) {
2409     if ((M0 | M1) < 2) {
2410       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2411       Swap = false;
2412       return true;
2413     } else
2414       return false;
2415   }
2416 
2417   if (IsLE) {
2418     if (M0 > 1 && M1 < 2) {
2419       Swap = false;
2420     } else if (M0 < 2 && M1 > 1) {
2421       M0 = (M0 + 2) % 4;
2422       M1 = (M1 + 2) % 4;
2423       Swap = true;
2424     } else
2425       return false;
2426 
2427     // Note: if control flow comes here that means Swap is already set above
2428     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2429     return true;
2430   } else { // BE
2431     if (M0 < 2 && M1 > 1) {
2432       Swap = false;
2433     } else if (M0 > 1 && M1 < 2) {
2434       M0 = (M0 + 2) % 4;
2435       M1 = (M1 + 2) % 4;
2436       Swap = true;
2437     } else
2438       return false;
2439 
2440     // Note: if control flow comes here that means Swap is already set above
2441     DM = (M0 << 1) + (M1 & 1);
2442     return true;
2443   }
2444 }
2445 
2446 
2447 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2448 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2449 /// elements are counted from the left of the vector register).
2450 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2451                                          SelectionDAG &DAG) {
2452   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2453   assert(isSplatShuffleMask(SVOp, EltSize));
2454   if (DAG.getDataLayout().isLittleEndian())
2455     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2456   else
2457     return SVOp->getMaskElt(0) / EltSize;
2458 }
2459 
2460 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2461 /// by using a vspltis[bhw] instruction of the specified element size, return
2462 /// the constant being splatted.  The ByteSize field indicates the number of
2463 /// bytes of each element [124] -> [bhw].
2464 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2465   SDValue OpVal;
2466 
2467   // If ByteSize of the splat is bigger than the element size of the
2468   // build_vector, then we have a case where we are checking for a splat where
2469   // multiple elements of the buildvector are folded together into a single
2470   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2471   unsigned EltSize = 16/N->getNumOperands();
2472   if (EltSize < ByteSize) {
2473     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2474     SDValue UniquedVals[4];
2475     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2476 
2477     // See if all of the elements in the buildvector agree across.
2478     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2479       if (N->getOperand(i).isUndef()) continue;
2480       // If the element isn't a constant, bail fully out.
2481       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2482 
2483       if (!UniquedVals[i&(Multiple-1)].getNode())
2484         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2485       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2486         return SDValue();  // no match.
2487     }
2488 
2489     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2490     // either constant or undef values that are identical for each chunk.  See
2491     // if these chunks can form into a larger vspltis*.
2492 
2493     // Check to see if all of the leading entries are either 0 or -1.  If
2494     // neither, then this won't fit into the immediate field.
2495     bool LeadingZero = true;
2496     bool LeadingOnes = true;
2497     for (unsigned i = 0; i != Multiple-1; ++i) {
2498       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2499 
2500       LeadingZero &= isNullConstant(UniquedVals[i]);
2501       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2502     }
2503     // Finally, check the least significant entry.
2504     if (LeadingZero) {
2505       if (!UniquedVals[Multiple-1].getNode())
2506         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2507       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2508       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2509         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2510     }
2511     if (LeadingOnes) {
2512       if (!UniquedVals[Multiple-1].getNode())
2513         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2514       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2515       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2516         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2517     }
2518 
2519     return SDValue();
2520   }
2521 
2522   // Check to see if this buildvec has a single non-undef value in its elements.
2523   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2524     if (N->getOperand(i).isUndef()) continue;
2525     if (!OpVal.getNode())
2526       OpVal = N->getOperand(i);
2527     else if (OpVal != N->getOperand(i))
2528       return SDValue();
2529   }
2530 
2531   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2532 
2533   unsigned ValSizeInBytes = EltSize;
2534   uint64_t Value = 0;
2535   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2536     Value = CN->getZExtValue();
2537   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2538     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2539     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2540   }
2541 
2542   // If the splat value is larger than the element value, then we can never do
2543   // this splat.  The only case that we could fit the replicated bits into our
2544   // immediate field for would be zero, and we prefer to use vxor for it.
2545   if (ValSizeInBytes < ByteSize) return SDValue();
2546 
2547   // If the element value is larger than the splat value, check if it consists
2548   // of a repeated bit pattern of size ByteSize.
2549   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2550     return SDValue();
2551 
2552   // Properly sign extend the value.
2553   int MaskVal = SignExtend32(Value, ByteSize * 8);
2554 
2555   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2556   if (MaskVal == 0) return SDValue();
2557 
2558   // Finally, if this value fits in a 5 bit sext field, return it
2559   if (SignExtend32<5>(MaskVal) == MaskVal)
2560     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2561   return SDValue();
2562 }
2563 
2564 //===----------------------------------------------------------------------===//
2565 //  Addressing Mode Selection
2566 //===----------------------------------------------------------------------===//
2567 
2568 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2569 /// or 64-bit immediate, and if the value can be accurately represented as a
2570 /// sign extension from a 16-bit value.  If so, this returns true and the
2571 /// immediate.
2572 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2573   if (!isa<ConstantSDNode>(N))
2574     return false;
2575 
2576   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2577   if (N->getValueType(0) == MVT::i32)
2578     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2579   else
2580     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2581 }
2582 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2583   return isIntS16Immediate(Op.getNode(), Imm);
2584 }
2585 
2586 /// Used when computing address flags for selecting loads and stores.
2587 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2588 /// An OR of two provably disjoint values is equivalent to an ADD.
2589 /// Most PPC load/store instructions compute the effective address as a sum,
2590 /// so doing this conversion is useful.
2591 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2592   if (N.getOpcode() != ISD::OR)
2593     return false;
2594   KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2595   if (!LHSKnown.Zero.getBoolValue())
2596     return false;
2597   KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2598   return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2599 }
2600 
2601 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2602 /// be represented as an indexed [r+r] operation.
2603 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2604                                                SDValue &Index,
2605                                                SelectionDAG &DAG) const {
2606   for (SDNode *U : N->uses()) {
2607     if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2608       if (Memop->getMemoryVT() == MVT::f64) {
2609           Base = N.getOperand(0);
2610           Index = N.getOperand(1);
2611           return true;
2612       }
2613     }
2614   }
2615   return false;
2616 }
2617 
2618 /// isIntS34Immediate - This method tests if value of node given can be
2619 /// accurately represented as a sign extension from a 34-bit value.  If so,
2620 /// this returns true and the immediate.
2621 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2622   if (!isa<ConstantSDNode>(N))
2623     return false;
2624 
2625   Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2626   return isInt<34>(Imm);
2627 }
2628 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2629   return isIntS34Immediate(Op.getNode(), Imm);
2630 }
2631 
2632 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2633 /// can be represented as an indexed [r+r] operation.  Returns false if it
2634 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2635 /// non-zero and N can be represented by a base register plus a signed 16-bit
2636 /// displacement, make a more precise judgement by checking (displacement % \p
2637 /// EncodingAlignment).
2638 bool PPCTargetLowering::SelectAddressRegReg(
2639     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2640     MaybeAlign EncodingAlignment) const {
2641   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2642   // a [pc+imm].
2643   if (SelectAddressPCRel(N, Base))
2644     return false;
2645 
2646   int16_t Imm = 0;
2647   if (N.getOpcode() == ISD::ADD) {
2648     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2649     // SPE load/store can only handle 8-bit offsets.
2650     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2651         return true;
2652     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2653         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2654       return false; // r+i
2655     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2656       return false;    // r+i
2657 
2658     Base = N.getOperand(0);
2659     Index = N.getOperand(1);
2660     return true;
2661   } else if (N.getOpcode() == ISD::OR) {
2662     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2663         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2664       return false; // r+i can fold it if we can.
2665 
2666     // If this is an or of disjoint bitfields, we can codegen this as an add
2667     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2668     // disjoint.
2669     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2670 
2671     if (LHSKnown.Zero.getBoolValue()) {
2672       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2673       // If all of the bits are known zero on the LHS or RHS, the add won't
2674       // carry.
2675       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2676         Base = N.getOperand(0);
2677         Index = N.getOperand(1);
2678         return true;
2679       }
2680     }
2681   }
2682 
2683   return false;
2684 }
2685 
2686 // If we happen to be doing an i64 load or store into a stack slot that has
2687 // less than a 4-byte alignment, then the frame-index elimination may need to
2688 // use an indexed load or store instruction (because the offset may not be a
2689 // multiple of 4). The extra register needed to hold the offset comes from the
2690 // register scavenger, and it is possible that the scavenger will need to use
2691 // an emergency spill slot. As a result, we need to make sure that a spill slot
2692 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2693 // stack slot.
2694 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2695   // FIXME: This does not handle the LWA case.
2696   if (VT != MVT::i64)
2697     return;
2698 
2699   // NOTE: We'll exclude negative FIs here, which come from argument
2700   // lowering, because there are no known test cases triggering this problem
2701   // using packed structures (or similar). We can remove this exclusion if
2702   // we find such a test case. The reason why this is so test-case driven is
2703   // because this entire 'fixup' is only to prevent crashes (from the
2704   // register scavenger) on not-really-valid inputs. For example, if we have:
2705   //   %a = alloca i1
2706   //   %b = bitcast i1* %a to i64*
2707   //   store i64* a, i64 b
2708   // then the store should really be marked as 'align 1', but is not. If it
2709   // were marked as 'align 1' then the indexed form would have been
2710   // instruction-selected initially, and the problem this 'fixup' is preventing
2711   // won't happen regardless.
2712   if (FrameIdx < 0)
2713     return;
2714 
2715   MachineFunction &MF = DAG.getMachineFunction();
2716   MachineFrameInfo &MFI = MF.getFrameInfo();
2717 
2718   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2719     return;
2720 
2721   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2722   FuncInfo->setHasNonRISpills();
2723 }
2724 
2725 /// Returns true if the address N can be represented by a base register plus
2726 /// a signed 16-bit displacement [r+imm], and if it is not better
2727 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2728 /// displacements that are multiples of that value.
2729 bool PPCTargetLowering::SelectAddressRegImm(
2730     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2731     MaybeAlign EncodingAlignment) const {
2732   // FIXME dl should come from parent load or store, not from address
2733   SDLoc dl(N);
2734 
2735   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2736   // a [pc+imm].
2737   if (SelectAddressPCRel(N, Base))
2738     return false;
2739 
2740   // If this can be more profitably realized as r+r, fail.
2741   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2742     return false;
2743 
2744   if (N.getOpcode() == ISD::ADD) {
2745     int16_t imm = 0;
2746     if (isIntS16Immediate(N.getOperand(1), imm) &&
2747         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2748       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2749       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2750         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2751         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2752       } else {
2753         Base = N.getOperand(0);
2754       }
2755       return true; // [r+i]
2756     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2757       // Match LOAD (ADD (X, Lo(G))).
2758       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2759              && "Cannot handle constant offsets yet!");
2760       Disp = N.getOperand(1).getOperand(0);  // The global address.
2761       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2762              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2763              Disp.getOpcode() == ISD::TargetConstantPool ||
2764              Disp.getOpcode() == ISD::TargetJumpTable);
2765       Base = N.getOperand(0);
2766       return true;  // [&g+r]
2767     }
2768   } else if (N.getOpcode() == ISD::OR) {
2769     int16_t imm = 0;
2770     if (isIntS16Immediate(N.getOperand(1), imm) &&
2771         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2772       // If this is an or of disjoint bitfields, we can codegen this as an add
2773       // (for better address arithmetic) if the LHS and RHS of the OR are
2774       // provably disjoint.
2775       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2776 
2777       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2778         // If all of the bits are known zero on the LHS or RHS, the add won't
2779         // carry.
2780         if (FrameIndexSDNode *FI =
2781               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2782           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2783           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2784         } else {
2785           Base = N.getOperand(0);
2786         }
2787         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2788         return true;
2789       }
2790     }
2791   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2792     // Loading from a constant address.
2793 
2794     // If this address fits entirely in a 16-bit sext immediate field, codegen
2795     // this as "d, 0"
2796     int16_t Imm;
2797     if (isIntS16Immediate(CN, Imm) &&
2798         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2799       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2800       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2801                              CN->getValueType(0));
2802       return true;
2803     }
2804 
2805     // Handle 32-bit sext immediates with LIS + addr mode.
2806     if ((CN->getValueType(0) == MVT::i32 ||
2807          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2808         (!EncodingAlignment ||
2809          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2810       int Addr = (int)CN->getZExtValue();
2811 
2812       // Otherwise, break this down into an LIS + disp.
2813       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2814 
2815       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2816                                    MVT::i32);
2817       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2818       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2819       return true;
2820     }
2821   }
2822 
2823   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2824   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2825     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2826     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2827   } else
2828     Base = N;
2829   return true;      // [r+0]
2830 }
2831 
2832 /// Similar to the 16-bit case but for instructions that take a 34-bit
2833 /// displacement field (prefixed loads/stores).
2834 bool PPCTargetLowering::SelectAddressRegImm34(SDValue N, SDValue &Disp,
2835                                               SDValue &Base,
2836                                               SelectionDAG &DAG) const {
2837   // Only on 64-bit targets.
2838   if (N.getValueType() != MVT::i64)
2839     return false;
2840 
2841   SDLoc dl(N);
2842   int64_t Imm = 0;
2843 
2844   if (N.getOpcode() == ISD::ADD) {
2845     if (!isIntS34Immediate(N.getOperand(1), Imm))
2846       return false;
2847     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2848     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2849       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2850     else
2851       Base = N.getOperand(0);
2852     return true;
2853   }
2854 
2855   if (N.getOpcode() == ISD::OR) {
2856     if (!isIntS34Immediate(N.getOperand(1), Imm))
2857       return false;
2858     // If this is an or of disjoint bitfields, we can codegen this as an add
2859     // (for better address arithmetic) if the LHS and RHS of the OR are
2860     // provably disjoint.
2861     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2862     if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2863       return false;
2864     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2865       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2866     else
2867       Base = N.getOperand(0);
2868     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2869     return true;
2870   }
2871 
2872   if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2873     Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2874     Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2875     return true;
2876   }
2877 
2878   return false;
2879 }
2880 
2881 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2882 /// represented as an indexed [r+r] operation.
2883 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2884                                                 SDValue &Index,
2885                                                 SelectionDAG &DAG) const {
2886   // Check to see if we can easily represent this as an [r+r] address.  This
2887   // will fail if it thinks that the address is more profitably represented as
2888   // reg+imm, e.g. where imm = 0.
2889   if (SelectAddressRegReg(N, Base, Index, DAG))
2890     return true;
2891 
2892   // If the address is the result of an add, we will utilize the fact that the
2893   // address calculation includes an implicit add.  However, we can reduce
2894   // register pressure if we do not materialize a constant just for use as the
2895   // index register.  We only get rid of the add if it is not an add of a
2896   // value and a 16-bit signed constant and both have a single use.
2897   int16_t imm = 0;
2898   if (N.getOpcode() == ISD::ADD &&
2899       (!isIntS16Immediate(N.getOperand(1), imm) ||
2900        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2901     Base = N.getOperand(0);
2902     Index = N.getOperand(1);
2903     return true;
2904   }
2905 
2906   // Otherwise, do it the hard way, using R0 as the base register.
2907   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2908                          N.getValueType());
2909   Index = N;
2910   return true;
2911 }
2912 
2913 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2914   Ty *PCRelCand = dyn_cast<Ty>(N);
2915   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2916 }
2917 
2918 /// Returns true if this address is a PC Relative address.
2919 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2920 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2921 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2922   // This is a materialize PC Relative node. Always select this as PC Relative.
2923   Base = N;
2924   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2925     return true;
2926   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2927       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2928       isValidPCRelNode<JumpTableSDNode>(N) ||
2929       isValidPCRelNode<BlockAddressSDNode>(N))
2930     return true;
2931   return false;
2932 }
2933 
2934 /// Returns true if we should use a direct load into vector instruction
2935 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2936 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2937 
2938   // If there are any other uses other than scalar to vector, then we should
2939   // keep it as a scalar load -> direct move pattern to prevent multiple
2940   // loads.
2941   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2942   if (!LD)
2943     return false;
2944 
2945   EVT MemVT = LD->getMemoryVT();
2946   if (!MemVT.isSimple())
2947     return false;
2948   switch(MemVT.getSimpleVT().SimpleTy) {
2949   case MVT::i64:
2950     break;
2951   case MVT::i32:
2952     if (!ST.hasP8Vector())
2953       return false;
2954     break;
2955   case MVT::i16:
2956   case MVT::i8:
2957     if (!ST.hasP9Vector())
2958       return false;
2959     break;
2960   default:
2961     return false;
2962   }
2963 
2964   SDValue LoadedVal(N, 0);
2965   if (!LoadedVal.hasOneUse())
2966     return false;
2967 
2968   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2969        UI != UE; ++UI)
2970     if (UI.getUse().get().getResNo() == 0 &&
2971         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2972         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2973       return false;
2974 
2975   return true;
2976 }
2977 
2978 /// getPreIndexedAddressParts - returns true by value, base pointer and
2979 /// offset pointer and addressing mode by reference if the node's address
2980 /// can be legally represented as pre-indexed load / store address.
2981 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2982                                                   SDValue &Offset,
2983                                                   ISD::MemIndexedMode &AM,
2984                                                   SelectionDAG &DAG) const {
2985   if (DisablePPCPreinc) return false;
2986 
2987   bool isLoad = true;
2988   SDValue Ptr;
2989   EVT VT;
2990   unsigned Alignment;
2991   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2992     Ptr = LD->getBasePtr();
2993     VT = LD->getMemoryVT();
2994     Alignment = LD->getAlignment();
2995   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2996     Ptr = ST->getBasePtr();
2997     VT  = ST->getMemoryVT();
2998     Alignment = ST->getAlignment();
2999     isLoad = false;
3000   } else
3001     return false;
3002 
3003   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3004   // instructions because we can fold these into a more efficient instruction
3005   // instead, (such as LXSD).
3006   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3007     return false;
3008   }
3009 
3010   // PowerPC doesn't have preinc load/store instructions for vectors
3011   if (VT.isVector())
3012     return false;
3013 
3014   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3015     // Common code will reject creating a pre-inc form if the base pointer
3016     // is a frame index, or if N is a store and the base pointer is either
3017     // the same as or a predecessor of the value being stored.  Check for
3018     // those situations here, and try with swapped Base/Offset instead.
3019     bool Swap = false;
3020 
3021     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3022       Swap = true;
3023     else if (!isLoad) {
3024       SDValue Val = cast<StoreSDNode>(N)->getValue();
3025       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3026         Swap = true;
3027     }
3028 
3029     if (Swap)
3030       std::swap(Base, Offset);
3031 
3032     AM = ISD::PRE_INC;
3033     return true;
3034   }
3035 
3036   // LDU/STU can only handle immediates that are a multiple of 4.
3037   if (VT != MVT::i64) {
3038     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
3039       return false;
3040   } else {
3041     // LDU/STU need an address with at least 4-byte alignment.
3042     if (Alignment < 4)
3043       return false;
3044 
3045     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3046       return false;
3047   }
3048 
3049   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3050     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
3051     // sext i32 to i64 when addr mode is r+i.
3052     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3053         LD->getExtensionType() == ISD::SEXTLOAD &&
3054         isa<ConstantSDNode>(Offset))
3055       return false;
3056   }
3057 
3058   AM = ISD::PRE_INC;
3059   return true;
3060 }
3061 
3062 //===----------------------------------------------------------------------===//
3063 //  LowerOperation implementation
3064 //===----------------------------------------------------------------------===//
3065 
3066 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3067 /// and LoOpFlags to the target MO flags.
3068 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3069                                unsigned &HiOpFlags, unsigned &LoOpFlags,
3070                                const GlobalValue *GV = nullptr) {
3071   HiOpFlags = PPCII::MO_HA;
3072   LoOpFlags = PPCII::MO_LO;
3073 
3074   // Don't use the pic base if not in PIC relocation model.
3075   if (IsPIC) {
3076     HiOpFlags |= PPCII::MO_PIC_FLAG;
3077     LoOpFlags |= PPCII::MO_PIC_FLAG;
3078   }
3079 }
3080 
3081 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3082                              SelectionDAG &DAG) {
3083   SDLoc DL(HiPart);
3084   EVT PtrVT = HiPart.getValueType();
3085   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3086 
3087   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3088   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3089 
3090   // With PIC, the first instruction is actually "GR+hi(&G)".
3091   if (isPIC)
3092     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3093                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3094 
3095   // Generate non-pic code that has direct accesses to the constant pool.
3096   // The address of the global is just (hi(&g)+lo(&g)).
3097   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3098 }
3099 
3100 static void setUsesTOCBasePtr(MachineFunction &MF) {
3101   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3102   FuncInfo->setUsesTOCBasePtr();
3103 }
3104 
3105 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3106   setUsesTOCBasePtr(DAG.getMachineFunction());
3107 }
3108 
3109 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3110                                        SDValue GA) const {
3111   const bool Is64Bit = Subtarget.isPPC64();
3112   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3113   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3114                         : Subtarget.isAIXABI()
3115                               ? DAG.getRegister(PPC::R2, VT)
3116                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3117   SDValue Ops[] = { GA, Reg };
3118   return DAG.getMemIntrinsicNode(
3119       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3120       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
3121       MachineMemOperand::MOLoad);
3122 }
3123 
3124 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3125                                              SelectionDAG &DAG) const {
3126   EVT PtrVT = Op.getValueType();
3127   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3128   const Constant *C = CP->getConstVal();
3129 
3130   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3131   // The actual address of the GlobalValue is stored in the TOC.
3132   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3133     if (Subtarget.isUsingPCRelativeCalls()) {
3134       SDLoc DL(CP);
3135       EVT Ty = getPointerTy(DAG.getDataLayout());
3136       SDValue ConstPool = DAG.getTargetConstantPool(
3137           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3138       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3139     }
3140     setUsesTOCBasePtr(DAG);
3141     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3142     return getTOCEntry(DAG, SDLoc(CP), GA);
3143   }
3144 
3145   unsigned MOHiFlag, MOLoFlag;
3146   bool IsPIC = isPositionIndependent();
3147   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3148 
3149   if (IsPIC && Subtarget.isSVR4ABI()) {
3150     SDValue GA =
3151         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3152     return getTOCEntry(DAG, SDLoc(CP), GA);
3153   }
3154 
3155   SDValue CPIHi =
3156       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3157   SDValue CPILo =
3158       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3159   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3160 }
3161 
3162 // For 64-bit PowerPC, prefer the more compact relative encodings.
3163 // This trades 32 bits per jump table entry for one or two instructions
3164 // on the jump site.
3165 unsigned PPCTargetLowering::getJumpTableEncoding() const {
3166   if (isJumpTableRelative())
3167     return MachineJumpTableInfo::EK_LabelDifference32;
3168 
3169   return TargetLowering::getJumpTableEncoding();
3170 }
3171 
3172 bool PPCTargetLowering::isJumpTableRelative() const {
3173   if (UseAbsoluteJumpTables)
3174     return false;
3175   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3176     return true;
3177   return TargetLowering::isJumpTableRelative();
3178 }
3179 
3180 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
3181                                                     SelectionDAG &DAG) const {
3182   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3183     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3184 
3185   switch (getTargetMachine().getCodeModel()) {
3186   case CodeModel::Small:
3187   case CodeModel::Medium:
3188     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3189   default:
3190     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3191                        getPointerTy(DAG.getDataLayout()));
3192   }
3193 }
3194 
3195 const MCExpr *
3196 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
3197                                                 unsigned JTI,
3198                                                 MCContext &Ctx) const {
3199   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3200     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3201 
3202   switch (getTargetMachine().getCodeModel()) {
3203   case CodeModel::Small:
3204   case CodeModel::Medium:
3205     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3206   default:
3207     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3208   }
3209 }
3210 
3211 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3212   EVT PtrVT = Op.getValueType();
3213   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3214 
3215   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3216   if (Subtarget.isUsingPCRelativeCalls()) {
3217     SDLoc DL(JT);
3218     EVT Ty = getPointerTy(DAG.getDataLayout());
3219     SDValue GA =
3220         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3221     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3222     return MatAddr;
3223   }
3224 
3225   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3226   // The actual address of the GlobalValue is stored in the TOC.
3227   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3228     setUsesTOCBasePtr(DAG);
3229     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3230     return getTOCEntry(DAG, SDLoc(JT), GA);
3231   }
3232 
3233   unsigned MOHiFlag, MOLoFlag;
3234   bool IsPIC = isPositionIndependent();
3235   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3236 
3237   if (IsPIC && Subtarget.isSVR4ABI()) {
3238     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3239                                         PPCII::MO_PIC_FLAG);
3240     return getTOCEntry(DAG, SDLoc(GA), GA);
3241   }
3242 
3243   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3244   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3245   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3246 }
3247 
3248 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3249                                              SelectionDAG &DAG) const {
3250   EVT PtrVT = Op.getValueType();
3251   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3252   const BlockAddress *BA = BASDN->getBlockAddress();
3253 
3254   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3255   if (Subtarget.isUsingPCRelativeCalls()) {
3256     SDLoc DL(BASDN);
3257     EVT Ty = getPointerTy(DAG.getDataLayout());
3258     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3259                                            PPCII::MO_PCREL_FLAG);
3260     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3261     return MatAddr;
3262   }
3263 
3264   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3265   // The actual BlockAddress is stored in the TOC.
3266   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3267     setUsesTOCBasePtr(DAG);
3268     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3269     return getTOCEntry(DAG, SDLoc(BASDN), GA);
3270   }
3271 
3272   // 32-bit position-independent ELF stores the BlockAddress in the .got.
3273   if (Subtarget.is32BitELFABI() && isPositionIndependent())
3274     return getTOCEntry(
3275         DAG, SDLoc(BASDN),
3276         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3277 
3278   unsigned MOHiFlag, MOLoFlag;
3279   bool IsPIC = isPositionIndependent();
3280   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3281   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3282   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3283   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3284 }
3285 
3286 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3287                                               SelectionDAG &DAG) const {
3288   if (Subtarget.isAIXABI())
3289     return LowerGlobalTLSAddressAIX(Op, DAG);
3290 
3291   return LowerGlobalTLSAddressLinux(Op, DAG);
3292 }
3293 
3294 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3295                                                     SelectionDAG &DAG) const {
3296   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3297 
3298   if (DAG.getTarget().useEmulatedTLS())
3299     report_fatal_error("Emulated TLS is not yet supported on AIX");
3300 
3301   SDLoc dl(GA);
3302   const GlobalValue *GV = GA->getGlobal();
3303   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3304 
3305   // The general-dynamic model is the only access model supported for now, so
3306   // all the GlobalTLSAddress nodes are lowered with this model.
3307   // We need to generate two TOC entries, one for the variable offset, one for
3308   // the region handle. The global address for the TOC entry of the region
3309   // handle is created with the MO_TLSGDM_FLAG flag and the global address
3310   // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3311   SDValue VariableOffsetTGA =
3312       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3313   SDValue RegionHandleTGA =
3314       DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3315   SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3316   SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3317   return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3318                      RegionHandle);
3319 }
3320 
3321 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3322                                                       SelectionDAG &DAG) const {
3323   // FIXME: TLS addresses currently use medium model code sequences,
3324   // which is the most useful form.  Eventually support for small and
3325   // large models could be added if users need it, at the cost of
3326   // additional complexity.
3327   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3328   if (DAG.getTarget().useEmulatedTLS())
3329     return LowerToTLSEmulatedModel(GA, DAG);
3330 
3331   SDLoc dl(GA);
3332   const GlobalValue *GV = GA->getGlobal();
3333   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3334   bool is64bit = Subtarget.isPPC64();
3335   const Module *M = DAG.getMachineFunction().getFunction().getParent();
3336   PICLevel::Level picLevel = M->getPICLevel();
3337 
3338   const TargetMachine &TM = getTargetMachine();
3339   TLSModel::Model Model = TM.getTLSModel(GV);
3340 
3341   if (Model == TLSModel::LocalExec) {
3342     if (Subtarget.isUsingPCRelativeCalls()) {
3343       SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3344       SDValue TGA = DAG.getTargetGlobalAddress(
3345           GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3346       SDValue MatAddr =
3347           DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3348       return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3349     }
3350 
3351     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3352                                                PPCII::MO_TPREL_HA);
3353     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3354                                                PPCII::MO_TPREL_LO);
3355     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3356                              : DAG.getRegister(PPC::R2, MVT::i32);
3357 
3358     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3359     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3360   }
3361 
3362   if (Model == TLSModel::InitialExec) {
3363     bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3364     SDValue TGA = DAG.getTargetGlobalAddress(
3365         GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3366     SDValue TGATLS = DAG.getTargetGlobalAddress(
3367         GV, dl, PtrVT, 0,
3368         IsPCRel ? (PPCII::MO_TLS | PPCII::MO_PCREL_FLAG) : PPCII::MO_TLS);
3369     SDValue TPOffset;
3370     if (IsPCRel) {
3371       SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3372       TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3373                              MachinePointerInfo());
3374     } else {
3375       SDValue GOTPtr;
3376       if (is64bit) {
3377         setUsesTOCBasePtr(DAG);
3378         SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3379         GOTPtr =
3380             DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3381       } else {
3382         if (!TM.isPositionIndependent())
3383           GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3384         else if (picLevel == PICLevel::SmallPIC)
3385           GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3386         else
3387           GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3388       }
3389       TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3390     }
3391     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3392   }
3393 
3394   if (Model == TLSModel::GeneralDynamic) {
3395     if (Subtarget.isUsingPCRelativeCalls()) {
3396       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3397                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3398       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3399     }
3400 
3401     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3402     SDValue GOTPtr;
3403     if (is64bit) {
3404       setUsesTOCBasePtr(DAG);
3405       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3406       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3407                                    GOTReg, TGA);
3408     } else {
3409       if (picLevel == PICLevel::SmallPIC)
3410         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3411       else
3412         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3413     }
3414     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3415                        GOTPtr, TGA, TGA);
3416   }
3417 
3418   if (Model == TLSModel::LocalDynamic) {
3419     if (Subtarget.isUsingPCRelativeCalls()) {
3420       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3421                                                PPCII::MO_GOT_TLSLD_PCREL_FLAG);
3422       SDValue MatPCRel =
3423           DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3424       return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3425     }
3426 
3427     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3428     SDValue GOTPtr;
3429     if (is64bit) {
3430       setUsesTOCBasePtr(DAG);
3431       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3432       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3433                            GOTReg, TGA);
3434     } else {
3435       if (picLevel == PICLevel::SmallPIC)
3436         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3437       else
3438         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3439     }
3440     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3441                                   PtrVT, GOTPtr, TGA, TGA);
3442     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3443                                       PtrVT, TLSAddr, TGA);
3444     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3445   }
3446 
3447   llvm_unreachable("Unknown TLS model!");
3448 }
3449 
3450 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3451                                               SelectionDAG &DAG) const {
3452   EVT PtrVT = Op.getValueType();
3453   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3454   SDLoc DL(GSDN);
3455   const GlobalValue *GV = GSDN->getGlobal();
3456 
3457   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3458   // The actual address of the GlobalValue is stored in the TOC.
3459   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3460     if (Subtarget.isUsingPCRelativeCalls()) {
3461       EVT Ty = getPointerTy(DAG.getDataLayout());
3462       if (isAccessedAsGotIndirect(Op)) {
3463         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3464                                                 PPCII::MO_PCREL_FLAG |
3465                                                     PPCII::MO_GOT_FLAG);
3466         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3467         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3468                                    MachinePointerInfo());
3469         return Load;
3470       } else {
3471         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3472                                                 PPCII::MO_PCREL_FLAG);
3473         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3474       }
3475     }
3476     setUsesTOCBasePtr(DAG);
3477     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3478     return getTOCEntry(DAG, DL, GA);
3479   }
3480 
3481   unsigned MOHiFlag, MOLoFlag;
3482   bool IsPIC = isPositionIndependent();
3483   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3484 
3485   if (IsPIC && Subtarget.isSVR4ABI()) {
3486     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3487                                             GSDN->getOffset(),
3488                                             PPCII::MO_PIC_FLAG);
3489     return getTOCEntry(DAG, DL, GA);
3490   }
3491 
3492   SDValue GAHi =
3493     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3494   SDValue GALo =
3495     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3496 
3497   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3498 }
3499 
3500 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3501   bool IsStrict = Op->isStrictFPOpcode();
3502   ISD::CondCode CC =
3503       cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3504   SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3505   SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3506   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3507   EVT LHSVT = LHS.getValueType();
3508   SDLoc dl(Op);
3509 
3510   // Soften the setcc with libcall if it is fp128.
3511   if (LHSVT == MVT::f128) {
3512     assert(!Subtarget.hasP9Vector() &&
3513            "SETCC for f128 is already legal under Power9!");
3514     softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3515                         Op->getOpcode() == ISD::STRICT_FSETCCS);
3516     if (RHS.getNode())
3517       LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3518                         DAG.getCondCode(CC));
3519     if (IsStrict)
3520       return DAG.getMergeValues({LHS, Chain}, dl);
3521     return LHS;
3522   }
3523 
3524   assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3525 
3526   if (Op.getValueType() == MVT::v2i64) {
3527     // When the operands themselves are v2i64 values, we need to do something
3528     // special because VSX has no underlying comparison operations for these.
3529     if (LHS.getValueType() == MVT::v2i64) {
3530       // Equality can be handled by casting to the legal type for Altivec
3531       // comparisons, everything else needs to be expanded.
3532       if (CC != ISD::SETEQ && CC != ISD::SETNE)
3533         return SDValue();
3534       SDValue SetCC32 = DAG.getSetCC(
3535           dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3536           DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3537       int ShuffV[] = {1, 0, 3, 2};
3538       SDValue Shuff =
3539           DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3540       return DAG.getBitcast(MVT::v2i64,
3541                             DAG.getNode(CC == ISD::SETEQ ? ISD::AND : ISD::OR,
3542                                         dl, MVT::v4i32, Shuff, SetCC32));
3543     }
3544 
3545     // We handle most of these in the usual way.
3546     return Op;
3547   }
3548 
3549   // If we're comparing for equality to zero, expose the fact that this is
3550   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3551   // fold the new nodes.
3552   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3553     return V;
3554 
3555   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3556     // Leave comparisons against 0 and -1 alone for now, since they're usually
3557     // optimized.  FIXME: revisit this when we can custom lower all setcc
3558     // optimizations.
3559     if (C->isAllOnes() || C->isZero())
3560       return SDValue();
3561   }
3562 
3563   // If we have an integer seteq/setne, turn it into a compare against zero
3564   // by xor'ing the rhs with the lhs, which is faster than setting a
3565   // condition register, reading it back out, and masking the correct bit.  The
3566   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3567   // the result to other bit-twiddling opportunities.
3568   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3569     EVT VT = Op.getValueType();
3570     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3571     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3572   }
3573   return SDValue();
3574 }
3575 
3576 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3577   SDNode *Node = Op.getNode();
3578   EVT VT = Node->getValueType(0);
3579   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3580   SDValue InChain = Node->getOperand(0);
3581   SDValue VAListPtr = Node->getOperand(1);
3582   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3583   SDLoc dl(Node);
3584 
3585   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3586 
3587   // gpr_index
3588   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3589                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3590   InChain = GprIndex.getValue(1);
3591 
3592   if (VT == MVT::i64) {
3593     // Check if GprIndex is even
3594     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3595                                  DAG.getConstant(1, dl, MVT::i32));
3596     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3597                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3598     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3599                                           DAG.getConstant(1, dl, MVT::i32));
3600     // Align GprIndex to be even if it isn't
3601     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3602                            GprIndex);
3603   }
3604 
3605   // fpr index is 1 byte after gpr
3606   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3607                                DAG.getConstant(1, dl, MVT::i32));
3608 
3609   // fpr
3610   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3611                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3612   InChain = FprIndex.getValue(1);
3613 
3614   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3615                                        DAG.getConstant(8, dl, MVT::i32));
3616 
3617   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3618                                         DAG.getConstant(4, dl, MVT::i32));
3619 
3620   // areas
3621   SDValue OverflowArea =
3622       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3623   InChain = OverflowArea.getValue(1);
3624 
3625   SDValue RegSaveArea =
3626       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3627   InChain = RegSaveArea.getValue(1);
3628 
3629   // select overflow_area if index > 8
3630   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3631                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3632 
3633   // adjustment constant gpr_index * 4/8
3634   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3635                                     VT.isInteger() ? GprIndex : FprIndex,
3636                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3637                                                     MVT::i32));
3638 
3639   // OurReg = RegSaveArea + RegConstant
3640   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3641                                RegConstant);
3642 
3643   // Floating types are 32 bytes into RegSaveArea
3644   if (VT.isFloatingPoint())
3645     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3646                          DAG.getConstant(32, dl, MVT::i32));
3647 
3648   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3649   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3650                                    VT.isInteger() ? GprIndex : FprIndex,
3651                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3652                                                    MVT::i32));
3653 
3654   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3655                               VT.isInteger() ? VAListPtr : FprPtr,
3656                               MachinePointerInfo(SV), MVT::i8);
3657 
3658   // determine if we should load from reg_save_area or overflow_area
3659   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3660 
3661   // increase overflow_area by 4/8 if gpr/fpr > 8
3662   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3663                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3664                                           dl, MVT::i32));
3665 
3666   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3667                              OverflowAreaPlusN);
3668 
3669   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3670                               MachinePointerInfo(), MVT::i32);
3671 
3672   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3673 }
3674 
3675 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3676   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3677 
3678   // We have to copy the entire va_list struct:
3679   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3680   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3681                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3682                        false, true, false, MachinePointerInfo(),
3683                        MachinePointerInfo());
3684 }
3685 
3686 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3687                                                   SelectionDAG &DAG) const {
3688   if (Subtarget.isAIXABI())
3689     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3690 
3691   return Op.getOperand(0);
3692 }
3693 
3694 SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3695   MachineFunction &MF = DAG.getMachineFunction();
3696   PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3697 
3698   assert((Op.getOpcode() == ISD::INLINEASM ||
3699           Op.getOpcode() == ISD::INLINEASM_BR) &&
3700          "Expecting Inline ASM node.");
3701 
3702   // If an LR store is already known to be required then there is not point in
3703   // checking this ASM as well.
3704   if (MFI.isLRStoreRequired())
3705     return Op;
3706 
3707   // Inline ASM nodes have an optional last operand that is an incoming Flag of
3708   // type MVT::Glue. We want to ignore this last operand if that is the case.
3709   unsigned NumOps = Op.getNumOperands();
3710   if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3711     --NumOps;
3712 
3713   // Check all operands that may contain the LR.
3714   for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3715     unsigned Flags = cast<ConstantSDNode>(Op.getOperand(i))->getZExtValue();
3716     unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
3717     ++i; // Skip the ID value.
3718 
3719     switch (InlineAsm::getKind(Flags)) {
3720     default:
3721       llvm_unreachable("Bad flags!");
3722     case InlineAsm::Kind_RegUse:
3723     case InlineAsm::Kind_Imm:
3724     case InlineAsm::Kind_Mem:
3725       i += NumVals;
3726       break;
3727     case InlineAsm::Kind_Clobber:
3728     case InlineAsm::Kind_RegDef:
3729     case InlineAsm::Kind_RegDefEarlyClobber: {
3730       for (; NumVals; --NumVals, ++i) {
3731         Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3732         if (Reg != PPC::LR && Reg != PPC::LR8)
3733           continue;
3734         MFI.setLRStoreRequired();
3735         return Op;
3736       }
3737       break;
3738     }
3739     }
3740   }
3741 
3742   return Op;
3743 }
3744 
3745 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3746                                                 SelectionDAG &DAG) const {
3747   if (Subtarget.isAIXABI())
3748     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3749 
3750   SDValue Chain = Op.getOperand(0);
3751   SDValue Trmp = Op.getOperand(1); // trampoline
3752   SDValue FPtr = Op.getOperand(2); // nested function
3753   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3754   SDLoc dl(Op);
3755 
3756   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3757   bool isPPC64 = (PtrVT == MVT::i64);
3758   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3759 
3760   TargetLowering::ArgListTy Args;
3761   TargetLowering::ArgListEntry Entry;
3762 
3763   Entry.Ty = IntPtrTy;
3764   Entry.Node = Trmp; Args.push_back(Entry);
3765 
3766   // TrampSize == (isPPC64 ? 48 : 40);
3767   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3768                                isPPC64 ? MVT::i64 : MVT::i32);
3769   Args.push_back(Entry);
3770 
3771   Entry.Node = FPtr; Args.push_back(Entry);
3772   Entry.Node = Nest; Args.push_back(Entry);
3773 
3774   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3775   TargetLowering::CallLoweringInfo CLI(DAG);
3776   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3777       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3778       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3779 
3780   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3781   return CallResult.second;
3782 }
3783 
3784 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3785   MachineFunction &MF = DAG.getMachineFunction();
3786   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3787   EVT PtrVT = getPointerTy(MF.getDataLayout());
3788 
3789   SDLoc dl(Op);
3790 
3791   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3792     // vastart just stores the address of the VarArgsFrameIndex slot into the
3793     // memory location argument.
3794     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3795     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3796     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3797                         MachinePointerInfo(SV));
3798   }
3799 
3800   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3801   // We suppose the given va_list is already allocated.
3802   //
3803   // typedef struct {
3804   //  char gpr;     /* index into the array of 8 GPRs
3805   //                 * stored in the register save area
3806   //                 * gpr=0 corresponds to r3,
3807   //                 * gpr=1 to r4, etc.
3808   //                 */
3809   //  char fpr;     /* index into the array of 8 FPRs
3810   //                 * stored in the register save area
3811   //                 * fpr=0 corresponds to f1,
3812   //                 * fpr=1 to f2, etc.
3813   //                 */
3814   //  char *overflow_arg_area;
3815   //                /* location on stack that holds
3816   //                 * the next overflow argument
3817   //                 */
3818   //  char *reg_save_area;
3819   //               /* where r3:r10 and f1:f8 (if saved)
3820   //                * are stored
3821   //                */
3822   // } va_list[1];
3823 
3824   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3825   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3826   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3827                                             PtrVT);
3828   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3829                                  PtrVT);
3830 
3831   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3832   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3833 
3834   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3835   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3836 
3837   uint64_t FPROffset = 1;
3838   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3839 
3840   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3841 
3842   // Store first byte : number of int regs
3843   SDValue firstStore =
3844       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3845                         MachinePointerInfo(SV), MVT::i8);
3846   uint64_t nextOffset = FPROffset;
3847   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3848                                   ConstFPROffset);
3849 
3850   // Store second byte : number of float regs
3851   SDValue secondStore =
3852       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3853                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3854   nextOffset += StackOffset;
3855   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3856 
3857   // Store second word : arguments given on stack
3858   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3859                                     MachinePointerInfo(SV, nextOffset));
3860   nextOffset += FrameOffset;
3861   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3862 
3863   // Store third word : arguments given in registers
3864   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3865                       MachinePointerInfo(SV, nextOffset));
3866 }
3867 
3868 /// FPR - The set of FP registers that should be allocated for arguments
3869 /// on Darwin and AIX.
3870 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3871                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3872                                 PPC::F11, PPC::F12, PPC::F13};
3873 
3874 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3875 /// the stack.
3876 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3877                                        unsigned PtrByteSize) {
3878   unsigned ArgSize = ArgVT.getStoreSize();
3879   if (Flags.isByVal())
3880     ArgSize = Flags.getByValSize();
3881 
3882   // Round up to multiples of the pointer size, except for array members,
3883   // which are always packed.
3884   if (!Flags.isInConsecutiveRegs())
3885     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3886 
3887   return ArgSize;
3888 }
3889 
3890 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3891 /// on the stack.
3892 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3893                                          ISD::ArgFlagsTy Flags,
3894                                          unsigned PtrByteSize) {
3895   Align Alignment(PtrByteSize);
3896 
3897   // Altivec parameters are padded to a 16 byte boundary.
3898   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3899       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3900       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3901       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3902     Alignment = Align(16);
3903 
3904   // ByVal parameters are aligned as requested.
3905   if (Flags.isByVal()) {
3906     auto BVAlign = Flags.getNonZeroByValAlign();
3907     if (BVAlign > PtrByteSize) {
3908       if (BVAlign.value() % PtrByteSize != 0)
3909         llvm_unreachable(
3910             "ByVal alignment is not a multiple of the pointer size");
3911 
3912       Alignment = BVAlign;
3913     }
3914   }
3915 
3916   // Array members are always packed to their original alignment.
3917   if (Flags.isInConsecutiveRegs()) {
3918     // If the array member was split into multiple registers, the first
3919     // needs to be aligned to the size of the full type.  (Except for
3920     // ppcf128, which is only aligned as its f64 components.)
3921     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3922       Alignment = Align(OrigVT.getStoreSize());
3923     else
3924       Alignment = Align(ArgVT.getStoreSize());
3925   }
3926 
3927   return Alignment;
3928 }
3929 
3930 /// CalculateStackSlotUsed - Return whether this argument will use its
3931 /// stack slot (instead of being passed in registers).  ArgOffset,
3932 /// AvailableFPRs, and AvailableVRs must hold the current argument
3933 /// position, and will be updated to account for this argument.
3934 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3935                                    unsigned PtrByteSize, unsigned LinkageSize,
3936                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3937                                    unsigned &AvailableFPRs,
3938                                    unsigned &AvailableVRs) {
3939   bool UseMemory = false;
3940 
3941   // Respect alignment of argument on the stack.
3942   Align Alignment =
3943       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3944   ArgOffset = alignTo(ArgOffset, Alignment);
3945   // If there's no space left in the argument save area, we must
3946   // use memory (this check also catches zero-sized arguments).
3947   if (ArgOffset >= LinkageSize + ParamAreaSize)
3948     UseMemory = true;
3949 
3950   // Allocate argument on the stack.
3951   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3952   if (Flags.isInConsecutiveRegsLast())
3953     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3954   // If we overran the argument save area, we must use memory
3955   // (this check catches arguments passed partially in memory)
3956   if (ArgOffset > LinkageSize + ParamAreaSize)
3957     UseMemory = true;
3958 
3959   // However, if the argument is actually passed in an FPR or a VR,
3960   // we don't use memory after all.
3961   if (!Flags.isByVal()) {
3962     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3963       if (AvailableFPRs > 0) {
3964         --AvailableFPRs;
3965         return false;
3966       }
3967     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3968         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3969         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3970         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3971       if (AvailableVRs > 0) {
3972         --AvailableVRs;
3973         return false;
3974       }
3975   }
3976 
3977   return UseMemory;
3978 }
3979 
3980 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3981 /// ensure minimum alignment required for target.
3982 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3983                                      unsigned NumBytes) {
3984   return alignTo(NumBytes, Lowering->getStackAlign());
3985 }
3986 
3987 SDValue PPCTargetLowering::LowerFormalArguments(
3988     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3989     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3990     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3991   if (Subtarget.isAIXABI())
3992     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3993                                     InVals);
3994   if (Subtarget.is64BitELFABI())
3995     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3996                                        InVals);
3997   assert(Subtarget.is32BitELFABI());
3998   return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3999                                      InVals);
4000 }
4001 
4002 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4003     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4004     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4005     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4006 
4007   // 32-bit SVR4 ABI Stack Frame Layout:
4008   //              +-----------------------------------+
4009   //        +-->  |            Back chain             |
4010   //        |     +-----------------------------------+
4011   //        |     | Floating-point register save area |
4012   //        |     +-----------------------------------+
4013   //        |     |    General register save area     |
4014   //        |     +-----------------------------------+
4015   //        |     |          CR save word             |
4016   //        |     +-----------------------------------+
4017   //        |     |         VRSAVE save word          |
4018   //        |     +-----------------------------------+
4019   //        |     |         Alignment padding         |
4020   //        |     +-----------------------------------+
4021   //        |     |     Vector register save area     |
4022   //        |     +-----------------------------------+
4023   //        |     |       Local variable space        |
4024   //        |     +-----------------------------------+
4025   //        |     |        Parameter list area        |
4026   //        |     +-----------------------------------+
4027   //        |     |           LR save word            |
4028   //        |     +-----------------------------------+
4029   // SP-->  +---  |            Back chain             |
4030   //              +-----------------------------------+
4031   //
4032   // Specifications:
4033   //   System V Application Binary Interface PowerPC Processor Supplement
4034   //   AltiVec Technology Programming Interface Manual
4035 
4036   MachineFunction &MF = DAG.getMachineFunction();
4037   MachineFrameInfo &MFI = MF.getFrameInfo();
4038   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4039 
4040   EVT PtrVT = getPointerTy(MF.getDataLayout());
4041   // Potential tail calls could cause overwriting of argument stack slots.
4042   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4043                        (CallConv == CallingConv::Fast));
4044   const Align PtrAlign(4);
4045 
4046   // Assign locations to all of the incoming arguments.
4047   SmallVector<CCValAssign, 16> ArgLocs;
4048   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4049                  *DAG.getContext());
4050 
4051   // Reserve space for the linkage area on the stack.
4052   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4053   CCInfo.AllocateStack(LinkageSize, PtrAlign);
4054   if (useSoftFloat())
4055     CCInfo.PreAnalyzeFormalArguments(Ins);
4056 
4057   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4058   CCInfo.clearWasPPCF128();
4059 
4060   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4061     CCValAssign &VA = ArgLocs[i];
4062 
4063     // Arguments stored in registers.
4064     if (VA.isRegLoc()) {
4065       const TargetRegisterClass *RC;
4066       EVT ValVT = VA.getValVT();
4067 
4068       switch (ValVT.getSimpleVT().SimpleTy) {
4069         default:
4070           llvm_unreachable("ValVT not supported by formal arguments Lowering");
4071         case MVT::i1:
4072         case MVT::i32:
4073           RC = &PPC::GPRCRegClass;
4074           break;
4075         case MVT::f32:
4076           if (Subtarget.hasP8Vector())
4077             RC = &PPC::VSSRCRegClass;
4078           else if (Subtarget.hasSPE())
4079             RC = &PPC::GPRCRegClass;
4080           else
4081             RC = &PPC::F4RCRegClass;
4082           break;
4083         case MVT::f64:
4084           if (Subtarget.hasVSX())
4085             RC = &PPC::VSFRCRegClass;
4086           else if (Subtarget.hasSPE())
4087             // SPE passes doubles in GPR pairs.
4088             RC = &PPC::GPRCRegClass;
4089           else
4090             RC = &PPC::F8RCRegClass;
4091           break;
4092         case MVT::v16i8:
4093         case MVT::v8i16:
4094         case MVT::v4i32:
4095           RC = &PPC::VRRCRegClass;
4096           break;
4097         case MVT::v4f32:
4098           RC = &PPC::VRRCRegClass;
4099           break;
4100         case MVT::v2f64:
4101         case MVT::v2i64:
4102           RC = &PPC::VRRCRegClass;
4103           break;
4104       }
4105 
4106       SDValue ArgValue;
4107       // Transform the arguments stored in physical registers into
4108       // virtual ones.
4109       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4110         assert(i + 1 < e && "No second half of double precision argument");
4111         Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4112         Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4113         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4114         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4115         if (!Subtarget.isLittleEndian())
4116           std::swap (ArgValueLo, ArgValueHi);
4117         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4118                                ArgValueHi);
4119       } else {
4120         Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4121         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4122                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
4123         if (ValVT == MVT::i1)
4124           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4125       }
4126 
4127       InVals.push_back(ArgValue);
4128     } else {
4129       // Argument stored in memory.
4130       assert(VA.isMemLoc());
4131 
4132       // Get the extended size of the argument type in stack
4133       unsigned ArgSize = VA.getLocVT().getStoreSize();
4134       // Get the actual size of the argument type
4135       unsigned ObjSize = VA.getValVT().getStoreSize();
4136       unsigned ArgOffset = VA.getLocMemOffset();
4137       // Stack objects in PPC32 are right justified.
4138       ArgOffset += ArgSize - ObjSize;
4139       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4140 
4141       // Create load nodes to retrieve arguments from the stack.
4142       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4143       InVals.push_back(
4144           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4145     }
4146   }
4147 
4148   // Assign locations to all of the incoming aggregate by value arguments.
4149   // Aggregates passed by value are stored in the local variable space of the
4150   // caller's stack frame, right above the parameter list area.
4151   SmallVector<CCValAssign, 16> ByValArgLocs;
4152   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4153                       ByValArgLocs, *DAG.getContext());
4154 
4155   // Reserve stack space for the allocations in CCInfo.
4156   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
4157 
4158   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4159 
4160   // Area that is at least reserved in the caller of this function.
4161   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
4162   MinReservedArea = std::max(MinReservedArea, LinkageSize);
4163 
4164   // Set the size that is at least reserved in caller of this function.  Tail
4165   // call optimized function's reserved stack space needs to be aligned so that
4166   // taking the difference between two stack areas will result in an aligned
4167   // stack.
4168   MinReservedArea =
4169       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4170   FuncInfo->setMinReservedArea(MinReservedArea);
4171 
4172   SmallVector<SDValue, 8> MemOps;
4173 
4174   // If the function takes variable number of arguments, make a frame index for
4175   // the start of the first vararg value... for expansion of llvm.va_start.
4176   if (isVarArg) {
4177     static const MCPhysReg GPArgRegs[] = {
4178       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4179       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4180     };
4181     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
4182 
4183     static const MCPhysReg FPArgRegs[] = {
4184       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4185       PPC::F8
4186     };
4187     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
4188 
4189     if (useSoftFloat() || hasSPE())
4190        NumFPArgRegs = 0;
4191 
4192     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4193     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4194 
4195     // Make room for NumGPArgRegs and NumFPArgRegs.
4196     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4197                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4198 
4199     FuncInfo->setVarArgsStackOffset(
4200       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4201                             CCInfo.getNextStackOffset(), true));
4202 
4203     FuncInfo->setVarArgsFrameIndex(
4204         MFI.CreateStackObject(Depth, Align(8), false));
4205     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4206 
4207     // The fixed integer arguments of a variadic function are stored to the
4208     // VarArgsFrameIndex on the stack so that they may be loaded by
4209     // dereferencing the result of va_next.
4210     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
4211       // Get an existing live-in vreg, or add a new one.
4212       Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
4213       if (!VReg)
4214         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
4215 
4216       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4217       SDValue Store =
4218           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4219       MemOps.push_back(Store);
4220       // Increment the address by four for the next argument to store
4221       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4222       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4223     }
4224 
4225     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4226     // is set.
4227     // The double arguments are stored to the VarArgsFrameIndex
4228     // on the stack.
4229     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4230       // Get an existing live-in vreg, or add a new one.
4231       Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4232       if (!VReg)
4233         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4234 
4235       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4236       SDValue Store =
4237           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4238       MemOps.push_back(Store);
4239       // Increment the address by eight for the next argument to store
4240       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4241                                          PtrVT);
4242       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4243     }
4244   }
4245 
4246   if (!MemOps.empty())
4247     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4248 
4249   return Chain;
4250 }
4251 
4252 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4253 // value to MVT::i64 and then truncate to the correct register size.
4254 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4255                                              EVT ObjectVT, SelectionDAG &DAG,
4256                                              SDValue ArgVal,
4257                                              const SDLoc &dl) const {
4258   if (Flags.isSExt())
4259     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4260                          DAG.getValueType(ObjectVT));
4261   else if (Flags.isZExt())
4262     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4263                          DAG.getValueType(ObjectVT));
4264 
4265   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4266 }
4267 
4268 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4269     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4270     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4271     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4272   // TODO: add description of PPC stack frame format, or at least some docs.
4273   //
4274   bool isELFv2ABI = Subtarget.isELFv2ABI();
4275   bool isLittleEndian = Subtarget.isLittleEndian();
4276   MachineFunction &MF = DAG.getMachineFunction();
4277   MachineFrameInfo &MFI = MF.getFrameInfo();
4278   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4279 
4280   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4281          "fastcc not supported on varargs functions");
4282 
4283   EVT PtrVT = getPointerTy(MF.getDataLayout());
4284   // Potential tail calls could cause overwriting of argument stack slots.
4285   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4286                        (CallConv == CallingConv::Fast));
4287   unsigned PtrByteSize = 8;
4288   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4289 
4290   static const MCPhysReg GPR[] = {
4291     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4292     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4293   };
4294   static const MCPhysReg VR[] = {
4295     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4296     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4297   };
4298 
4299   const unsigned Num_GPR_Regs = array_lengthof(GPR);
4300   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4301   const unsigned Num_VR_Regs  = array_lengthof(VR);
4302 
4303   // Do a first pass over the arguments to determine whether the ABI
4304   // guarantees that our caller has allocated the parameter save area
4305   // on its stack frame.  In the ELFv1 ABI, this is always the case;
4306   // in the ELFv2 ABI, it is true if this is a vararg function or if
4307   // any parameter is located in a stack slot.
4308 
4309   bool HasParameterArea = !isELFv2ABI || isVarArg;
4310   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4311   unsigned NumBytes = LinkageSize;
4312   unsigned AvailableFPRs = Num_FPR_Regs;
4313   unsigned AvailableVRs = Num_VR_Regs;
4314   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
4315     if (Ins[i].Flags.isNest())
4316       continue;
4317 
4318     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
4319                                PtrByteSize, LinkageSize, ParamAreaSize,
4320                                NumBytes, AvailableFPRs, AvailableVRs))
4321       HasParameterArea = true;
4322   }
4323 
4324   // Add DAG nodes to load the arguments or copy them out of registers.  On
4325   // entry to a function on PPC, the arguments start after the linkage area,
4326   // although the first ones are often in registers.
4327 
4328   unsigned ArgOffset = LinkageSize;
4329   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4330   SmallVector<SDValue, 8> MemOps;
4331   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4332   unsigned CurArgIdx = 0;
4333   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4334     SDValue ArgVal;
4335     bool needsLoad = false;
4336     EVT ObjectVT = Ins[ArgNo].VT;
4337     EVT OrigVT = Ins[ArgNo].ArgVT;
4338     unsigned ObjSize = ObjectVT.getStoreSize();
4339     unsigned ArgSize = ObjSize;
4340     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4341     if (Ins[ArgNo].isOrigArg()) {
4342       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4343       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4344     }
4345     // We re-align the argument offset for each argument, except when using the
4346     // fast calling convention, when we need to make sure we do that only when
4347     // we'll actually use a stack slot.
4348     unsigned CurArgOffset;
4349     Align Alignment;
4350     auto ComputeArgOffset = [&]() {
4351       /* Respect alignment of argument on the stack.  */
4352       Alignment =
4353           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4354       ArgOffset = alignTo(ArgOffset, Alignment);
4355       CurArgOffset = ArgOffset;
4356     };
4357 
4358     if (CallConv != CallingConv::Fast) {
4359       ComputeArgOffset();
4360 
4361       /* Compute GPR index associated with argument offset.  */
4362       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4363       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4364     }
4365 
4366     // FIXME the codegen can be much improved in some cases.
4367     // We do not have to keep everything in memory.
4368     if (Flags.isByVal()) {
4369       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4370 
4371       if (CallConv == CallingConv::Fast)
4372         ComputeArgOffset();
4373 
4374       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4375       ObjSize = Flags.getByValSize();
4376       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4377       // Empty aggregate parameters do not take up registers.  Examples:
4378       //   struct { } a;
4379       //   union  { } b;
4380       //   int c[0];
4381       // etc.  However, we have to provide a place-holder in InVals, so
4382       // pretend we have an 8-byte item at the current address for that
4383       // purpose.
4384       if (!ObjSize) {
4385         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4386         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4387         InVals.push_back(FIN);
4388         continue;
4389       }
4390 
4391       // Create a stack object covering all stack doublewords occupied
4392       // by the argument.  If the argument is (fully or partially) on
4393       // the stack, or if the argument is fully in registers but the
4394       // caller has allocated the parameter save anyway, we can refer
4395       // directly to the caller's stack frame.  Otherwise, create a
4396       // local copy in our own frame.
4397       int FI;
4398       if (HasParameterArea ||
4399           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4400         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4401       else
4402         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4403       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4404 
4405       // Handle aggregates smaller than 8 bytes.
4406       if (ObjSize < PtrByteSize) {
4407         // The value of the object is its address, which differs from the
4408         // address of the enclosing doubleword on big-endian systems.
4409         SDValue Arg = FIN;
4410         if (!isLittleEndian) {
4411           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4412           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4413         }
4414         InVals.push_back(Arg);
4415 
4416         if (GPR_idx != Num_GPR_Regs) {
4417           Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4418           FuncInfo->addLiveInAttr(VReg, Flags);
4419           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4420           EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4421           SDValue Store =
4422               DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4423                                 MachinePointerInfo(&*FuncArg), ObjType);
4424           MemOps.push_back(Store);
4425         }
4426         // Whether we copied from a register or not, advance the offset
4427         // into the parameter save area by a full doubleword.
4428         ArgOffset += PtrByteSize;
4429         continue;
4430       }
4431 
4432       // The value of the object is its address, which is the address of
4433       // its first stack doubleword.
4434       InVals.push_back(FIN);
4435 
4436       // Store whatever pieces of the object are in registers to memory.
4437       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4438         if (GPR_idx == Num_GPR_Regs)
4439           break;
4440 
4441         Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4442         FuncInfo->addLiveInAttr(VReg, Flags);
4443         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4444         SDValue Addr = FIN;
4445         if (j) {
4446           SDValue Off = DAG.getConstant(j, dl, PtrVT);
4447           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4448         }
4449         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
4450                                      MachinePointerInfo(&*FuncArg, j));
4451         MemOps.push_back(Store);
4452         ++GPR_idx;
4453       }
4454       ArgOffset += ArgSize;
4455       continue;
4456     }
4457 
4458     switch (ObjectVT.getSimpleVT().SimpleTy) {
4459     default: llvm_unreachable("Unhandled argument type!");
4460     case MVT::i1:
4461     case MVT::i32:
4462     case MVT::i64:
4463       if (Flags.isNest()) {
4464         // The 'nest' parameter, if any, is passed in R11.
4465         Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4466         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4467 
4468         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4469           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4470 
4471         break;
4472       }
4473 
4474       // These can be scalar arguments or elements of an integer array type
4475       // passed directly.  Clang may use those instead of "byval" aggregate
4476       // types to avoid forcing arguments to memory unnecessarily.
4477       if (GPR_idx != Num_GPR_Regs) {
4478         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4479         FuncInfo->addLiveInAttr(VReg, Flags);
4480         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4481 
4482         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4483           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4484           // value to MVT::i64 and then truncate to the correct register size.
4485           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4486       } else {
4487         if (CallConv == CallingConv::Fast)
4488           ComputeArgOffset();
4489 
4490         needsLoad = true;
4491         ArgSize = PtrByteSize;
4492       }
4493       if (CallConv != CallingConv::Fast || needsLoad)
4494         ArgOffset += 8;
4495       break;
4496 
4497     case MVT::f32:
4498     case MVT::f64:
4499       // These can be scalar arguments or elements of a float array type
4500       // passed directly.  The latter are used to implement ELFv2 homogenous
4501       // float aggregates.
4502       if (FPR_idx != Num_FPR_Regs) {
4503         unsigned VReg;
4504 
4505         if (ObjectVT == MVT::f32)
4506           VReg = MF.addLiveIn(FPR[FPR_idx],
4507                               Subtarget.hasP8Vector()
4508                                   ? &PPC::VSSRCRegClass
4509                                   : &PPC::F4RCRegClass);
4510         else
4511           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4512                                                 ? &PPC::VSFRCRegClass
4513                                                 : &PPC::F8RCRegClass);
4514 
4515         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4516         ++FPR_idx;
4517       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4518         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4519         // once we support fp <-> gpr moves.
4520 
4521         // This can only ever happen in the presence of f32 array types,
4522         // since otherwise we never run out of FPRs before running out
4523         // of GPRs.
4524         Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4525         FuncInfo->addLiveInAttr(VReg, Flags);
4526         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4527 
4528         if (ObjectVT == MVT::f32) {
4529           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4530             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4531                                  DAG.getConstant(32, dl, MVT::i32));
4532           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4533         }
4534 
4535         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4536       } else {
4537         if (CallConv == CallingConv::Fast)
4538           ComputeArgOffset();
4539 
4540         needsLoad = true;
4541       }
4542 
4543       // When passing an array of floats, the array occupies consecutive
4544       // space in the argument area; only round up to the next doubleword
4545       // at the end of the array.  Otherwise, each float takes 8 bytes.
4546       if (CallConv != CallingConv::Fast || needsLoad) {
4547         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4548         ArgOffset += ArgSize;
4549         if (Flags.isInConsecutiveRegsLast())
4550           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4551       }
4552       break;
4553     case MVT::v4f32:
4554     case MVT::v4i32:
4555     case MVT::v8i16:
4556     case MVT::v16i8:
4557     case MVT::v2f64:
4558     case MVT::v2i64:
4559     case MVT::v1i128:
4560     case MVT::f128:
4561       // These can be scalar arguments or elements of a vector array type
4562       // passed directly.  The latter are used to implement ELFv2 homogenous
4563       // vector aggregates.
4564       if (VR_idx != Num_VR_Regs) {
4565         Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4566         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4567         ++VR_idx;
4568       } else {
4569         if (CallConv == CallingConv::Fast)
4570           ComputeArgOffset();
4571         needsLoad = true;
4572       }
4573       if (CallConv != CallingConv::Fast || needsLoad)
4574         ArgOffset += 16;
4575       break;
4576     }
4577 
4578     // We need to load the argument to a virtual register if we determined
4579     // above that we ran out of physical registers of the appropriate type.
4580     if (needsLoad) {
4581       if (ObjSize < ArgSize && !isLittleEndian)
4582         CurArgOffset += ArgSize - ObjSize;
4583       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4584       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4585       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4586     }
4587 
4588     InVals.push_back(ArgVal);
4589   }
4590 
4591   // Area that is at least reserved in the caller of this function.
4592   unsigned MinReservedArea;
4593   if (HasParameterArea)
4594     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4595   else
4596     MinReservedArea = LinkageSize;
4597 
4598   // Set the size that is at least reserved in caller of this function.  Tail
4599   // call optimized functions' reserved stack space needs to be aligned so that
4600   // taking the difference between two stack areas will result in an aligned
4601   // stack.
4602   MinReservedArea =
4603       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4604   FuncInfo->setMinReservedArea(MinReservedArea);
4605 
4606   // If the function takes variable number of arguments, make a frame index for
4607   // the start of the first vararg value... for expansion of llvm.va_start.
4608   // On ELFv2ABI spec, it writes:
4609   // C programs that are intended to be *portable* across different compilers
4610   // and architectures must use the header file <stdarg.h> to deal with variable
4611   // argument lists.
4612   if (isVarArg && MFI.hasVAStart()) {
4613     int Depth = ArgOffset;
4614 
4615     FuncInfo->setVarArgsFrameIndex(
4616       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4617     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4618 
4619     // If this function is vararg, store any remaining integer argument regs
4620     // to their spots on the stack so that they may be loaded by dereferencing
4621     // the result of va_next.
4622     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4623          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4624       Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4625       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4626       SDValue Store =
4627           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4628       MemOps.push_back(Store);
4629       // Increment the address by four for the next argument to store
4630       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4631       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4632     }
4633   }
4634 
4635   if (!MemOps.empty())
4636     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4637 
4638   return Chain;
4639 }
4640 
4641 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4642 /// adjusted to accommodate the arguments for the tailcall.
4643 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4644                                    unsigned ParamSize) {
4645 
4646   if (!isTailCall) return 0;
4647 
4648   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4649   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4650   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4651   // Remember only if the new adjustment is bigger.
4652   if (SPDiff < FI->getTailCallSPDelta())
4653     FI->setTailCallSPDelta(SPDiff);
4654 
4655   return SPDiff;
4656 }
4657 
4658 static bool isFunctionGlobalAddress(SDValue Callee);
4659 
4660 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4661                               const TargetMachine &TM) {
4662   // It does not make sense to call callsShareTOCBase() with a caller that
4663   // is PC Relative since PC Relative callers do not have a TOC.
4664 #ifndef NDEBUG
4665   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4666   assert(!STICaller->isUsingPCRelativeCalls() &&
4667          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4668 #endif
4669 
4670   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4671   // don't have enough information to determine if the caller and callee share
4672   // the same  TOC base, so we have to pessimistically assume they don't for
4673   // correctness.
4674   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4675   if (!G)
4676     return false;
4677 
4678   const GlobalValue *GV = G->getGlobal();
4679 
4680   // If the callee is preemptable, then the static linker will use a plt-stub
4681   // which saves the toc to the stack, and needs a nop after the call
4682   // instruction to convert to a toc-restore.
4683   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4684     return false;
4685 
4686   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4687   // We may need a TOC restore in the situation where the caller requires a
4688   // valid TOC but the callee is PC Relative and does not.
4689   const Function *F = dyn_cast<Function>(GV);
4690   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4691 
4692   // If we have an Alias we can try to get the function from there.
4693   if (Alias) {
4694     const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4695     F = dyn_cast<Function>(GlobalObj);
4696   }
4697 
4698   // If we still have no valid function pointer we do not have enough
4699   // information to determine if the callee uses PC Relative calls so we must
4700   // assume that it does.
4701   if (!F)
4702     return false;
4703 
4704   // If the callee uses PC Relative we cannot guarantee that the callee won't
4705   // clobber the TOC of the caller and so we must assume that the two
4706   // functions do not share a TOC base.
4707   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4708   if (STICallee->isUsingPCRelativeCalls())
4709     return false;
4710 
4711   // If the GV is not a strong definition then we need to assume it can be
4712   // replaced by another function at link time. The function that replaces
4713   // it may not share the same TOC as the caller since the callee may be
4714   // replaced by a PC Relative version of the same function.
4715   if (!GV->isStrongDefinitionForLinker())
4716     return false;
4717 
4718   // The medium and large code models are expected to provide a sufficiently
4719   // large TOC to provide all data addressing needs of a module with a
4720   // single TOC.
4721   if (CodeModel::Medium == TM.getCodeModel() ||
4722       CodeModel::Large == TM.getCodeModel())
4723     return true;
4724 
4725   // Any explicitly-specified sections and section prefixes must also match.
4726   // Also, if we're using -ffunction-sections, then each function is always in
4727   // a different section (the same is true for COMDAT functions).
4728   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4729       GV->getSection() != Caller->getSection())
4730     return false;
4731   if (const auto *F = dyn_cast<Function>(GV)) {
4732     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4733       return false;
4734   }
4735 
4736   return true;
4737 }
4738 
4739 static bool
4740 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4741                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4742   assert(Subtarget.is64BitELFABI());
4743 
4744   const unsigned PtrByteSize = 8;
4745   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4746 
4747   static const MCPhysReg GPR[] = {
4748     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4749     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4750   };
4751   static const MCPhysReg VR[] = {
4752     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4753     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4754   };
4755 
4756   const unsigned NumGPRs = array_lengthof(GPR);
4757   const unsigned NumFPRs = 13;
4758   const unsigned NumVRs = array_lengthof(VR);
4759   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4760 
4761   unsigned NumBytes = LinkageSize;
4762   unsigned AvailableFPRs = NumFPRs;
4763   unsigned AvailableVRs = NumVRs;
4764 
4765   for (const ISD::OutputArg& Param : Outs) {
4766     if (Param.Flags.isNest()) continue;
4767 
4768     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4769                                LinkageSize, ParamAreaSize, NumBytes,
4770                                AvailableFPRs, AvailableVRs))
4771       return true;
4772   }
4773   return false;
4774 }
4775 
4776 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4777   if (CB.arg_size() != CallerFn->arg_size())
4778     return false;
4779 
4780   auto CalleeArgIter = CB.arg_begin();
4781   auto CalleeArgEnd = CB.arg_end();
4782   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4783 
4784   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4785     const Value* CalleeArg = *CalleeArgIter;
4786     const Value* CallerArg = &(*CallerArgIter);
4787     if (CalleeArg == CallerArg)
4788       continue;
4789 
4790     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4791     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4792     //      }
4793     // 1st argument of callee is undef and has the same type as caller.
4794     if (CalleeArg->getType() == CallerArg->getType() &&
4795         isa<UndefValue>(CalleeArg))
4796       continue;
4797 
4798     return false;
4799   }
4800 
4801   return true;
4802 }
4803 
4804 // Returns true if TCO is possible between the callers and callees
4805 // calling conventions.
4806 static bool
4807 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4808                                     CallingConv::ID CalleeCC) {
4809   // Tail calls are possible with fastcc and ccc.
4810   auto isTailCallableCC  = [] (CallingConv::ID CC){
4811       return  CC == CallingConv::C || CC == CallingConv::Fast;
4812   };
4813   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4814     return false;
4815 
4816   // We can safely tail call both fastcc and ccc callees from a c calling
4817   // convention caller. If the caller is fastcc, we may have less stack space
4818   // than a non-fastcc caller with the same signature so disable tail-calls in
4819   // that case.
4820   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4821 }
4822 
4823 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4824     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4825     const SmallVectorImpl<ISD::OutputArg> &Outs,
4826     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4827   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4828 
4829   if (DisableSCO && !TailCallOpt) return false;
4830 
4831   // Variadic argument functions are not supported.
4832   if (isVarArg) return false;
4833 
4834   auto &Caller = DAG.getMachineFunction().getFunction();
4835   // Check that the calling conventions are compatible for tco.
4836   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4837     return false;
4838 
4839   // Caller contains any byval parameter is not supported.
4840   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4841     return false;
4842 
4843   // Callee contains any byval parameter is not supported, too.
4844   // Note: This is a quick work around, because in some cases, e.g.
4845   // caller's stack size > callee's stack size, we are still able to apply
4846   // sibling call optimization. For example, gcc is able to do SCO for caller1
4847   // in the following example, but not for caller2.
4848   //   struct test {
4849   //     long int a;
4850   //     char ary[56];
4851   //   } gTest;
4852   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4853   //     b->a = v.a;
4854   //     return 0;
4855   //   }
4856   //   void caller1(struct test a, struct test c, struct test *b) {
4857   //     callee(gTest, b); }
4858   //   void caller2(struct test *b) { callee(gTest, b); }
4859   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4860     return false;
4861 
4862   // If callee and caller use different calling conventions, we cannot pass
4863   // parameters on stack since offsets for the parameter area may be different.
4864   if (Caller.getCallingConv() != CalleeCC &&
4865       needStackSlotPassParameters(Subtarget, Outs))
4866     return false;
4867 
4868   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4869   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4870   // callee potentially have different TOC bases then we cannot tail call since
4871   // we need to restore the TOC pointer after the call.
4872   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4873   // We cannot guarantee this for indirect calls or calls to external functions.
4874   // When PC-Relative addressing is used, the concept of the TOC is no longer
4875   // applicable so this check is not required.
4876   // Check first for indirect calls.
4877   if (!Subtarget.isUsingPCRelativeCalls() &&
4878       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4879     return false;
4880 
4881   // Check if we share the TOC base.
4882   if (!Subtarget.isUsingPCRelativeCalls() &&
4883       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4884     return false;
4885 
4886   // TCO allows altering callee ABI, so we don't have to check further.
4887   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4888     return true;
4889 
4890   if (DisableSCO) return false;
4891 
4892   // If callee use the same argument list that caller is using, then we can
4893   // apply SCO on this case. If it is not, then we need to check if callee needs
4894   // stack for passing arguments.
4895   // PC Relative tail calls may not have a CallBase.
4896   // If there is no CallBase we cannot verify if we have the same argument
4897   // list so assume that we don't have the same argument list.
4898   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4899       needStackSlotPassParameters(Subtarget, Outs))
4900     return false;
4901   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4902     return false;
4903 
4904   return true;
4905 }
4906 
4907 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4908 /// for tail call optimization. Targets which want to do tail call
4909 /// optimization should implement this function.
4910 bool
4911 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4912                                                      CallingConv::ID CalleeCC,
4913                                                      bool isVarArg,
4914                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4915                                                      SelectionDAG& DAG) const {
4916   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4917     return false;
4918 
4919   // Variable argument functions are not supported.
4920   if (isVarArg)
4921     return false;
4922 
4923   MachineFunction &MF = DAG.getMachineFunction();
4924   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4925   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4926     // Functions containing by val parameters are not supported.
4927     for (unsigned i = 0; i != Ins.size(); i++) {
4928        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4929        if (Flags.isByVal()) return false;
4930     }
4931 
4932     // Non-PIC/GOT tail calls are supported.
4933     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4934       return true;
4935 
4936     // At the moment we can only do local tail calls (in same module, hidden
4937     // or protected) if we are generating PIC.
4938     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4939       return G->getGlobal()->hasHiddenVisibility()
4940           || G->getGlobal()->hasProtectedVisibility();
4941   }
4942 
4943   return false;
4944 }
4945 
4946 /// isCallCompatibleAddress - Return the immediate to use if the specified
4947 /// 32-bit value is representable in the immediate field of a BxA instruction.
4948 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4949   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4950   if (!C) return nullptr;
4951 
4952   int Addr = C->getZExtValue();
4953   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4954       SignExtend32<26>(Addr) != Addr)
4955     return nullptr;  // Top 6 bits have to be sext of immediate.
4956 
4957   return DAG
4958       .getConstant(
4959           (int)C->getZExtValue() >> 2, SDLoc(Op),
4960           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4961       .getNode();
4962 }
4963 
4964 namespace {
4965 
4966 struct TailCallArgumentInfo {
4967   SDValue Arg;
4968   SDValue FrameIdxOp;
4969   int FrameIdx = 0;
4970 
4971   TailCallArgumentInfo() = default;
4972 };
4973 
4974 } // end anonymous namespace
4975 
4976 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4977 static void StoreTailCallArgumentsToStackSlot(
4978     SelectionDAG &DAG, SDValue Chain,
4979     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4980     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4981   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4982     SDValue Arg = TailCallArgs[i].Arg;
4983     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4984     int FI = TailCallArgs[i].FrameIdx;
4985     // Store relative to framepointer.
4986     MemOpChains.push_back(DAG.getStore(
4987         Chain, dl, Arg, FIN,
4988         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4989   }
4990 }
4991 
4992 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4993 /// the appropriate stack slot for the tail call optimized function call.
4994 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4995                                              SDValue OldRetAddr, SDValue OldFP,
4996                                              int SPDiff, const SDLoc &dl) {
4997   if (SPDiff) {
4998     // Calculate the new stack slot for the return address.
4999     MachineFunction &MF = DAG.getMachineFunction();
5000     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5001     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5002     bool isPPC64 = Subtarget.isPPC64();
5003     int SlotSize = isPPC64 ? 8 : 4;
5004     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5005     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5006                                                          NewRetAddrLoc, true);
5007     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5008     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
5009     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5010                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5011   }
5012   return Chain;
5013 }
5014 
5015 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5016 /// the position of the argument.
5017 static void
5018 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
5019                          SDValue Arg, int SPDiff, unsigned ArgOffset,
5020                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
5021   int Offset = ArgOffset + SPDiff;
5022   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5023   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5024   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5025   SDValue FIN = DAG.getFrameIndex(FI, VT);
5026   TailCallArgumentInfo Info;
5027   Info.Arg = Arg;
5028   Info.FrameIdxOp = FIN;
5029   Info.FrameIdx = FI;
5030   TailCallArguments.push_back(Info);
5031 }
5032 
5033 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5034 /// stack slot. Returns the chain as result and the loaded frame pointers in
5035 /// LROpOut/FPOpout. Used when tail calling.
5036 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5037     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5038     SDValue &FPOpOut, const SDLoc &dl) const {
5039   if (SPDiff) {
5040     // Load the LR and FP stack slot for later adjusting.
5041     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5042     LROpOut = getReturnAddrFrameIndex(DAG);
5043     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
5044     Chain = SDValue(LROpOut.getNode(), 1);
5045   }
5046   return Chain;
5047 }
5048 
5049 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5050 /// by "Src" to address "Dst" of size "Size".  Alignment information is
5051 /// specified by the specific parameter attribute. The copy will be passed as
5052 /// a byval function parameter.
5053 /// Sometimes what we are copying is the end of a larger object, the part that
5054 /// does not fit in registers.
5055 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
5056                                          SDValue Chain, ISD::ArgFlagsTy Flags,
5057                                          SelectionDAG &DAG, const SDLoc &dl) {
5058   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5059   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
5060                        Flags.getNonZeroByValAlign(), false, false, false,
5061                        MachinePointerInfo(), MachinePointerInfo());
5062 }
5063 
5064 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5065 /// tail calls.
5066 static void LowerMemOpCallTo(
5067     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5068     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5069     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5070     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5071   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5072   if (!isTailCall) {
5073     if (isVector) {
5074       SDValue StackPtr;
5075       if (isPPC64)
5076         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5077       else
5078         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5079       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5080                            DAG.getConstant(ArgOffset, dl, PtrVT));
5081     }
5082     MemOpChains.push_back(
5083         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5084     // Calculate and remember argument location.
5085   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5086                                   TailCallArguments);
5087 }
5088 
5089 static void
5090 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
5091                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5092                 SDValue FPOp,
5093                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5094   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5095   // might overwrite each other in case of tail call optimization.
5096   SmallVector<SDValue, 8> MemOpChains2;
5097   // Do not flag preceding copytoreg stuff together with the following stuff.
5098   InFlag = SDValue();
5099   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5100                                     MemOpChains2, dl);
5101   if (!MemOpChains2.empty())
5102     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5103 
5104   // Store the return address to the appropriate stack slot.
5105   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5106 
5107   // Emit callseq_end just before tailcall node.
5108   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5109                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5110   InFlag = Chain.getValue(1);
5111 }
5112 
5113 // Is this global address that of a function that can be called by name? (as
5114 // opposed to something that must hold a descriptor for an indirect call).
5115 static bool isFunctionGlobalAddress(SDValue Callee) {
5116   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5117     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5118         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5119       return false;
5120 
5121     return G->getGlobal()->getValueType()->isFunctionTy();
5122   }
5123 
5124   return false;
5125 }
5126 
5127 SDValue PPCTargetLowering::LowerCallResult(
5128     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5129     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5130     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5131   SmallVector<CCValAssign, 16> RVLocs;
5132   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5133                     *DAG.getContext());
5134 
5135   CCRetInfo.AnalyzeCallResult(
5136       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5137                ? RetCC_PPC_Cold
5138                : RetCC_PPC);
5139 
5140   // Copy all of the result registers out of their specified physreg.
5141   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5142     CCValAssign &VA = RVLocs[i];
5143     assert(VA.isRegLoc() && "Can only return in registers!");
5144 
5145     SDValue Val;
5146 
5147     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5148       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5149                                       InFlag);
5150       Chain = Lo.getValue(1);
5151       InFlag = Lo.getValue(2);
5152       VA = RVLocs[++i]; // skip ahead to next loc
5153       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5154                                       InFlag);
5155       Chain = Hi.getValue(1);
5156       InFlag = Hi.getValue(2);
5157       if (!Subtarget.isLittleEndian())
5158         std::swap (Lo, Hi);
5159       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5160     } else {
5161       Val = DAG.getCopyFromReg(Chain, dl,
5162                                VA.getLocReg(), VA.getLocVT(), InFlag);
5163       Chain = Val.getValue(1);
5164       InFlag = Val.getValue(2);
5165     }
5166 
5167     switch (VA.getLocInfo()) {
5168     default: llvm_unreachable("Unknown loc info!");
5169     case CCValAssign::Full: break;
5170     case CCValAssign::AExt:
5171       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5172       break;
5173     case CCValAssign::ZExt:
5174       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5175                         DAG.getValueType(VA.getValVT()));
5176       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5177       break;
5178     case CCValAssign::SExt:
5179       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5180                         DAG.getValueType(VA.getValVT()));
5181       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5182       break;
5183     }
5184 
5185     InVals.push_back(Val);
5186   }
5187 
5188   return Chain;
5189 }
5190 
5191 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5192                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5193   // PatchPoint calls are not indirect.
5194   if (isPatchPoint)
5195     return false;
5196 
5197   if (isFunctionGlobalAddress(Callee) || isa<ExternalSymbolSDNode>(Callee))
5198     return false;
5199 
5200   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5201   // becuase the immediate function pointer points to a descriptor instead of
5202   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5203   // pointer immediate points to the global entry point, while the BLA would
5204   // need to jump to the local entry point (see rL211174).
5205   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5206       isBLACompatibleAddress(Callee, DAG))
5207     return false;
5208 
5209   return true;
5210 }
5211 
5212 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5213 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5214   return Subtarget.isAIXABI() ||
5215          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5216 }
5217 
5218 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5219                               const Function &Caller, const SDValue &Callee,
5220                               const PPCSubtarget &Subtarget,
5221                               const TargetMachine &TM,
5222                               bool IsStrictFPCall = false) {
5223   if (CFlags.IsTailCall)
5224     return PPCISD::TC_RETURN;
5225 
5226   unsigned RetOpc = 0;
5227   // This is a call through a function pointer.
5228   if (CFlags.IsIndirect) {
5229     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5230     // indirect calls. The save of the caller's TOC pointer to the stack will be
5231     // inserted into the DAG as part of call lowering. The restore of the TOC
5232     // pointer is modeled by using a pseudo instruction for the call opcode that
5233     // represents the 2 instruction sequence of an indirect branch and link,
5234     // immediately followed by a load of the TOC pointer from the the stack save
5235     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5236     // as it is not saved or used.
5237     RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5238                                                  : PPCISD::BCTRL;
5239   } else if (Subtarget.isUsingPCRelativeCalls()) {
5240     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5241     RetOpc = PPCISD::CALL_NOTOC;
5242   } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5243     // The ABIs that maintain a TOC pointer accross calls need to have a nop
5244     // immediately following the call instruction if the caller and callee may
5245     // have different TOC bases. At link time if the linker determines the calls
5246     // may not share a TOC base, the call is redirected to a trampoline inserted
5247     // by the linker. The trampoline will (among other things) save the callers
5248     // TOC pointer at an ABI designated offset in the linkage area and the
5249     // linker will rewrite the nop to be a load of the TOC pointer from the
5250     // linkage area into gpr2.
5251     RetOpc = callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5252                                                     : PPCISD::CALL_NOP;
5253   else
5254     RetOpc = PPCISD::CALL;
5255   if (IsStrictFPCall) {
5256     switch (RetOpc) {
5257     default:
5258       llvm_unreachable("Unknown call opcode");
5259     case PPCISD::BCTRL_LOAD_TOC:
5260       RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5261       break;
5262     case PPCISD::BCTRL:
5263       RetOpc = PPCISD::BCTRL_RM;
5264       break;
5265     case PPCISD::CALL_NOTOC:
5266       RetOpc = PPCISD::CALL_NOTOC_RM;
5267       break;
5268     case PPCISD::CALL:
5269       RetOpc = PPCISD::CALL_RM;
5270       break;
5271     case PPCISD::CALL_NOP:
5272       RetOpc = PPCISD::CALL_NOP_RM;
5273       break;
5274     }
5275   }
5276   return RetOpc;
5277 }
5278 
5279 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5280                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5281   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5282     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5283       return SDValue(Dest, 0);
5284 
5285   // Returns true if the callee is local, and false otherwise.
5286   auto isLocalCallee = [&]() {
5287     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5288     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5289     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5290 
5291     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5292            !isa_and_nonnull<GlobalIFunc>(GV);
5293   };
5294 
5295   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5296   // a static relocation model causes some versions of GNU LD (2.17.50, at
5297   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5298   // built with secure-PLT.
5299   bool UsePlt =
5300       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5301       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5302 
5303   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5304     const TargetMachine &TM = Subtarget.getTargetMachine();
5305     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5306     MCSymbolXCOFF *S =
5307         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5308 
5309     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5310     return DAG.getMCSymbol(S, PtrVT);
5311   };
5312 
5313   if (isFunctionGlobalAddress(Callee)) {
5314     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5315 
5316     if (Subtarget.isAIXABI()) {
5317       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5318       return getAIXFuncEntryPointSymbolSDNode(GV);
5319     }
5320     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5321                                       UsePlt ? PPCII::MO_PLT : 0);
5322   }
5323 
5324   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5325     const char *SymName = S->getSymbol();
5326     if (Subtarget.isAIXABI()) {
5327       // If there exists a user-declared function whose name is the same as the
5328       // ExternalSymbol's, then we pick up the user-declared version.
5329       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5330       if (const Function *F =
5331               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5332         return getAIXFuncEntryPointSymbolSDNode(F);
5333 
5334       // On AIX, direct function calls reference the symbol for the function's
5335       // entry point, which is named by prepending a "." before the function's
5336       // C-linkage name. A Qualname is returned here because an external
5337       // function entry point is a csect with XTY_ER property.
5338       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5339         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5340         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5341             (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5342             XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER));
5343         return Sec->getQualNameSymbol();
5344       };
5345 
5346       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5347     }
5348     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5349                                        UsePlt ? PPCII::MO_PLT : 0);
5350   }
5351 
5352   // No transformation needed.
5353   assert(Callee.getNode() && "What no callee?");
5354   return Callee;
5355 }
5356 
5357 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5358   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5359          "Expected a CALLSEQ_STARTSDNode.");
5360 
5361   // The last operand is the chain, except when the node has glue. If the node
5362   // has glue, then the last operand is the glue, and the chain is the second
5363   // last operand.
5364   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5365   if (LastValue.getValueType() != MVT::Glue)
5366     return LastValue;
5367 
5368   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5369 }
5370 
5371 // Creates the node that moves a functions address into the count register
5372 // to prepare for an indirect call instruction.
5373 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5374                                 SDValue &Glue, SDValue &Chain,
5375                                 const SDLoc &dl) {
5376   SDValue MTCTROps[] = {Chain, Callee, Glue};
5377   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5378   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5379                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5380   // The glue is the second value produced.
5381   Glue = Chain.getValue(1);
5382 }
5383 
5384 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5385                                           SDValue &Glue, SDValue &Chain,
5386                                           SDValue CallSeqStart,
5387                                           const CallBase *CB, const SDLoc &dl,
5388                                           bool hasNest,
5389                                           const PPCSubtarget &Subtarget) {
5390   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5391   // entry point, but to the function descriptor (the function entry point
5392   // address is part of the function descriptor though).
5393   // The function descriptor is a three doubleword structure with the
5394   // following fields: function entry point, TOC base address and
5395   // environment pointer.
5396   // Thus for a call through a function pointer, the following actions need
5397   // to be performed:
5398   //   1. Save the TOC of the caller in the TOC save area of its stack
5399   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5400   //   2. Load the address of the function entry point from the function
5401   //      descriptor.
5402   //   3. Load the TOC of the callee from the function descriptor into r2.
5403   //   4. Load the environment pointer from the function descriptor into
5404   //      r11.
5405   //   5. Branch to the function entry point address.
5406   //   6. On return of the callee, the TOC of the caller needs to be
5407   //      restored (this is done in FinishCall()).
5408   //
5409   // The loads are scheduled at the beginning of the call sequence, and the
5410   // register copies are flagged together to ensure that no other
5411   // operations can be scheduled in between. E.g. without flagging the
5412   // copies together, a TOC access in the caller could be scheduled between
5413   // the assignment of the callee TOC and the branch to the callee, which leads
5414   // to incorrect code.
5415 
5416   // Start by loading the function address from the descriptor.
5417   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5418   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5419                       ? (MachineMemOperand::MODereferenceable |
5420                          MachineMemOperand::MOInvariant)
5421                       : MachineMemOperand::MONone;
5422 
5423   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5424 
5425   // Registers used in building the DAG.
5426   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5427   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5428 
5429   // Offsets of descriptor members.
5430   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5431   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5432 
5433   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5434   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5435 
5436   // One load for the functions entry point address.
5437   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5438                                     Alignment, MMOFlags);
5439 
5440   // One for loading the TOC anchor for the module that contains the called
5441   // function.
5442   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5443   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5444   SDValue TOCPtr =
5445       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5446                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5447 
5448   // One for loading the environment pointer.
5449   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5450   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5451   SDValue LoadEnvPtr =
5452       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5453                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5454 
5455 
5456   // Then copy the newly loaded TOC anchor to the TOC pointer.
5457   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5458   Chain = TOCVal.getValue(0);
5459   Glue = TOCVal.getValue(1);
5460 
5461   // If the function call has an explicit 'nest' parameter, it takes the
5462   // place of the environment pointer.
5463   assert((!hasNest || !Subtarget.isAIXABI()) &&
5464          "Nest parameter is not supported on AIX.");
5465   if (!hasNest) {
5466     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5467     Chain = EnvVal.getValue(0);
5468     Glue = EnvVal.getValue(1);
5469   }
5470 
5471   // The rest of the indirect call sequence is the same as the non-descriptor
5472   // DAG.
5473   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5474 }
5475 
5476 static void
5477 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5478                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5479                   SelectionDAG &DAG,
5480                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5481                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5482                   const PPCSubtarget &Subtarget) {
5483   const bool IsPPC64 = Subtarget.isPPC64();
5484   // MVT for a general purpose register.
5485   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5486 
5487   // First operand is always the chain.
5488   Ops.push_back(Chain);
5489 
5490   // If it's a direct call pass the callee as the second operand.
5491   if (!CFlags.IsIndirect)
5492     Ops.push_back(Callee);
5493   else {
5494     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5495 
5496     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5497     // on the stack (this would have been done in `LowerCall_64SVR4` or
5498     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5499     // represents both the indirect branch and a load that restores the TOC
5500     // pointer from the linkage area. The operand for the TOC restore is an add
5501     // of the TOC save offset to the stack pointer. This must be the second
5502     // operand: after the chain input but before any other variadic arguments.
5503     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5504     // saved or used.
5505     if (isTOCSaveRestoreRequired(Subtarget)) {
5506       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5507 
5508       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5509       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5510       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5511       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5512       Ops.push_back(AddTOC);
5513     }
5514 
5515     // Add the register used for the environment pointer.
5516     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5517       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5518                                     RegVT));
5519 
5520 
5521     // Add CTR register as callee so a bctr can be emitted later.
5522     if (CFlags.IsTailCall)
5523       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5524   }
5525 
5526   // If this is a tail call add stack pointer delta.
5527   if (CFlags.IsTailCall)
5528     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5529 
5530   // Add argument registers to the end of the list so that they are known live
5531   // into the call.
5532   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5533     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5534                                   RegsToPass[i].second.getValueType()));
5535 
5536   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5537   // no way to mark dependencies as implicit here.
5538   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5539   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5540        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5541     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5542 
5543   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5544   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5545     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5546 
5547   // Add a register mask operand representing the call-preserved registers.
5548   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5549   const uint32_t *Mask =
5550       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5551   assert(Mask && "Missing call preserved mask for calling convention");
5552   Ops.push_back(DAG.getRegisterMask(Mask));
5553 
5554   // If the glue is valid, it is the last operand.
5555   if (Glue.getNode())
5556     Ops.push_back(Glue);
5557 }
5558 
5559 SDValue PPCTargetLowering::FinishCall(
5560     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5561     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5562     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5563     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5564     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5565 
5566   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5567       Subtarget.isAIXABI())
5568     setUsesTOCBasePtr(DAG);
5569 
5570   unsigned CallOpc =
5571       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5572                     Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5573 
5574   if (!CFlags.IsIndirect)
5575     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5576   else if (Subtarget.usesFunctionDescriptors())
5577     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5578                                   dl, CFlags.HasNest, Subtarget);
5579   else
5580     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5581 
5582   // Build the operand list for the call instruction.
5583   SmallVector<SDValue, 8> Ops;
5584   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5585                     SPDiff, Subtarget);
5586 
5587   // Emit tail call.
5588   if (CFlags.IsTailCall) {
5589     // Indirect tail call when using PC Relative calls do not have the same
5590     // constraints.
5591     assert(((Callee.getOpcode() == ISD::Register &&
5592              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5593             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5594             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5595             isa<ConstantSDNode>(Callee) ||
5596             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5597            "Expecting a global address, external symbol, absolute value, "
5598            "register or an indirect tail call when PC Relative calls are "
5599            "used.");
5600     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5601     assert(CallOpc == PPCISD::TC_RETURN &&
5602            "Unexpected call opcode for a tail call.");
5603     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5604     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5605   }
5606 
5607   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5608   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5609   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5610   Glue = Chain.getValue(1);
5611 
5612   // When performing tail call optimization the callee pops its arguments off
5613   // the stack. Account for this here so these bytes can be pushed back on in
5614   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5615   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5616                          getTargetMachine().Options.GuaranteedTailCallOpt)
5617                             ? NumBytes
5618                             : 0;
5619 
5620   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5621                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5622                              Glue, dl);
5623   Glue = Chain.getValue(1);
5624 
5625   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5626                          DAG, InVals);
5627 }
5628 
5629 SDValue
5630 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5631                              SmallVectorImpl<SDValue> &InVals) const {
5632   SelectionDAG &DAG                     = CLI.DAG;
5633   SDLoc &dl                             = CLI.DL;
5634   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5635   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5636   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5637   SDValue Chain                         = CLI.Chain;
5638   SDValue Callee                        = CLI.Callee;
5639   bool &isTailCall                      = CLI.IsTailCall;
5640   CallingConv::ID CallConv              = CLI.CallConv;
5641   bool isVarArg                         = CLI.IsVarArg;
5642   bool isPatchPoint                     = CLI.IsPatchPoint;
5643   const CallBase *CB                    = CLI.CB;
5644 
5645   if (isTailCall) {
5646     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5647       isTailCall = false;
5648     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5649       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5650           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5651     else
5652       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5653                                                      Ins, DAG);
5654     if (isTailCall) {
5655       ++NumTailCalls;
5656       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5657         ++NumSiblingCalls;
5658 
5659       // PC Relative calls no longer guarantee that the callee is a Global
5660       // Address Node. The callee could be an indirect tail call in which
5661       // case the SDValue for the callee could be a load (to load the address
5662       // of a function pointer) or it may be a register copy (to move the
5663       // address of the callee from a function parameter into a virtual
5664       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5665       assert((Subtarget.isUsingPCRelativeCalls() ||
5666               isa<GlobalAddressSDNode>(Callee)) &&
5667              "Callee should be an llvm::Function object.");
5668 
5669       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5670                         << "\nTCO callee: ");
5671       LLVM_DEBUG(Callee.dump());
5672     }
5673   }
5674 
5675   if (!isTailCall && CB && CB->isMustTailCall())
5676     report_fatal_error("failed to perform tail call elimination on a call "
5677                        "site marked musttail");
5678 
5679   // When long calls (i.e. indirect calls) are always used, calls are always
5680   // made via function pointer. If we have a function name, first translate it
5681   // into a pointer.
5682   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5683       !isTailCall)
5684     Callee = LowerGlobalAddress(Callee, DAG);
5685 
5686   CallFlags CFlags(
5687       CallConv, isTailCall, isVarArg, isPatchPoint,
5688       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5689       // hasNest
5690       Subtarget.is64BitELFABI() &&
5691           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5692       CLI.NoMerge);
5693 
5694   if (Subtarget.isAIXABI())
5695     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5696                          InVals, CB);
5697 
5698   assert(Subtarget.isSVR4ABI());
5699   if (Subtarget.isPPC64())
5700     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5701                             InVals, CB);
5702   return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5703                           InVals, CB);
5704 }
5705 
5706 SDValue PPCTargetLowering::LowerCall_32SVR4(
5707     SDValue Chain, SDValue Callee, CallFlags CFlags,
5708     const SmallVectorImpl<ISD::OutputArg> &Outs,
5709     const SmallVectorImpl<SDValue> &OutVals,
5710     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5711     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5712     const CallBase *CB) const {
5713   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5714   // of the 32-bit SVR4 ABI stack frame layout.
5715 
5716   const CallingConv::ID CallConv = CFlags.CallConv;
5717   const bool IsVarArg = CFlags.IsVarArg;
5718   const bool IsTailCall = CFlags.IsTailCall;
5719 
5720   assert((CallConv == CallingConv::C ||
5721           CallConv == CallingConv::Cold ||
5722           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5723 
5724   const Align PtrAlign(4);
5725 
5726   MachineFunction &MF = DAG.getMachineFunction();
5727 
5728   // Mark this function as potentially containing a function that contains a
5729   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5730   // and restoring the callers stack pointer in this functions epilog. This is
5731   // done because by tail calling the called function might overwrite the value
5732   // in this function's (MF) stack pointer stack slot 0(SP).
5733   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5734       CallConv == CallingConv::Fast)
5735     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5736 
5737   // Count how many bytes are to be pushed on the stack, including the linkage
5738   // area, parameter list area and the part of the local variable space which
5739   // contains copies of aggregates which are passed by value.
5740 
5741   // Assign locations to all of the outgoing arguments.
5742   SmallVector<CCValAssign, 16> ArgLocs;
5743   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5744 
5745   // Reserve space for the linkage area on the stack.
5746   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5747                        PtrAlign);
5748   if (useSoftFloat())
5749     CCInfo.PreAnalyzeCallOperands(Outs);
5750 
5751   if (IsVarArg) {
5752     // Handle fixed and variable vector arguments differently.
5753     // Fixed vector arguments go into registers as long as registers are
5754     // available. Variable vector arguments always go into memory.
5755     unsigned NumArgs = Outs.size();
5756 
5757     for (unsigned i = 0; i != NumArgs; ++i) {
5758       MVT ArgVT = Outs[i].VT;
5759       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5760       bool Result;
5761 
5762       if (Outs[i].IsFixed) {
5763         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5764                                CCInfo);
5765       } else {
5766         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5767                                       ArgFlags, CCInfo);
5768       }
5769 
5770       if (Result) {
5771 #ifndef NDEBUG
5772         errs() << "Call operand #" << i << " has unhandled type "
5773              << EVT(ArgVT).getEVTString() << "\n";
5774 #endif
5775         llvm_unreachable(nullptr);
5776       }
5777     }
5778   } else {
5779     // All arguments are treated the same.
5780     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5781   }
5782   CCInfo.clearWasPPCF128();
5783 
5784   // Assign locations to all of the outgoing aggregate by value arguments.
5785   SmallVector<CCValAssign, 16> ByValArgLocs;
5786   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5787 
5788   // Reserve stack space for the allocations in CCInfo.
5789   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5790 
5791   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5792 
5793   // Size of the linkage area, parameter list area and the part of the local
5794   // space variable where copies of aggregates which are passed by value are
5795   // stored.
5796   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5797 
5798   // Calculate by how many bytes the stack has to be adjusted in case of tail
5799   // call optimization.
5800   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5801 
5802   // Adjust the stack pointer for the new arguments...
5803   // These operations are automatically eliminated by the prolog/epilog pass
5804   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5805   SDValue CallSeqStart = Chain;
5806 
5807   // Load the return address and frame pointer so it can be moved somewhere else
5808   // later.
5809   SDValue LROp, FPOp;
5810   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5811 
5812   // Set up a copy of the stack pointer for use loading and storing any
5813   // arguments that may not fit in the registers available for argument
5814   // passing.
5815   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5816 
5817   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5818   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5819   SmallVector<SDValue, 8> MemOpChains;
5820 
5821   bool seenFloatArg = false;
5822   // Walk the register/memloc assignments, inserting copies/loads.
5823   // i - Tracks the index into the list of registers allocated for the call
5824   // RealArgIdx - Tracks the index into the list of actual function arguments
5825   // j - Tracks the index into the list of byval arguments
5826   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5827        i != e;
5828        ++i, ++RealArgIdx) {
5829     CCValAssign &VA = ArgLocs[i];
5830     SDValue Arg = OutVals[RealArgIdx];
5831     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5832 
5833     if (Flags.isByVal()) {
5834       // Argument is an aggregate which is passed by value, thus we need to
5835       // create a copy of it in the local variable space of the current stack
5836       // frame (which is the stack frame of the caller) and pass the address of
5837       // this copy to the callee.
5838       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5839       CCValAssign &ByValVA = ByValArgLocs[j++];
5840       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5841 
5842       // Memory reserved in the local variable space of the callers stack frame.
5843       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5844 
5845       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5846       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5847                            StackPtr, PtrOff);
5848 
5849       // Create a copy of the argument in the local area of the current
5850       // stack frame.
5851       SDValue MemcpyCall =
5852         CreateCopyOfByValArgument(Arg, PtrOff,
5853                                   CallSeqStart.getNode()->getOperand(0),
5854                                   Flags, DAG, dl);
5855 
5856       // This must go outside the CALLSEQ_START..END.
5857       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5858                                                      SDLoc(MemcpyCall));
5859       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5860                              NewCallSeqStart.getNode());
5861       Chain = CallSeqStart = NewCallSeqStart;
5862 
5863       // Pass the address of the aggregate copy on the stack either in a
5864       // physical register or in the parameter list area of the current stack
5865       // frame to the callee.
5866       Arg = PtrOff;
5867     }
5868 
5869     // When useCRBits() is true, there can be i1 arguments.
5870     // It is because getRegisterType(MVT::i1) => MVT::i1,
5871     // and for other integer types getRegisterType() => MVT::i32.
5872     // Extend i1 and ensure callee will get i32.
5873     if (Arg.getValueType() == MVT::i1)
5874       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5875                         dl, MVT::i32, Arg);
5876 
5877     if (VA.isRegLoc()) {
5878       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5879       // Put argument in a physical register.
5880       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5881         bool IsLE = Subtarget.isLittleEndian();
5882         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5883                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5884         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5885         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5886                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5887         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5888                              SVal.getValue(0)));
5889       } else
5890         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5891     } else {
5892       // Put argument in the parameter list area of the current stack frame.
5893       assert(VA.isMemLoc());
5894       unsigned LocMemOffset = VA.getLocMemOffset();
5895 
5896       if (!IsTailCall) {
5897         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5898         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5899                              StackPtr, PtrOff);
5900 
5901         MemOpChains.push_back(
5902             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5903       } else {
5904         // Calculate and remember argument location.
5905         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5906                                  TailCallArguments);
5907       }
5908     }
5909   }
5910 
5911   if (!MemOpChains.empty())
5912     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5913 
5914   // Build a sequence of copy-to-reg nodes chained together with token chain
5915   // and flag operands which copy the outgoing args into the appropriate regs.
5916   SDValue InFlag;
5917   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5918     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5919                              RegsToPass[i].second, InFlag);
5920     InFlag = Chain.getValue(1);
5921   }
5922 
5923   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5924   // registers.
5925   if (IsVarArg) {
5926     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5927     SDValue Ops[] = { Chain, InFlag };
5928 
5929     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5930                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5931 
5932     InFlag = Chain.getValue(1);
5933   }
5934 
5935   if (IsTailCall)
5936     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5937                     TailCallArguments);
5938 
5939   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5940                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5941 }
5942 
5943 // Copy an argument into memory, being careful to do this outside the
5944 // call sequence for the call to which the argument belongs.
5945 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5946     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5947     SelectionDAG &DAG, const SDLoc &dl) const {
5948   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5949                         CallSeqStart.getNode()->getOperand(0),
5950                         Flags, DAG, dl);
5951   // The MEMCPY must go outside the CALLSEQ_START..END.
5952   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5953   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5954                                                  SDLoc(MemcpyCall));
5955   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5956                          NewCallSeqStart.getNode());
5957   return NewCallSeqStart;
5958 }
5959 
5960 SDValue PPCTargetLowering::LowerCall_64SVR4(
5961     SDValue Chain, SDValue Callee, CallFlags CFlags,
5962     const SmallVectorImpl<ISD::OutputArg> &Outs,
5963     const SmallVectorImpl<SDValue> &OutVals,
5964     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5965     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5966     const CallBase *CB) const {
5967   bool isELFv2ABI = Subtarget.isELFv2ABI();
5968   bool isLittleEndian = Subtarget.isLittleEndian();
5969   unsigned NumOps = Outs.size();
5970   bool IsSibCall = false;
5971   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5972 
5973   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5974   unsigned PtrByteSize = 8;
5975 
5976   MachineFunction &MF = DAG.getMachineFunction();
5977 
5978   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5979     IsSibCall = true;
5980 
5981   // Mark this function as potentially containing a function that contains a
5982   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5983   // and restoring the callers stack pointer in this functions epilog. This is
5984   // done because by tail calling the called function might overwrite the value
5985   // in this function's (MF) stack pointer stack slot 0(SP).
5986   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5987     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5988 
5989   assert(!(IsFastCall && CFlags.IsVarArg) &&
5990          "fastcc not supported on varargs functions");
5991 
5992   // Count how many bytes are to be pushed on the stack, including the linkage
5993   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5994   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5995   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5996   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5997   unsigned NumBytes = LinkageSize;
5998   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5999 
6000   static const MCPhysReg GPR[] = {
6001     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6002     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6003   };
6004   static const MCPhysReg VR[] = {
6005     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6006     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6007   };
6008 
6009   const unsigned NumGPRs = array_lengthof(GPR);
6010   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6011   const unsigned NumVRs  = array_lengthof(VR);
6012 
6013   // On ELFv2, we can avoid allocating the parameter area if all the arguments
6014   // can be passed to the callee in registers.
6015   // For the fast calling convention, there is another check below.
6016   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6017   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6018   if (!HasParameterArea) {
6019     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6020     unsigned AvailableFPRs = NumFPRs;
6021     unsigned AvailableVRs = NumVRs;
6022     unsigned NumBytesTmp = NumBytes;
6023     for (unsigned i = 0; i != NumOps; ++i) {
6024       if (Outs[i].Flags.isNest()) continue;
6025       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6026                                  PtrByteSize, LinkageSize, ParamAreaSize,
6027                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
6028         HasParameterArea = true;
6029     }
6030   }
6031 
6032   // When using the fast calling convention, we don't provide backing for
6033   // arguments that will be in registers.
6034   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6035 
6036   // Avoid allocating parameter area for fastcc functions if all the arguments
6037   // can be passed in the registers.
6038   if (IsFastCall)
6039     HasParameterArea = false;
6040 
6041   // Add up all the space actually used.
6042   for (unsigned i = 0; i != NumOps; ++i) {
6043     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6044     EVT ArgVT = Outs[i].VT;
6045     EVT OrigVT = Outs[i].ArgVT;
6046 
6047     if (Flags.isNest())
6048       continue;
6049 
6050     if (IsFastCall) {
6051       if (Flags.isByVal()) {
6052         NumGPRsUsed += (Flags.getByValSize()+7)/8;
6053         if (NumGPRsUsed > NumGPRs)
6054           HasParameterArea = true;
6055       } else {
6056         switch (ArgVT.getSimpleVT().SimpleTy) {
6057         default: llvm_unreachable("Unexpected ValueType for argument!");
6058         case MVT::i1:
6059         case MVT::i32:
6060         case MVT::i64:
6061           if (++NumGPRsUsed <= NumGPRs)
6062             continue;
6063           break;
6064         case MVT::v4i32:
6065         case MVT::v8i16:
6066         case MVT::v16i8:
6067         case MVT::v2f64:
6068         case MVT::v2i64:
6069         case MVT::v1i128:
6070         case MVT::f128:
6071           if (++NumVRsUsed <= NumVRs)
6072             continue;
6073           break;
6074         case MVT::v4f32:
6075           if (++NumVRsUsed <= NumVRs)
6076             continue;
6077           break;
6078         case MVT::f32:
6079         case MVT::f64:
6080           if (++NumFPRsUsed <= NumFPRs)
6081             continue;
6082           break;
6083         }
6084         HasParameterArea = true;
6085       }
6086     }
6087 
6088     /* Respect alignment of argument on the stack.  */
6089     auto Alignement =
6090         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6091     NumBytes = alignTo(NumBytes, Alignement);
6092 
6093     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6094     if (Flags.isInConsecutiveRegsLast())
6095       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6096   }
6097 
6098   unsigned NumBytesActuallyUsed = NumBytes;
6099 
6100   // In the old ELFv1 ABI,
6101   // the prolog code of the callee may store up to 8 GPR argument registers to
6102   // the stack, allowing va_start to index over them in memory if its varargs.
6103   // Because we cannot tell if this is needed on the caller side, we have to
6104   // conservatively assume that it is needed.  As such, make sure we have at
6105   // least enough stack space for the caller to store the 8 GPRs.
6106   // In the ELFv2 ABI, we allocate the parameter area iff a callee
6107   // really requires memory operands, e.g. a vararg function.
6108   if (HasParameterArea)
6109     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6110   else
6111     NumBytes = LinkageSize;
6112 
6113   // Tail call needs the stack to be aligned.
6114   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6115     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6116 
6117   int SPDiff = 0;
6118 
6119   // Calculate by how many bytes the stack has to be adjusted in case of tail
6120   // call optimization.
6121   if (!IsSibCall)
6122     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6123 
6124   // To protect arguments on the stack from being clobbered in a tail call,
6125   // force all the loads to happen before doing any other lowering.
6126   if (CFlags.IsTailCall)
6127     Chain = DAG.getStackArgumentTokenFactor(Chain);
6128 
6129   // Adjust the stack pointer for the new arguments...
6130   // These operations are automatically eliminated by the prolog/epilog pass
6131   if (!IsSibCall)
6132     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6133   SDValue CallSeqStart = Chain;
6134 
6135   // Load the return address and frame pointer so it can be move somewhere else
6136   // later.
6137   SDValue LROp, FPOp;
6138   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6139 
6140   // Set up a copy of the stack pointer for use loading and storing any
6141   // arguments that may not fit in the registers available for argument
6142   // passing.
6143   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6144 
6145   // Figure out which arguments are going to go in registers, and which in
6146   // memory.  Also, if this is a vararg function, floating point operations
6147   // must be stored to our stack, and loaded into integer regs as well, if
6148   // any integer regs are available for argument passing.
6149   unsigned ArgOffset = LinkageSize;
6150 
6151   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6152   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6153 
6154   SmallVector<SDValue, 8> MemOpChains;
6155   for (unsigned i = 0; i != NumOps; ++i) {
6156     SDValue Arg = OutVals[i];
6157     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6158     EVT ArgVT = Outs[i].VT;
6159     EVT OrigVT = Outs[i].ArgVT;
6160 
6161     // PtrOff will be used to store the current argument to the stack if a
6162     // register cannot be found for it.
6163     SDValue PtrOff;
6164 
6165     // We re-align the argument offset for each argument, except when using the
6166     // fast calling convention, when we need to make sure we do that only when
6167     // we'll actually use a stack slot.
6168     auto ComputePtrOff = [&]() {
6169       /* Respect alignment of argument on the stack.  */
6170       auto Alignment =
6171           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6172       ArgOffset = alignTo(ArgOffset, Alignment);
6173 
6174       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6175 
6176       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6177     };
6178 
6179     if (!IsFastCall) {
6180       ComputePtrOff();
6181 
6182       /* Compute GPR index associated with argument offset.  */
6183       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6184       GPR_idx = std::min(GPR_idx, NumGPRs);
6185     }
6186 
6187     // Promote integers to 64-bit values.
6188     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6189       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6190       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6191       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6192     }
6193 
6194     // FIXME memcpy is used way more than necessary.  Correctness first.
6195     // Note: "by value" is code for passing a structure by value, not
6196     // basic types.
6197     if (Flags.isByVal()) {
6198       // Note: Size includes alignment padding, so
6199       //   struct x { short a; char b; }
6200       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6201       // These are the proper values we need for right-justifying the
6202       // aggregate in a parameter register.
6203       unsigned Size = Flags.getByValSize();
6204 
6205       // An empty aggregate parameter takes up no storage and no
6206       // registers.
6207       if (Size == 0)
6208         continue;
6209 
6210       if (IsFastCall)
6211         ComputePtrOff();
6212 
6213       // All aggregates smaller than 8 bytes must be passed right-justified.
6214       if (Size==1 || Size==2 || Size==4) {
6215         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6216         if (GPR_idx != NumGPRs) {
6217           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6218                                         MachinePointerInfo(), VT);
6219           MemOpChains.push_back(Load.getValue(1));
6220           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6221 
6222           ArgOffset += PtrByteSize;
6223           continue;
6224         }
6225       }
6226 
6227       if (GPR_idx == NumGPRs && Size < 8) {
6228         SDValue AddPtr = PtrOff;
6229         if (!isLittleEndian) {
6230           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6231                                           PtrOff.getValueType());
6232           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6233         }
6234         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6235                                                           CallSeqStart,
6236                                                           Flags, DAG, dl);
6237         ArgOffset += PtrByteSize;
6238         continue;
6239       }
6240       // Copy the object to parameter save area if it can not be entirely passed
6241       // by registers.
6242       // FIXME: we only need to copy the parts which need to be passed in
6243       // parameter save area. For the parts passed by registers, we don't need
6244       // to copy them to the stack although we need to allocate space for them
6245       // in parameter save area.
6246       if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6247         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6248                                                           CallSeqStart,
6249                                                           Flags, DAG, dl);
6250 
6251       // When a register is available, pass a small aggregate right-justified.
6252       if (Size < 8 && GPR_idx != NumGPRs) {
6253         // The easiest way to get this right-justified in a register
6254         // is to copy the structure into the rightmost portion of a
6255         // local variable slot, then load the whole slot into the
6256         // register.
6257         // FIXME: The memcpy seems to produce pretty awful code for
6258         // small aggregates, particularly for packed ones.
6259         // FIXME: It would be preferable to use the slot in the
6260         // parameter save area instead of a new local variable.
6261         SDValue AddPtr = PtrOff;
6262         if (!isLittleEndian) {
6263           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6264           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6265         }
6266         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6267                                                           CallSeqStart,
6268                                                           Flags, DAG, dl);
6269 
6270         // Load the slot into the register.
6271         SDValue Load =
6272             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6273         MemOpChains.push_back(Load.getValue(1));
6274         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6275 
6276         // Done with this argument.
6277         ArgOffset += PtrByteSize;
6278         continue;
6279       }
6280 
6281       // For aggregates larger than PtrByteSize, copy the pieces of the
6282       // object that fit into registers from the parameter save area.
6283       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6284         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6285         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6286         if (GPR_idx != NumGPRs) {
6287           SDValue Load =
6288               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6289           MemOpChains.push_back(Load.getValue(1));
6290           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6291           ArgOffset += PtrByteSize;
6292         } else {
6293           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6294           break;
6295         }
6296       }
6297       continue;
6298     }
6299 
6300     switch (Arg.getSimpleValueType().SimpleTy) {
6301     default: llvm_unreachable("Unexpected ValueType for argument!");
6302     case MVT::i1:
6303     case MVT::i32:
6304     case MVT::i64:
6305       if (Flags.isNest()) {
6306         // The 'nest' parameter, if any, is passed in R11.
6307         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6308         break;
6309       }
6310 
6311       // These can be scalar arguments or elements of an integer array type
6312       // passed directly.  Clang may use those instead of "byval" aggregate
6313       // types to avoid forcing arguments to memory unnecessarily.
6314       if (GPR_idx != NumGPRs) {
6315         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6316       } else {
6317         if (IsFastCall)
6318           ComputePtrOff();
6319 
6320         assert(HasParameterArea &&
6321                "Parameter area must exist to pass an argument in memory.");
6322         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6323                          true, CFlags.IsTailCall, false, MemOpChains,
6324                          TailCallArguments, dl);
6325         if (IsFastCall)
6326           ArgOffset += PtrByteSize;
6327       }
6328       if (!IsFastCall)
6329         ArgOffset += PtrByteSize;
6330       break;
6331     case MVT::f32:
6332     case MVT::f64: {
6333       // These can be scalar arguments or elements of a float array type
6334       // passed directly.  The latter are used to implement ELFv2 homogenous
6335       // float aggregates.
6336 
6337       // Named arguments go into FPRs first, and once they overflow, the
6338       // remaining arguments go into GPRs and then the parameter save area.
6339       // Unnamed arguments for vararg functions always go to GPRs and
6340       // then the parameter save area.  For now, put all arguments to vararg
6341       // routines always in both locations (FPR *and* GPR or stack slot).
6342       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6343       bool NeededLoad = false;
6344 
6345       // First load the argument into the next available FPR.
6346       if (FPR_idx != NumFPRs)
6347         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6348 
6349       // Next, load the argument into GPR or stack slot if needed.
6350       if (!NeedGPROrStack)
6351         ;
6352       else if (GPR_idx != NumGPRs && !IsFastCall) {
6353         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6354         // once we support fp <-> gpr moves.
6355 
6356         // In the non-vararg case, this can only ever happen in the
6357         // presence of f32 array types, since otherwise we never run
6358         // out of FPRs before running out of GPRs.
6359         SDValue ArgVal;
6360 
6361         // Double values are always passed in a single GPR.
6362         if (Arg.getValueType() != MVT::f32) {
6363           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6364 
6365         // Non-array float values are extended and passed in a GPR.
6366         } else if (!Flags.isInConsecutiveRegs()) {
6367           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6368           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6369 
6370         // If we have an array of floats, we collect every odd element
6371         // together with its predecessor into one GPR.
6372         } else if (ArgOffset % PtrByteSize != 0) {
6373           SDValue Lo, Hi;
6374           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6375           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6376           if (!isLittleEndian)
6377             std::swap(Lo, Hi);
6378           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6379 
6380         // The final element, if even, goes into the first half of a GPR.
6381         } else if (Flags.isInConsecutiveRegsLast()) {
6382           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6383           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6384           if (!isLittleEndian)
6385             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6386                                  DAG.getConstant(32, dl, MVT::i32));
6387 
6388         // Non-final even elements are skipped; they will be handled
6389         // together the with subsequent argument on the next go-around.
6390         } else
6391           ArgVal = SDValue();
6392 
6393         if (ArgVal.getNode())
6394           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6395       } else {
6396         if (IsFastCall)
6397           ComputePtrOff();
6398 
6399         // Single-precision floating-point values are mapped to the
6400         // second (rightmost) word of the stack doubleword.
6401         if (Arg.getValueType() == MVT::f32 &&
6402             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6403           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6404           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6405         }
6406 
6407         assert(HasParameterArea &&
6408                "Parameter area must exist to pass an argument in memory.");
6409         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6410                          true, CFlags.IsTailCall, false, MemOpChains,
6411                          TailCallArguments, dl);
6412 
6413         NeededLoad = true;
6414       }
6415       // When passing an array of floats, the array occupies consecutive
6416       // space in the argument area; only round up to the next doubleword
6417       // at the end of the array.  Otherwise, each float takes 8 bytes.
6418       if (!IsFastCall || NeededLoad) {
6419         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6420                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6421         if (Flags.isInConsecutiveRegsLast())
6422           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6423       }
6424       break;
6425     }
6426     case MVT::v4f32:
6427     case MVT::v4i32:
6428     case MVT::v8i16:
6429     case MVT::v16i8:
6430     case MVT::v2f64:
6431     case MVT::v2i64:
6432     case MVT::v1i128:
6433     case MVT::f128:
6434       // These can be scalar arguments or elements of a vector array type
6435       // passed directly.  The latter are used to implement ELFv2 homogenous
6436       // vector aggregates.
6437 
6438       // For a varargs call, named arguments go into VRs or on the stack as
6439       // usual; unnamed arguments always go to the stack or the corresponding
6440       // GPRs when within range.  For now, we always put the value in both
6441       // locations (or even all three).
6442       if (CFlags.IsVarArg) {
6443         assert(HasParameterArea &&
6444                "Parameter area must exist if we have a varargs call.");
6445         // We could elide this store in the case where the object fits
6446         // entirely in R registers.  Maybe later.
6447         SDValue Store =
6448             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6449         MemOpChains.push_back(Store);
6450         if (VR_idx != NumVRs) {
6451           SDValue Load =
6452               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6453           MemOpChains.push_back(Load.getValue(1));
6454           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6455         }
6456         ArgOffset += 16;
6457         for (unsigned i=0; i<16; i+=PtrByteSize) {
6458           if (GPR_idx == NumGPRs)
6459             break;
6460           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6461                                    DAG.getConstant(i, dl, PtrVT));
6462           SDValue Load =
6463               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6464           MemOpChains.push_back(Load.getValue(1));
6465           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6466         }
6467         break;
6468       }
6469 
6470       // Non-varargs Altivec params go into VRs or on the stack.
6471       if (VR_idx != NumVRs) {
6472         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6473       } else {
6474         if (IsFastCall)
6475           ComputePtrOff();
6476 
6477         assert(HasParameterArea &&
6478                "Parameter area must exist to pass an argument in memory.");
6479         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6480                          true, CFlags.IsTailCall, true, MemOpChains,
6481                          TailCallArguments, dl);
6482         if (IsFastCall)
6483           ArgOffset += 16;
6484       }
6485 
6486       if (!IsFastCall)
6487         ArgOffset += 16;
6488       break;
6489     }
6490   }
6491 
6492   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6493          "mismatch in size of parameter area");
6494   (void)NumBytesActuallyUsed;
6495 
6496   if (!MemOpChains.empty())
6497     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6498 
6499   // Check if this is an indirect call (MTCTR/BCTRL).
6500   // See prepareDescriptorIndirectCall and buildCallOperands for more
6501   // information about calls through function pointers in the 64-bit SVR4 ABI.
6502   if (CFlags.IsIndirect) {
6503     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6504     // caller in the TOC save area.
6505     if (isTOCSaveRestoreRequired(Subtarget)) {
6506       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6507       // Load r2 into a virtual register and store it to the TOC save area.
6508       setUsesTOCBasePtr(DAG);
6509       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6510       // TOC save area offset.
6511       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6512       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6513       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6514       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6515                            MachinePointerInfo::getStack(
6516                                DAG.getMachineFunction(), TOCSaveOffset));
6517     }
6518     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6519     // This does not mean the MTCTR instruction must use R12; it's easier
6520     // to model this as an extra parameter, so do that.
6521     if (isELFv2ABI && !CFlags.IsPatchPoint)
6522       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6523   }
6524 
6525   // Build a sequence of copy-to-reg nodes chained together with token chain
6526   // and flag operands which copy the outgoing args into the appropriate regs.
6527   SDValue InFlag;
6528   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6529     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6530                              RegsToPass[i].second, InFlag);
6531     InFlag = Chain.getValue(1);
6532   }
6533 
6534   if (CFlags.IsTailCall && !IsSibCall)
6535     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6536                     TailCallArguments);
6537 
6538   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6539                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6540 }
6541 
6542 // Returns true when the shadow of a general purpose argument register
6543 // in the parameter save area is aligned to at least 'RequiredAlign'.
6544 static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6545   assert(RequiredAlign.value() <= 16 &&
6546          "Required alignment greater than stack alignment.");
6547   switch (Reg) {
6548   default:
6549     report_fatal_error("called on invalid register.");
6550   case PPC::R5:
6551   case PPC::R9:
6552   case PPC::X3:
6553   case PPC::X5:
6554   case PPC::X7:
6555   case PPC::X9:
6556     // These registers are 16 byte aligned which is the most strict aligment
6557     // we can support.
6558     return true;
6559   case PPC::R3:
6560   case PPC::R7:
6561   case PPC::X4:
6562   case PPC::X6:
6563   case PPC::X8:
6564   case PPC::X10:
6565     // The shadow of these registers in the PSA is 8 byte aligned.
6566     return RequiredAlign <= 8;
6567   case PPC::R4:
6568   case PPC::R6:
6569   case PPC::R8:
6570   case PPC::R10:
6571     return RequiredAlign <= 4;
6572   }
6573 }
6574 
6575 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6576                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6577                    CCState &S) {
6578   AIXCCState &State = static_cast<AIXCCState &>(S);
6579   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6580       State.getMachineFunction().getSubtarget());
6581   const bool IsPPC64 = Subtarget.isPPC64();
6582   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6583   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6584 
6585   if (ValVT == MVT::f128)
6586     report_fatal_error("f128 is unimplemented on AIX.");
6587 
6588   if (ArgFlags.isNest())
6589     report_fatal_error("Nest arguments are unimplemented.");
6590 
6591   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6592                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6593                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6594   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6595                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6596                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6597 
6598   static const MCPhysReg VR[] = {// Vector registers.
6599                                  PPC::V2,  PPC::V3,  PPC::V4,  PPC::V5,
6600                                  PPC::V6,  PPC::V7,  PPC::V8,  PPC::V9,
6601                                  PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6602 
6603   if (ArgFlags.isByVal()) {
6604     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6605       report_fatal_error("Pass-by-value arguments with alignment greater than "
6606                          "register width are not supported.");
6607 
6608     const unsigned ByValSize = ArgFlags.getByValSize();
6609 
6610     // An empty aggregate parameter takes up no storage and no registers,
6611     // but needs a MemLoc for a stack slot for the formal arguments side.
6612     if (ByValSize == 0) {
6613       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6614                                        State.getNextStackOffset(), RegVT,
6615                                        LocInfo));
6616       return false;
6617     }
6618 
6619     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6620     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6621     for (const unsigned E = Offset + StackSize; Offset < E;
6622          Offset += PtrAlign.value()) {
6623       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6624         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6625       else {
6626         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6627                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6628                                          LocInfo));
6629         break;
6630       }
6631     }
6632     return false;
6633   }
6634 
6635   // Arguments always reserve parameter save area.
6636   switch (ValVT.SimpleTy) {
6637   default:
6638     report_fatal_error("Unhandled value type for argument.");
6639   case MVT::i64:
6640     // i64 arguments should have been split to i32 for PPC32.
6641     assert(IsPPC64 && "PPC32 should have split i64 values.");
6642     LLVM_FALLTHROUGH;
6643   case MVT::i1:
6644   case MVT::i32: {
6645     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6646     // AIX integer arguments are always passed in register width.
6647     if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6648       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6649                                   : CCValAssign::LocInfo::ZExt;
6650     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6651       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6652     else
6653       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6654 
6655     return false;
6656   }
6657   case MVT::f32:
6658   case MVT::f64: {
6659     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6660     const unsigned StoreSize = LocVT.getStoreSize();
6661     // Floats are always 4-byte aligned in the PSA on AIX.
6662     // This includes f64 in 64-bit mode for ABI compatibility.
6663     const unsigned Offset =
6664         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6665     unsigned FReg = State.AllocateReg(FPR);
6666     if (FReg)
6667       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6668 
6669     // Reserve and initialize GPRs or initialize the PSA as required.
6670     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6671       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6672         assert(FReg && "An FPR should be available when a GPR is reserved.");
6673         if (State.isVarArg()) {
6674           // Successfully reserved GPRs are only initialized for vararg calls.
6675           // Custom handling is required for:
6676           //   f64 in PPC32 needs to be split into 2 GPRs.
6677           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6678           State.addLoc(
6679               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6680         }
6681       } else {
6682         // If there are insufficient GPRs, the PSA needs to be initialized.
6683         // Initialization occurs even if an FPR was initialized for
6684         // compatibility with the AIX XL compiler. The full memory for the
6685         // argument will be initialized even if a prior word is saved in GPR.
6686         // A custom memLoc is used when the argument also passes in FPR so
6687         // that the callee handling can skip over it easily.
6688         State.addLoc(
6689             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6690                                              LocInfo)
6691                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6692         break;
6693       }
6694     }
6695 
6696     return false;
6697   }
6698   case MVT::v4f32:
6699   case MVT::v4i32:
6700   case MVT::v8i16:
6701   case MVT::v16i8:
6702   case MVT::v2i64:
6703   case MVT::v2f64:
6704   case MVT::v1i128: {
6705     const unsigned VecSize = 16;
6706     const Align VecAlign(VecSize);
6707 
6708     if (!State.isVarArg()) {
6709       // If there are vector registers remaining we don't consume any stack
6710       // space.
6711       if (unsigned VReg = State.AllocateReg(VR)) {
6712         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6713         return false;
6714       }
6715       // Vectors passed on the stack do not shadow GPRs or FPRs even though they
6716       // might be allocated in the portion of the PSA that is shadowed by the
6717       // GPRs.
6718       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6719       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6720       return false;
6721     }
6722 
6723     const unsigned PtrSize = IsPPC64 ? 8 : 4;
6724     ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6725 
6726     unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
6727     // Burn any underaligned registers and their shadowed stack space until
6728     // we reach the required alignment.
6729     while (NextRegIndex != GPRs.size() &&
6730            !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
6731       // Shadow allocate register and its stack shadow.
6732       unsigned Reg = State.AllocateReg(GPRs);
6733       State.AllocateStack(PtrSize, PtrAlign);
6734       assert(Reg && "Allocating register unexpectedly failed.");
6735       (void)Reg;
6736       NextRegIndex = State.getFirstUnallocated(GPRs);
6737     }
6738 
6739     // Vectors that are passed as fixed arguments are handled differently.
6740     // They are passed in VRs if any are available (unlike arguments passed
6741     // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
6742     // functions)
6743     if (State.isFixed(ValNo)) {
6744       if (unsigned VReg = State.AllocateReg(VR)) {
6745         State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
6746         // Shadow allocate GPRs and stack space even though we pass in a VR.
6747         for (unsigned I = 0; I != VecSize; I += PtrSize)
6748           State.AllocateReg(GPRs);
6749         State.AllocateStack(VecSize, VecAlign);
6750         return false;
6751       }
6752       // No vector registers remain so pass on the stack.
6753       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6754       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6755       return false;
6756     }
6757 
6758     // If all GPRS are consumed then we pass the argument fully on the stack.
6759     if (NextRegIndex == GPRs.size()) {
6760       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6761       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6762       return false;
6763     }
6764 
6765     // Corner case for 32-bit codegen. We have 2 registers to pass the first
6766     // half of the argument, and then need to pass the remaining half on the
6767     // stack.
6768     if (GPRs[NextRegIndex] == PPC::R9) {
6769       const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6770       State.addLoc(
6771           CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6772 
6773       const unsigned FirstReg = State.AllocateReg(PPC::R9);
6774       const unsigned SecondReg = State.AllocateReg(PPC::R10);
6775       assert(FirstReg && SecondReg &&
6776              "Allocating R9 or R10 unexpectedly failed.");
6777       State.addLoc(
6778           CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
6779       State.addLoc(
6780           CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
6781       return false;
6782     }
6783 
6784     // We have enough GPRs to fully pass the vector argument, and we have
6785     // already consumed any underaligned registers. Start with the custom
6786     // MemLoc and then the custom RegLocs.
6787     const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
6788     State.addLoc(
6789         CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6790     for (unsigned I = 0; I != VecSize; I += PtrSize) {
6791       const unsigned Reg = State.AllocateReg(GPRs);
6792       assert(Reg && "Failed to allocated register for vararg vector argument");
6793       State.addLoc(
6794           CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6795     }
6796     return false;
6797   }
6798   }
6799   return true;
6800 }
6801 
6802 // So far, this function is only used by LowerFormalArguments_AIX()
6803 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6804                                                     bool IsPPC64,
6805                                                     bool HasP8Vector,
6806                                                     bool HasVSX) {
6807   assert((IsPPC64 || SVT != MVT::i64) &&
6808          "i64 should have been split for 32-bit codegen.");
6809 
6810   switch (SVT) {
6811   default:
6812     report_fatal_error("Unexpected value type for formal argument");
6813   case MVT::i1:
6814   case MVT::i32:
6815   case MVT::i64:
6816     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6817   case MVT::f32:
6818     return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
6819   case MVT::f64:
6820     return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
6821   case MVT::v4f32:
6822   case MVT::v4i32:
6823   case MVT::v8i16:
6824   case MVT::v16i8:
6825   case MVT::v2i64:
6826   case MVT::v2f64:
6827   case MVT::v1i128:
6828     return &PPC::VRRCRegClass;
6829   }
6830 }
6831 
6832 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6833                                         SelectionDAG &DAG, SDValue ArgValue,
6834                                         MVT LocVT, const SDLoc &dl) {
6835   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6836   assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
6837 
6838   if (Flags.isSExt())
6839     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6840                            DAG.getValueType(ValVT));
6841   else if (Flags.isZExt())
6842     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6843                            DAG.getValueType(ValVT));
6844 
6845   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6846 }
6847 
6848 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6849   const unsigned LASize = FL->getLinkageSize();
6850 
6851   if (PPC::GPRCRegClass.contains(Reg)) {
6852     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6853            "Reg must be a valid argument register!");
6854     return LASize + 4 * (Reg - PPC::R3);
6855   }
6856 
6857   if (PPC::G8RCRegClass.contains(Reg)) {
6858     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6859            "Reg must be a valid argument register!");
6860     return LASize + 8 * (Reg - PPC::X3);
6861   }
6862 
6863   llvm_unreachable("Only general purpose registers expected.");
6864 }
6865 
6866 //   AIX ABI Stack Frame Layout:
6867 //
6868 //   Low Memory +--------------------------------------------+
6869 //   SP   +---> | Back chain                                 | ---+
6870 //        |     +--------------------------------------------+    |
6871 //        |     | Saved Condition Register                   |    |
6872 //        |     +--------------------------------------------+    |
6873 //        |     | Saved Linkage Register                     |    |
6874 //        |     +--------------------------------------------+    | Linkage Area
6875 //        |     | Reserved for compilers                     |    |
6876 //        |     +--------------------------------------------+    |
6877 //        |     | Reserved for binders                       |    |
6878 //        |     +--------------------------------------------+    |
6879 //        |     | Saved TOC pointer                          | ---+
6880 //        |     +--------------------------------------------+
6881 //        |     | Parameter save area                        |
6882 //        |     +--------------------------------------------+
6883 //        |     | Alloca space                               |
6884 //        |     +--------------------------------------------+
6885 //        |     | Local variable space                       |
6886 //        |     +--------------------------------------------+
6887 //        |     | Float/int conversion temporary             |
6888 //        |     +--------------------------------------------+
6889 //        |     | Save area for AltiVec registers            |
6890 //        |     +--------------------------------------------+
6891 //        |     | AltiVec alignment padding                  |
6892 //        |     +--------------------------------------------+
6893 //        |     | Save area for VRSAVE register              |
6894 //        |     +--------------------------------------------+
6895 //        |     | Save area for General Purpose registers    |
6896 //        |     +--------------------------------------------+
6897 //        |     | Save area for Floating Point registers     |
6898 //        |     +--------------------------------------------+
6899 //        +---- | Back chain                                 |
6900 // High Memory  +--------------------------------------------+
6901 //
6902 //  Specifications:
6903 //  AIX 7.2 Assembler Language Reference
6904 //  Subroutine linkage convention
6905 
6906 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6907     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6908     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6909     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6910 
6911   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6912           CallConv == CallingConv::Fast) &&
6913          "Unexpected calling convention!");
6914 
6915   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6916     report_fatal_error("Tail call support is unimplemented on AIX.");
6917 
6918   if (useSoftFloat())
6919     report_fatal_error("Soft float support is unimplemented on AIX.");
6920 
6921   const PPCSubtarget &Subtarget =
6922       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6923 
6924   const bool IsPPC64 = Subtarget.isPPC64();
6925   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6926 
6927   // Assign locations to all of the incoming arguments.
6928   SmallVector<CCValAssign, 16> ArgLocs;
6929   MachineFunction &MF = DAG.getMachineFunction();
6930   MachineFrameInfo &MFI = MF.getFrameInfo();
6931   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6932   AIXCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6933 
6934   const EVT PtrVT = getPointerTy(MF.getDataLayout());
6935   // Reserve space for the linkage area on the stack.
6936   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6937   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
6938   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6939 
6940   SmallVector<SDValue, 8> MemOps;
6941 
6942   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
6943     CCValAssign &VA = ArgLocs[I++];
6944     MVT LocVT = VA.getLocVT();
6945     MVT ValVT = VA.getValVT();
6946     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
6947     // For compatibility with the AIX XL compiler, the float args in the
6948     // parameter save area are initialized even if the argument is available
6949     // in register.  The caller is required to initialize both the register
6950     // and memory, however, the callee can choose to expect it in either.
6951     // The memloc is dismissed here because the argument is retrieved from
6952     // the register.
6953     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
6954       continue;
6955 
6956     auto HandleMemLoc = [&]() {
6957       const unsigned LocSize = LocVT.getStoreSize();
6958       const unsigned ValSize = ValVT.getStoreSize();
6959       assert((ValSize <= LocSize) &&
6960              "Object size is larger than size of MemLoc");
6961       int CurArgOffset = VA.getLocMemOffset();
6962       // Objects are right-justified because AIX is big-endian.
6963       if (LocSize > ValSize)
6964         CurArgOffset += LocSize - ValSize;
6965       // Potential tail calls could cause overwriting of argument stack slots.
6966       const bool IsImmutable =
6967           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
6968             (CallConv == CallingConv::Fast));
6969       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
6970       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
6971       SDValue ArgValue =
6972           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
6973       InVals.push_back(ArgValue);
6974     };
6975 
6976     // Vector arguments to VaArg functions are passed both on the stack, and
6977     // in any available GPRs. Load the value from the stack and add the GPRs
6978     // as live ins.
6979     if (VA.isMemLoc() && VA.needsCustom()) {
6980       assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
6981       assert(isVarArg && "Only use custom memloc for vararg.");
6982       // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
6983       // matching custom RegLocs.
6984       const unsigned OriginalValNo = VA.getValNo();
6985       (void)OriginalValNo;
6986 
6987       auto HandleCustomVecRegLoc = [&]() {
6988         assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
6989                "Missing custom RegLoc.");
6990         VA = ArgLocs[I++];
6991         assert(VA.getValVT().isVector() &&
6992                "Unexpected Val type for custom RegLoc.");
6993         assert(VA.getValNo() == OriginalValNo &&
6994                "ValNo mismatch between custom MemLoc and RegLoc.");
6995         MVT::SimpleValueType SVT = VA.getLocVT().SimpleTy;
6996         MF.addLiveIn(VA.getLocReg(),
6997                      getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
6998                                        Subtarget.hasVSX()));
6999       };
7000 
7001       HandleMemLoc();
7002       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7003       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7004       // R10.
7005       HandleCustomVecRegLoc();
7006       HandleCustomVecRegLoc();
7007 
7008       // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7009       // we passed the vector in R5, R6, R7 and R8.
7010       if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7011         assert(!IsPPC64 &&
7012                "Only 2 custom RegLocs expected for 64-bit codegen.");
7013         HandleCustomVecRegLoc();
7014         HandleCustomVecRegLoc();
7015       }
7016 
7017       continue;
7018     }
7019 
7020     if (VA.isRegLoc()) {
7021       if (VA.getValVT().isScalarInteger())
7022         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7023       else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7024         switch (VA.getValVT().SimpleTy) {
7025         default:
7026           report_fatal_error("Unhandled value type for argument.");
7027         case MVT::f32:
7028           FuncInfo->appendParameterType(PPCFunctionInfo::ShortFloatingPoint);
7029           break;
7030         case MVT::f64:
7031           FuncInfo->appendParameterType(PPCFunctionInfo::LongFloatingPoint);
7032           break;
7033         }
7034       } else if (VA.getValVT().isVector()) {
7035         switch (VA.getValVT().SimpleTy) {
7036         default:
7037           report_fatal_error("Unhandled value type for argument.");
7038         case MVT::v16i8:
7039           FuncInfo->appendParameterType(PPCFunctionInfo::VectorChar);
7040           break;
7041         case MVT::v8i16:
7042           FuncInfo->appendParameterType(PPCFunctionInfo::VectorShort);
7043           break;
7044         case MVT::v4i32:
7045         case MVT::v2i64:
7046         case MVT::v1i128:
7047           FuncInfo->appendParameterType(PPCFunctionInfo::VectorInt);
7048           break;
7049         case MVT::v4f32:
7050         case MVT::v2f64:
7051           FuncInfo->appendParameterType(PPCFunctionInfo::VectorFloat);
7052           break;
7053         }
7054       }
7055     }
7056 
7057     if (Flags.isByVal() && VA.isMemLoc()) {
7058       const unsigned Size =
7059           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7060                   PtrByteSize);
7061       const int FI = MF.getFrameInfo().CreateFixedObject(
7062           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7063           /* IsAliased */ true);
7064       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7065       InVals.push_back(FIN);
7066 
7067       continue;
7068     }
7069 
7070     if (Flags.isByVal()) {
7071       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7072 
7073       const MCPhysReg ArgReg = VA.getLocReg();
7074       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7075 
7076       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7077         report_fatal_error("Over aligned byvals not supported yet.");
7078 
7079       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7080       const int FI = MF.getFrameInfo().CreateFixedObject(
7081           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7082           /* IsAliased */ true);
7083       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7084       InVals.push_back(FIN);
7085 
7086       // Add live ins for all the RegLocs for the same ByVal.
7087       const TargetRegisterClass *RegClass =
7088           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7089 
7090       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7091                                                unsigned Offset) {
7092         const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7093         // Since the callers side has left justified the aggregate in the
7094         // register, we can simply store the entire register into the stack
7095         // slot.
7096         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7097         // The store to the fixedstack object is needed becuase accessing a
7098         // field of the ByVal will use a gep and load. Ideally we will optimize
7099         // to extracting the value from the register directly, and elide the
7100         // stores when the arguments address is not taken, but that will need to
7101         // be future work.
7102         SDValue Store = DAG.getStore(
7103             CopyFrom.getValue(1), dl, CopyFrom,
7104             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7105             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7106 
7107         MemOps.push_back(Store);
7108       };
7109 
7110       unsigned Offset = 0;
7111       HandleRegLoc(VA.getLocReg(), Offset);
7112       Offset += PtrByteSize;
7113       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7114            Offset += PtrByteSize) {
7115         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7116                "RegLocs should be for ByVal argument.");
7117 
7118         const CCValAssign RL = ArgLocs[I++];
7119         HandleRegLoc(RL.getLocReg(), Offset);
7120         FuncInfo->appendParameterType(PPCFunctionInfo::FixedType);
7121       }
7122 
7123       if (Offset != StackSize) {
7124         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7125                "Expected MemLoc for remaining bytes.");
7126         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7127         // Consume the MemLoc.The InVal has already been emitted, so nothing
7128         // more needs to be done.
7129         ++I;
7130       }
7131 
7132       continue;
7133     }
7134 
7135     if (VA.isRegLoc() && !VA.needsCustom()) {
7136       MVT::SimpleValueType SVT = ValVT.SimpleTy;
7137       Register VReg =
7138           MF.addLiveIn(VA.getLocReg(),
7139                        getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7140                                          Subtarget.hasVSX()));
7141       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7142       if (ValVT.isScalarInteger() &&
7143           (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7144         ArgValue =
7145             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7146       }
7147       InVals.push_back(ArgValue);
7148       continue;
7149     }
7150     if (VA.isMemLoc()) {
7151       HandleMemLoc();
7152       continue;
7153     }
7154   }
7155 
7156   // On AIX a minimum of 8 words is saved to the parameter save area.
7157   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7158   // Area that is at least reserved in the caller of this function.
7159   unsigned CallerReservedArea =
7160       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7161 
7162   // Set the size that is at least reserved in caller of this function. Tail
7163   // call optimized function's reserved stack space needs to be aligned so
7164   // that taking the difference between two stack areas will result in an
7165   // aligned stack.
7166   CallerReservedArea =
7167       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7168   FuncInfo->setMinReservedArea(CallerReservedArea);
7169 
7170   if (isVarArg) {
7171     FuncInfo->setVarArgsFrameIndex(
7172         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7173     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7174 
7175     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7176                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7177 
7178     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7179                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7180     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7181 
7182     // The fixed integer arguments of a variadic function are stored to the
7183     // VarArgsFrameIndex on the stack so that they may be loaded by
7184     // dereferencing the result of va_next.
7185     for (unsigned GPRIndex =
7186              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7187          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7188 
7189       const Register VReg =
7190           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7191                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7192 
7193       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7194       SDValue Store =
7195           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7196       MemOps.push_back(Store);
7197       // Increment the address for the next argument to store.
7198       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7199       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7200     }
7201   }
7202 
7203   if (!MemOps.empty())
7204     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7205 
7206   return Chain;
7207 }
7208 
7209 SDValue PPCTargetLowering::LowerCall_AIX(
7210     SDValue Chain, SDValue Callee, CallFlags CFlags,
7211     const SmallVectorImpl<ISD::OutputArg> &Outs,
7212     const SmallVectorImpl<SDValue> &OutVals,
7213     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7214     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7215     const CallBase *CB) const {
7216   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7217   // AIX ABI stack frame layout.
7218 
7219   assert((CFlags.CallConv == CallingConv::C ||
7220           CFlags.CallConv == CallingConv::Cold ||
7221           CFlags.CallConv == CallingConv::Fast) &&
7222          "Unexpected calling convention!");
7223 
7224   if (CFlags.IsPatchPoint)
7225     report_fatal_error("This call type is unimplemented on AIX.");
7226 
7227   const PPCSubtarget& Subtarget =
7228       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7229 
7230   MachineFunction &MF = DAG.getMachineFunction();
7231   SmallVector<CCValAssign, 16> ArgLocs;
7232   AIXCCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7233                     *DAG.getContext());
7234 
7235   // Reserve space for the linkage save area (LSA) on the stack.
7236   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7237   //   [SP][CR][LR][2 x reserved][TOC].
7238   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7239   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7240   const bool IsPPC64 = Subtarget.isPPC64();
7241   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7242   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7243   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7244   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7245 
7246   // The prolog code of the callee may store up to 8 GPR argument registers to
7247   // the stack, allowing va_start to index over them in memory if the callee
7248   // is variadic.
7249   // Because we cannot tell if this is needed on the caller side, we have to
7250   // conservatively assume that it is needed.  As such, make sure we have at
7251   // least enough stack space for the caller to store the 8 GPRs.
7252   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7253   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7254                                      CCInfo.getNextStackOffset());
7255 
7256   // Adjust the stack pointer for the new arguments...
7257   // These operations are automatically eliminated by the prolog/epilog pass.
7258   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7259   SDValue CallSeqStart = Chain;
7260 
7261   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7262   SmallVector<SDValue, 8> MemOpChains;
7263 
7264   // Set up a copy of the stack pointer for loading and storing any
7265   // arguments that may not fit in the registers available for argument
7266   // passing.
7267   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7268                                    : DAG.getRegister(PPC::R1, MVT::i32);
7269 
7270   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7271     const unsigned ValNo = ArgLocs[I].getValNo();
7272     SDValue Arg = OutVals[ValNo];
7273     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7274 
7275     if (Flags.isByVal()) {
7276       const unsigned ByValSize = Flags.getByValSize();
7277 
7278       // Nothing to do for zero-sized ByVals on the caller side.
7279       if (!ByValSize) {
7280         ++I;
7281         continue;
7282       }
7283 
7284       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7285         return DAG.getExtLoad(
7286             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7287             (LoadOffset != 0)
7288                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7289                 : Arg,
7290             MachinePointerInfo(), VT);
7291       };
7292 
7293       unsigned LoadOffset = 0;
7294 
7295       // Initialize registers, which are fully occupied by the by-val argument.
7296       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7297         SDValue Load = GetLoad(PtrVT, LoadOffset);
7298         MemOpChains.push_back(Load.getValue(1));
7299         LoadOffset += PtrByteSize;
7300         const CCValAssign &ByValVA = ArgLocs[I++];
7301         assert(ByValVA.getValNo() == ValNo &&
7302                "Unexpected location for pass-by-value argument.");
7303         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7304       }
7305 
7306       if (LoadOffset == ByValSize)
7307         continue;
7308 
7309       // There must be one more loc to handle the remainder.
7310       assert(ArgLocs[I].getValNo() == ValNo &&
7311              "Expected additional location for by-value argument.");
7312 
7313       if (ArgLocs[I].isMemLoc()) {
7314         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7315         const CCValAssign &ByValVA = ArgLocs[I++];
7316         ISD::ArgFlagsTy MemcpyFlags = Flags;
7317         // Only memcpy the bytes that don't pass in register.
7318         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7319         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7320             (LoadOffset != 0)
7321                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7322                 : Arg,
7323             DAG.getObjectPtrOffset(dl, StackPtr,
7324                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7325             CallSeqStart, MemcpyFlags, DAG, dl);
7326         continue;
7327       }
7328 
7329       // Initialize the final register residue.
7330       // Any residue that occupies the final by-val arg register must be
7331       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7332       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7333       // 2 and 1 byte loads.
7334       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7335       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7336              "Unexpected register residue for by-value argument.");
7337       SDValue ResidueVal;
7338       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7339         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7340         const MVT VT =
7341             N == 1 ? MVT::i8
7342                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7343         SDValue Load = GetLoad(VT, LoadOffset);
7344         MemOpChains.push_back(Load.getValue(1));
7345         LoadOffset += N;
7346         Bytes += N;
7347 
7348         // By-val arguments are passed left-justfied in register.
7349         // Every load here needs to be shifted, otherwise a full register load
7350         // should have been used.
7351         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7352                "Unexpected load emitted during handling of pass-by-value "
7353                "argument.");
7354         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7355         EVT ShiftAmountTy =
7356             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7357         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7358         SDValue ShiftedLoad =
7359             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7360         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7361                                               ShiftedLoad)
7362                                 : ShiftedLoad;
7363       }
7364 
7365       const CCValAssign &ByValVA = ArgLocs[I++];
7366       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7367       continue;
7368     }
7369 
7370     CCValAssign &VA = ArgLocs[I++];
7371     const MVT LocVT = VA.getLocVT();
7372     const MVT ValVT = VA.getValVT();
7373 
7374     switch (VA.getLocInfo()) {
7375     default:
7376       report_fatal_error("Unexpected argument extension type.");
7377     case CCValAssign::Full:
7378       break;
7379     case CCValAssign::ZExt:
7380       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7381       break;
7382     case CCValAssign::SExt:
7383       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7384       break;
7385     }
7386 
7387     if (VA.isRegLoc() && !VA.needsCustom()) {
7388       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7389       continue;
7390     }
7391 
7392     // Vector arguments passed to VarArg functions need custom handling when
7393     // they are passed (at least partially) in GPRs.
7394     if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7395       assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7396       // Store value to its stack slot.
7397       SDValue PtrOff =
7398           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7399       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7400       SDValue Store =
7401           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7402       MemOpChains.push_back(Store);
7403       const unsigned OriginalValNo = VA.getValNo();
7404       // Then load the GPRs from the stack
7405       unsigned LoadOffset = 0;
7406       auto HandleCustomVecRegLoc = [&]() {
7407         assert(I != E && "Unexpected end of CCvalAssigns.");
7408         assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7409                "Expected custom RegLoc.");
7410         CCValAssign RegVA = ArgLocs[I++];
7411         assert(RegVA.getValNo() == OriginalValNo &&
7412                "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7413         SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7414                                   DAG.getConstant(LoadOffset, dl, PtrVT));
7415         SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7416         MemOpChains.push_back(Load.getValue(1));
7417         RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7418         LoadOffset += PtrByteSize;
7419       };
7420 
7421       // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7422       // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7423       // R10.
7424       HandleCustomVecRegLoc();
7425       HandleCustomVecRegLoc();
7426 
7427       if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7428           ArgLocs[I].getValNo() == OriginalValNo) {
7429         assert(!IsPPC64 &&
7430                "Only 2 custom RegLocs expected for 64-bit codegen.");
7431         HandleCustomVecRegLoc();
7432         HandleCustomVecRegLoc();
7433       }
7434 
7435       continue;
7436     }
7437 
7438     if (VA.isMemLoc()) {
7439       SDValue PtrOff =
7440           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7441       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7442       MemOpChains.push_back(
7443           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7444 
7445       continue;
7446     }
7447 
7448     if (!ValVT.isFloatingPoint())
7449       report_fatal_error(
7450           "Unexpected register handling for calling convention.");
7451 
7452     // Custom handling is used for GPR initializations for vararg float
7453     // arguments.
7454     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7455            LocVT.isInteger() &&
7456            "Custom register handling only expected for VarArg.");
7457 
7458     SDValue ArgAsInt =
7459         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7460 
7461     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7462       // f32 in 32-bit GPR
7463       // f64 in 64-bit GPR
7464       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7465     else if (Arg.getValueType().getFixedSizeInBits() <
7466              LocVT.getFixedSizeInBits())
7467       // f32 in 64-bit GPR.
7468       RegsToPass.push_back(std::make_pair(
7469           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7470     else {
7471       // f64 in two 32-bit GPRs
7472       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7473       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7474              "Unexpected custom register for argument!");
7475       CCValAssign &GPR1 = VA;
7476       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7477                                      DAG.getConstant(32, dl, MVT::i8));
7478       RegsToPass.push_back(std::make_pair(
7479           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7480 
7481       if (I != E) {
7482         // If only 1 GPR was available, there will only be one custom GPR and
7483         // the argument will also pass in memory.
7484         CCValAssign &PeekArg = ArgLocs[I];
7485         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7486           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7487           CCValAssign &GPR2 = ArgLocs[I++];
7488           RegsToPass.push_back(std::make_pair(
7489               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7490         }
7491       }
7492     }
7493   }
7494 
7495   if (!MemOpChains.empty())
7496     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7497 
7498   // For indirect calls, we need to save the TOC base to the stack for
7499   // restoration after the call.
7500   if (CFlags.IsIndirect) {
7501     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7502     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7503     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7504     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7505     const unsigned TOCSaveOffset =
7506         Subtarget.getFrameLowering()->getTOCSaveOffset();
7507 
7508     setUsesTOCBasePtr(DAG);
7509     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7510     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7511     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7512     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7513     Chain = DAG.getStore(
7514         Val.getValue(1), dl, Val, AddPtr,
7515         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7516   }
7517 
7518   // Build a sequence of copy-to-reg nodes chained together with token chain
7519   // and flag operands which copy the outgoing args into the appropriate regs.
7520   SDValue InFlag;
7521   for (auto Reg : RegsToPass) {
7522     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7523     InFlag = Chain.getValue(1);
7524   }
7525 
7526   const int SPDiff = 0;
7527   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7528                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7529 }
7530 
7531 bool
7532 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7533                                   MachineFunction &MF, bool isVarArg,
7534                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7535                                   LLVMContext &Context) const {
7536   SmallVector<CCValAssign, 16> RVLocs;
7537   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7538   return CCInfo.CheckReturn(
7539       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7540                 ? RetCC_PPC_Cold
7541                 : RetCC_PPC);
7542 }
7543 
7544 SDValue
7545 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7546                                bool isVarArg,
7547                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7548                                const SmallVectorImpl<SDValue> &OutVals,
7549                                const SDLoc &dl, SelectionDAG &DAG) const {
7550   SmallVector<CCValAssign, 16> RVLocs;
7551   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7552                  *DAG.getContext());
7553   CCInfo.AnalyzeReturn(Outs,
7554                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7555                            ? RetCC_PPC_Cold
7556                            : RetCC_PPC);
7557 
7558   SDValue Flag;
7559   SmallVector<SDValue, 4> RetOps(1, Chain);
7560 
7561   // Copy the result values into the output registers.
7562   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7563     CCValAssign &VA = RVLocs[i];
7564     assert(VA.isRegLoc() && "Can only return in registers!");
7565 
7566     SDValue Arg = OutVals[RealResIdx];
7567 
7568     switch (VA.getLocInfo()) {
7569     default: llvm_unreachable("Unknown loc info!");
7570     case CCValAssign::Full: break;
7571     case CCValAssign::AExt:
7572       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7573       break;
7574     case CCValAssign::ZExt:
7575       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7576       break;
7577     case CCValAssign::SExt:
7578       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7579       break;
7580     }
7581     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7582       bool isLittleEndian = Subtarget.isLittleEndian();
7583       // Legalize ret f64 -> ret 2 x i32.
7584       SDValue SVal =
7585           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7586                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7587       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7588       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7589       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7590                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7591       Flag = Chain.getValue(1);
7592       VA = RVLocs[++i]; // skip ahead to next loc
7593       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7594     } else
7595       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7596     Flag = Chain.getValue(1);
7597     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7598   }
7599 
7600   RetOps[0] = Chain;  // Update chain.
7601 
7602   // Add the flag if we have it.
7603   if (Flag.getNode())
7604     RetOps.push_back(Flag);
7605 
7606   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7607 }
7608 
7609 SDValue
7610 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7611                                                 SelectionDAG &DAG) const {
7612   SDLoc dl(Op);
7613 
7614   // Get the correct type for integers.
7615   EVT IntVT = Op.getValueType();
7616 
7617   // Get the inputs.
7618   SDValue Chain = Op.getOperand(0);
7619   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7620   // Build a DYNAREAOFFSET node.
7621   SDValue Ops[2] = {Chain, FPSIdx};
7622   SDVTList VTs = DAG.getVTList(IntVT);
7623   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7624 }
7625 
7626 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7627                                              SelectionDAG &DAG) const {
7628   // When we pop the dynamic allocation we need to restore the SP link.
7629   SDLoc dl(Op);
7630 
7631   // Get the correct type for pointers.
7632   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7633 
7634   // Construct the stack pointer operand.
7635   bool isPPC64 = Subtarget.isPPC64();
7636   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7637   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7638 
7639   // Get the operands for the STACKRESTORE.
7640   SDValue Chain = Op.getOperand(0);
7641   SDValue SaveSP = Op.getOperand(1);
7642 
7643   // Load the old link SP.
7644   SDValue LoadLinkSP =
7645       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7646 
7647   // Restore the stack pointer.
7648   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7649 
7650   // Store the old link SP.
7651   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7652 }
7653 
7654 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7655   MachineFunction &MF = DAG.getMachineFunction();
7656   bool isPPC64 = Subtarget.isPPC64();
7657   EVT PtrVT = getPointerTy(MF.getDataLayout());
7658 
7659   // Get current frame pointer save index.  The users of this index will be
7660   // primarily DYNALLOC instructions.
7661   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7662   int RASI = FI->getReturnAddrSaveIndex();
7663 
7664   // If the frame pointer save index hasn't been defined yet.
7665   if (!RASI) {
7666     // Find out what the fix offset of the frame pointer save area.
7667     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7668     // Allocate the frame index for frame pointer save area.
7669     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7670     // Save the result.
7671     FI->setReturnAddrSaveIndex(RASI);
7672   }
7673   return DAG.getFrameIndex(RASI, PtrVT);
7674 }
7675 
7676 SDValue
7677 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7678   MachineFunction &MF = DAG.getMachineFunction();
7679   bool isPPC64 = Subtarget.isPPC64();
7680   EVT PtrVT = getPointerTy(MF.getDataLayout());
7681 
7682   // Get current frame pointer save index.  The users of this index will be
7683   // primarily DYNALLOC instructions.
7684   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7685   int FPSI = FI->getFramePointerSaveIndex();
7686 
7687   // If the frame pointer save index hasn't been defined yet.
7688   if (!FPSI) {
7689     // Find out what the fix offset of the frame pointer save area.
7690     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7691     // Allocate the frame index for frame pointer save area.
7692     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7693     // Save the result.
7694     FI->setFramePointerSaveIndex(FPSI);
7695   }
7696   return DAG.getFrameIndex(FPSI, PtrVT);
7697 }
7698 
7699 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7700                                                    SelectionDAG &DAG) const {
7701   MachineFunction &MF = DAG.getMachineFunction();
7702   // Get the inputs.
7703   SDValue Chain = Op.getOperand(0);
7704   SDValue Size  = Op.getOperand(1);
7705   SDLoc dl(Op);
7706 
7707   // Get the correct type for pointers.
7708   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7709   // Negate the size.
7710   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7711                                 DAG.getConstant(0, dl, PtrVT), Size);
7712   // Construct a node for the frame pointer save index.
7713   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7714   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7715   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7716   if (hasInlineStackProbe(MF))
7717     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7718   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7719 }
7720 
7721 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7722                                                      SelectionDAG &DAG) const {
7723   MachineFunction &MF = DAG.getMachineFunction();
7724 
7725   bool isPPC64 = Subtarget.isPPC64();
7726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7727 
7728   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7729   return DAG.getFrameIndex(FI, PtrVT);
7730 }
7731 
7732 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7733                                                SelectionDAG &DAG) const {
7734   SDLoc DL(Op);
7735   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7736                      DAG.getVTList(MVT::i32, MVT::Other),
7737                      Op.getOperand(0), Op.getOperand(1));
7738 }
7739 
7740 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7741                                                 SelectionDAG &DAG) const {
7742   SDLoc DL(Op);
7743   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7744                      Op.getOperand(0), Op.getOperand(1));
7745 }
7746 
7747 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7748   if (Op.getValueType().isVector())
7749     return LowerVectorLoad(Op, DAG);
7750 
7751   assert(Op.getValueType() == MVT::i1 &&
7752          "Custom lowering only for i1 loads");
7753 
7754   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7755 
7756   SDLoc dl(Op);
7757   LoadSDNode *LD = cast<LoadSDNode>(Op);
7758 
7759   SDValue Chain = LD->getChain();
7760   SDValue BasePtr = LD->getBasePtr();
7761   MachineMemOperand *MMO = LD->getMemOperand();
7762 
7763   SDValue NewLD =
7764       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7765                      BasePtr, MVT::i8, MMO);
7766   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7767 
7768   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7769   return DAG.getMergeValues(Ops, dl);
7770 }
7771 
7772 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7773   if (Op.getOperand(1).getValueType().isVector())
7774     return LowerVectorStore(Op, DAG);
7775 
7776   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7777          "Custom lowering only for i1 stores");
7778 
7779   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7780 
7781   SDLoc dl(Op);
7782   StoreSDNode *ST = cast<StoreSDNode>(Op);
7783 
7784   SDValue Chain = ST->getChain();
7785   SDValue BasePtr = ST->getBasePtr();
7786   SDValue Value = ST->getValue();
7787   MachineMemOperand *MMO = ST->getMemOperand();
7788 
7789   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7790                       Value);
7791   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7792 }
7793 
7794 // FIXME: Remove this once the ANDI glue bug is fixed:
7795 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7796   assert(Op.getValueType() == MVT::i1 &&
7797          "Custom lowering only for i1 results");
7798 
7799   SDLoc DL(Op);
7800   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7801 }
7802 
7803 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7804                                                SelectionDAG &DAG) const {
7805 
7806   // Implements a vector truncate that fits in a vector register as a shuffle.
7807   // We want to legalize vector truncates down to where the source fits in
7808   // a vector register (and target is therefore smaller than vector register
7809   // size).  At that point legalization will try to custom lower the sub-legal
7810   // result and get here - where we can contain the truncate as a single target
7811   // operation.
7812 
7813   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7814   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7815   //
7816   // We will implement it for big-endian ordering as this (where x denotes
7817   // undefined):
7818   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7819   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7820   //
7821   // The same operation in little-endian ordering will be:
7822   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7823   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7824 
7825   EVT TrgVT = Op.getValueType();
7826   assert(TrgVT.isVector() && "Vector type expected.");
7827   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7828   EVT EltVT = TrgVT.getVectorElementType();
7829   if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
7830       TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
7831       !isPowerOf2_32(EltVT.getSizeInBits()))
7832     return SDValue();
7833 
7834   SDValue N1 = Op.getOperand(0);
7835   EVT SrcVT = N1.getValueType();
7836   unsigned SrcSize = SrcVT.getSizeInBits();
7837   if (SrcSize > 256 ||
7838       !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
7839       !isPowerOf2_32(SrcVT.getVectorElementType().getSizeInBits()))
7840     return SDValue();
7841   if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
7842     return SDValue();
7843 
7844   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7845   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7846 
7847   SDLoc DL(Op);
7848   SDValue Op1, Op2;
7849   if (SrcSize == 256) {
7850     EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
7851     EVT SplitVT =
7852         N1.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
7853     unsigned SplitNumElts = SplitVT.getVectorNumElements();
7854     Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7855                       DAG.getConstant(0, DL, VecIdxTy));
7856     Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
7857                       DAG.getConstant(SplitNumElts, DL, VecIdxTy));
7858   }
7859   else {
7860     Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7861     Op2 = DAG.getUNDEF(WideVT);
7862   }
7863 
7864   // First list the elements we want to keep.
7865   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7866   SmallVector<int, 16> ShuffV;
7867   if (Subtarget.isLittleEndian())
7868     for (unsigned i = 0; i < TrgNumElts; ++i)
7869       ShuffV.push_back(i * SizeMult);
7870   else
7871     for (unsigned i = 1; i <= TrgNumElts; ++i)
7872       ShuffV.push_back(i * SizeMult - 1);
7873 
7874   // Populate the remaining elements with undefs.
7875   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7876     // ShuffV.push_back(i + WideNumElts);
7877     ShuffV.push_back(WideNumElts + 1);
7878 
7879   Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
7880   Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
7881   return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
7882 }
7883 
7884 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7885 /// possible.
7886 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7887   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7888   EVT ResVT = Op.getValueType();
7889   EVT CmpVT = Op.getOperand(0).getValueType();
7890   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7891   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7892   SDLoc dl(Op);
7893 
7894   // Without power9-vector, we don't have native instruction for f128 comparison.
7895   // Following transformation to libcall is needed for setcc:
7896   // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
7897   if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
7898     SDValue Z = DAG.getSetCC(
7899         dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
7900         LHS, RHS, CC);
7901     SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
7902     return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
7903   }
7904 
7905   // Not FP, or using SPE? Not a fsel.
7906   if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
7907       Subtarget.hasSPE())
7908     return Op;
7909 
7910   SDNodeFlags Flags = Op.getNode()->getFlags();
7911 
7912   // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
7913   // presence of infinities.
7914   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7915     switch (CC) {
7916     default:
7917       break;
7918     case ISD::SETOGT:
7919     case ISD::SETGT:
7920       return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
7921     case ISD::SETOLT:
7922     case ISD::SETLT:
7923       return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
7924     }
7925   }
7926 
7927   // We might be able to do better than this under some circumstances, but in
7928   // general, fsel-based lowering of select is a finite-math-only optimization.
7929   // For more information, see section F.3 of the 2.06 ISA specification.
7930   // With ISA 3.0
7931   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7932       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7933     return Op;
7934 
7935   // If the RHS of the comparison is a 0.0, we don't need to do the
7936   // subtraction at all.
7937   SDValue Sel1;
7938   if (isFloatingPointZero(RHS))
7939     switch (CC) {
7940     default: break;       // SETUO etc aren't handled by fsel.
7941     case ISD::SETNE:
7942       std::swap(TV, FV);
7943       LLVM_FALLTHROUGH;
7944     case ISD::SETEQ:
7945       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7946         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7947       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7948       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7949         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7950       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7951                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7952     case ISD::SETULT:
7953     case ISD::SETLT:
7954       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7955       LLVM_FALLTHROUGH;
7956     case ISD::SETOGE:
7957     case ISD::SETGE:
7958       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7959         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7960       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7961     case ISD::SETUGT:
7962     case ISD::SETGT:
7963       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7964       LLVM_FALLTHROUGH;
7965     case ISD::SETOLE:
7966     case ISD::SETLE:
7967       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7968         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7969       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7970                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7971     }
7972 
7973   SDValue Cmp;
7974   switch (CC) {
7975   default: break;       // SETUO etc aren't handled by fsel.
7976   case ISD::SETNE:
7977     std::swap(TV, FV);
7978     LLVM_FALLTHROUGH;
7979   case ISD::SETEQ:
7980     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7981     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7982       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7983     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7984     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7985       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7986     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7987                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7988   case ISD::SETULT:
7989   case ISD::SETLT:
7990     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7991     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7992       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7993     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7994   case ISD::SETOGE:
7995   case ISD::SETGE:
7996     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7997     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7998       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7999     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8000   case ISD::SETUGT:
8001   case ISD::SETGT:
8002     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8003     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8004       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8005     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8006   case ISD::SETOLE:
8007   case ISD::SETLE:
8008     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8009     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
8010       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8011     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8012   }
8013   return Op;
8014 }
8015 
8016 static unsigned getPPCStrictOpcode(unsigned Opc) {
8017   switch (Opc) {
8018   default:
8019     llvm_unreachable("No strict version of this opcode!");
8020   case PPCISD::FCTIDZ:
8021     return PPCISD::STRICT_FCTIDZ;
8022   case PPCISD::FCTIWZ:
8023     return PPCISD::STRICT_FCTIWZ;
8024   case PPCISD::FCTIDUZ:
8025     return PPCISD::STRICT_FCTIDUZ;
8026   case PPCISD::FCTIWUZ:
8027     return PPCISD::STRICT_FCTIWUZ;
8028   case PPCISD::FCFID:
8029     return PPCISD::STRICT_FCFID;
8030   case PPCISD::FCFIDU:
8031     return PPCISD::STRICT_FCFIDU;
8032   case PPCISD::FCFIDS:
8033     return PPCISD::STRICT_FCFIDS;
8034   case PPCISD::FCFIDUS:
8035     return PPCISD::STRICT_FCFIDUS;
8036   }
8037 }
8038 
8039 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
8040                               const PPCSubtarget &Subtarget) {
8041   SDLoc dl(Op);
8042   bool IsStrict = Op->isStrictFPOpcode();
8043   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8044                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8045 
8046   // TODO: Any other flags to propagate?
8047   SDNodeFlags Flags;
8048   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8049 
8050   // For strict nodes, source is the second operand.
8051   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8052   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8053   assert(Src.getValueType().isFloatingPoint());
8054   if (Src.getValueType() == MVT::f32) {
8055     if (IsStrict) {
8056       Src =
8057           DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
8058                       DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8059       Chain = Src.getValue(1);
8060     } else
8061       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8062   }
8063   SDValue Conv;
8064   unsigned Opc = ISD::DELETED_NODE;
8065   switch (Op.getSimpleValueType().SimpleTy) {
8066   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8067   case MVT::i32:
8068     Opc = IsSigned ? PPCISD::FCTIWZ
8069                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8070     break;
8071   case MVT::i64:
8072     assert((IsSigned || Subtarget.hasFPCVT()) &&
8073            "i64 FP_TO_UINT is supported only with FPCVT");
8074     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8075   }
8076   if (IsStrict) {
8077     Opc = getPPCStrictOpcode(Opc);
8078     Conv = DAG.getNode(Opc, dl, DAG.getVTList(MVT::f64, MVT::Other),
8079                        {Chain, Src}, Flags);
8080   } else {
8081     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8082   }
8083   return Conv;
8084 }
8085 
8086 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8087                                                SelectionDAG &DAG,
8088                                                const SDLoc &dl) const {
8089   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8090   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8091                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8092   bool IsStrict = Op->isStrictFPOpcode();
8093 
8094   // Convert the FP value to an int value through memory.
8095   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8096                   (IsSigned || Subtarget.hasFPCVT());
8097   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8098   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8099   MachinePointerInfo MPI =
8100       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8101 
8102   // Emit a store to the stack slot.
8103   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8104   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8105   if (i32Stack) {
8106     MachineFunction &MF = DAG.getMachineFunction();
8107     Alignment = Align(4);
8108     MachineMemOperand *MMO =
8109         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8110     SDValue Ops[] = { Chain, Tmp, FIPtr };
8111     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8112               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8113   } else
8114     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8115 
8116   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8117   // add in a bias on big endian.
8118   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8119     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8120                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8121     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8122   }
8123 
8124   RLI.Chain = Chain;
8125   RLI.Ptr = FIPtr;
8126   RLI.MPI = MPI;
8127   RLI.Alignment = Alignment;
8128 }
8129 
8130 /// Custom lowers floating point to integer conversions to use
8131 /// the direct move instructions available in ISA 2.07 to avoid the
8132 /// need for load/store combinations.
8133 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8134                                                     SelectionDAG &DAG,
8135                                                     const SDLoc &dl) const {
8136   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8137   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8138   if (Op->isStrictFPOpcode())
8139     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8140   else
8141     return Mov;
8142 }
8143 
8144 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8145                                           const SDLoc &dl) const {
8146   bool IsStrict = Op->isStrictFPOpcode();
8147   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8148                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8149   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8150   EVT SrcVT = Src.getValueType();
8151   EVT DstVT = Op.getValueType();
8152 
8153   // FP to INT conversions are legal for f128.
8154   if (SrcVT == MVT::f128)
8155     return Subtarget.hasP9Vector() ? Op : SDValue();
8156 
8157   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8158   // PPC (the libcall is not available).
8159   if (SrcVT == MVT::ppcf128) {
8160     if (DstVT == MVT::i32) {
8161       // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8162       // set other fast-math flags to FP operations in both strict and
8163       // non-strict cases. (FP_TO_SINT, FSUB)
8164       SDNodeFlags Flags;
8165       Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8166 
8167       if (IsSigned) {
8168         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8169                                  DAG.getIntPtrConstant(0, dl));
8170         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8171                                  DAG.getIntPtrConstant(1, dl));
8172 
8173         // Add the two halves of the long double in round-to-zero mode, and use
8174         // a smaller FP_TO_SINT.
8175         if (IsStrict) {
8176           SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8177                                     DAG.getVTList(MVT::f64, MVT::Other),
8178                                     {Op.getOperand(0), Lo, Hi}, Flags);
8179           return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8180                              DAG.getVTList(MVT::i32, MVT::Other),
8181                              {Res.getValue(1), Res}, Flags);
8182         } else {
8183           SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8184           return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8185         }
8186       } else {
8187         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8188         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8189         SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8190         SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8191         if (IsStrict) {
8192           // Sel = Src < 0x80000000
8193           // FltOfs = select Sel, 0.0, 0x80000000
8194           // IntOfs = select Sel, 0, 0x80000000
8195           // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8196           SDValue Chain = Op.getOperand(0);
8197           EVT SetCCVT =
8198               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8199           EVT DstSetCCVT =
8200               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8201           SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8202                                      Chain, true);
8203           Chain = Sel.getValue(1);
8204 
8205           SDValue FltOfs = DAG.getSelect(
8206               dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8207           Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8208 
8209           SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8210                                     DAG.getVTList(SrcVT, MVT::Other),
8211                                     {Chain, Src, FltOfs}, Flags);
8212           Chain = Val.getValue(1);
8213           SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8214                                      DAG.getVTList(DstVT, MVT::Other),
8215                                      {Chain, Val}, Flags);
8216           Chain = SInt.getValue(1);
8217           SDValue IntOfs = DAG.getSelect(
8218               dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8219           SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8220           return DAG.getMergeValues({Result, Chain}, dl);
8221         } else {
8222           // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8223           // FIXME: generated code sucks.
8224           SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8225           True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8226           True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8227           SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8228           return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8229         }
8230       }
8231     }
8232 
8233     return SDValue();
8234   }
8235 
8236   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8237     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8238 
8239   ReuseLoadInfo RLI;
8240   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8241 
8242   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8243                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8244 }
8245 
8246 // We're trying to insert a regular store, S, and then a load, L. If the
8247 // incoming value, O, is a load, we might just be able to have our load use the
8248 // address used by O. However, we don't know if anything else will store to
8249 // that address before we can load from it. To prevent this situation, we need
8250 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8251 // the same chain operand as O, we create a token factor from the chain results
8252 // of O and L, and we replace all uses of O's chain result with that token
8253 // factor (see spliceIntoChain below for this last part).
8254 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8255                                             ReuseLoadInfo &RLI,
8256                                             SelectionDAG &DAG,
8257                                             ISD::LoadExtType ET) const {
8258   // Conservatively skip reusing for constrained FP nodes.
8259   if (Op->isStrictFPOpcode())
8260     return false;
8261 
8262   SDLoc dl(Op);
8263   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8264                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8265   if (ET == ISD::NON_EXTLOAD &&
8266       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8267       isOperationLegalOrCustom(Op.getOpcode(),
8268                                Op.getOperand(0).getValueType())) {
8269 
8270     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8271     return true;
8272   }
8273 
8274   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8275   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8276       LD->isNonTemporal())
8277     return false;
8278   if (LD->getMemoryVT() != MemVT)
8279     return false;
8280 
8281   // If the result of the load is an illegal type, then we can't build a
8282   // valid chain for reuse since the legalised loads and token factor node that
8283   // ties the legalised loads together uses a different output chain then the
8284   // illegal load.
8285   if (!isTypeLegal(LD->getValueType(0)))
8286     return false;
8287 
8288   RLI.Ptr = LD->getBasePtr();
8289   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8290     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8291            "Non-pre-inc AM on PPC?");
8292     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8293                           LD->getOffset());
8294   }
8295 
8296   RLI.Chain = LD->getChain();
8297   RLI.MPI = LD->getPointerInfo();
8298   RLI.IsDereferenceable = LD->isDereferenceable();
8299   RLI.IsInvariant = LD->isInvariant();
8300   RLI.Alignment = LD->getAlign();
8301   RLI.AAInfo = LD->getAAInfo();
8302   RLI.Ranges = LD->getRanges();
8303 
8304   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8305   return true;
8306 }
8307 
8308 // Given the head of the old chain, ResChain, insert a token factor containing
8309 // it and NewResChain, and make users of ResChain now be users of that token
8310 // factor.
8311 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8312 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8313                                         SDValue NewResChain,
8314                                         SelectionDAG &DAG) const {
8315   if (!ResChain)
8316     return;
8317 
8318   SDLoc dl(NewResChain);
8319 
8320   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8321                            NewResChain, DAG.getUNDEF(MVT::Other));
8322   assert(TF.getNode() != NewResChain.getNode() &&
8323          "A new TF really is required here");
8324 
8325   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8326   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8327 }
8328 
8329 /// Analyze profitability of direct move
8330 /// prefer float load to int load plus direct move
8331 /// when there is no integer use of int load
8332 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8333   SDNode *Origin = Op.getOperand(0).getNode();
8334   if (Origin->getOpcode() != ISD::LOAD)
8335     return true;
8336 
8337   // If there is no LXSIBZX/LXSIHZX, like Power8,
8338   // prefer direct move if the memory size is 1 or 2 bytes.
8339   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8340   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8341     return true;
8342 
8343   for (SDNode::use_iterator UI = Origin->use_begin(),
8344                             UE = Origin->use_end();
8345        UI != UE; ++UI) {
8346 
8347     // Only look at the users of the loaded value.
8348     if (UI.getUse().get().getResNo() != 0)
8349       continue;
8350 
8351     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8352         UI->getOpcode() != ISD::UINT_TO_FP &&
8353         UI->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8354         UI->getOpcode() != ISD::STRICT_UINT_TO_FP)
8355       return true;
8356   }
8357 
8358   return false;
8359 }
8360 
8361 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8362                               const PPCSubtarget &Subtarget,
8363                               SDValue Chain = SDValue()) {
8364   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8365                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8366   SDLoc dl(Op);
8367 
8368   // TODO: Any other flags to propagate?
8369   SDNodeFlags Flags;
8370   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8371 
8372   // If we have FCFIDS, then use it when converting to single-precision.
8373   // Otherwise, convert to double-precision and then round.
8374   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8375   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8376                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8377   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8378   if (Op->isStrictFPOpcode()) {
8379     if (!Chain)
8380       Chain = Op.getOperand(0);
8381     return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8382                        DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8383   } else
8384     return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8385 }
8386 
8387 /// Custom lowers integer to floating point conversions to use
8388 /// the direct move instructions available in ISA 2.07 to avoid the
8389 /// need for load/store combinations.
8390 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8391                                                     SelectionDAG &DAG,
8392                                                     const SDLoc &dl) const {
8393   assert((Op.getValueType() == MVT::f32 ||
8394           Op.getValueType() == MVT::f64) &&
8395          "Invalid floating point type as target of conversion");
8396   assert(Subtarget.hasFPCVT() &&
8397          "Int to FP conversions with direct moves require FPCVT");
8398   SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8399   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8400   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8401                 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8402   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8403   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8404   return convertIntToFP(Op, Mov, DAG, Subtarget);
8405 }
8406 
8407 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8408 
8409   EVT VecVT = Vec.getValueType();
8410   assert(VecVT.isVector() && "Expected a vector type.");
8411   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8412 
8413   EVT EltVT = VecVT.getVectorElementType();
8414   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8415   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8416 
8417   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8418   SmallVector<SDValue, 16> Ops(NumConcat);
8419   Ops[0] = Vec;
8420   SDValue UndefVec = DAG.getUNDEF(VecVT);
8421   for (unsigned i = 1; i < NumConcat; ++i)
8422     Ops[i] = UndefVec;
8423 
8424   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8425 }
8426 
8427 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8428                                                 const SDLoc &dl) const {
8429   bool IsStrict = Op->isStrictFPOpcode();
8430   unsigned Opc = Op.getOpcode();
8431   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8432   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP ||
8433           Opc == ISD::STRICT_UINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP) &&
8434          "Unexpected conversion type");
8435   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8436          "Supports conversions to v2f64/v4f32 only.");
8437 
8438   // TODO: Any other flags to propagate?
8439   SDNodeFlags Flags;
8440   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8441 
8442   bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8443   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8444 
8445   SDValue Wide = widenVec(DAG, Src, dl);
8446   EVT WideVT = Wide.getValueType();
8447   unsigned WideNumElts = WideVT.getVectorNumElements();
8448   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8449 
8450   SmallVector<int, 16> ShuffV;
8451   for (unsigned i = 0; i < WideNumElts; ++i)
8452     ShuffV.push_back(i + WideNumElts);
8453 
8454   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8455   int SaveElts = FourEltRes ? 4 : 2;
8456   if (Subtarget.isLittleEndian())
8457     for (int i = 0; i < SaveElts; i++)
8458       ShuffV[i * Stride] = i;
8459   else
8460     for (int i = 1; i <= SaveElts; i++)
8461       ShuffV[i * Stride - 1] = i - 1;
8462 
8463   SDValue ShuffleSrc2 =
8464       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8465   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8466 
8467   SDValue Extend;
8468   if (SignedConv) {
8469     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8470     EVT ExtVT = Src.getValueType();
8471     if (Subtarget.hasP9Altivec())
8472       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8473                                IntermediateVT.getVectorNumElements());
8474 
8475     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8476                          DAG.getValueType(ExtVT));
8477   } else
8478     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8479 
8480   if (IsStrict)
8481     return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8482                        {Op.getOperand(0), Extend}, Flags);
8483 
8484   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8485 }
8486 
8487 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8488                                           SelectionDAG &DAG) const {
8489   SDLoc dl(Op);
8490   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8491                   Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8492   bool IsStrict = Op->isStrictFPOpcode();
8493   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8494   SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8495 
8496   // TODO: Any other flags to propagate?
8497   SDNodeFlags Flags;
8498   Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8499 
8500   EVT InVT = Src.getValueType();
8501   EVT OutVT = Op.getValueType();
8502   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8503       isOperationCustom(Op.getOpcode(), InVT))
8504     return LowerINT_TO_FPVector(Op, DAG, dl);
8505 
8506   // Conversions to f128 are legal.
8507   if (Op.getValueType() == MVT::f128)
8508     return Subtarget.hasP9Vector() ? Op : SDValue();
8509 
8510   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8511   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8512     return SDValue();
8513 
8514   if (Src.getValueType() == MVT::i1) {
8515     SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8516                               DAG.getConstantFP(1.0, dl, Op.getValueType()),
8517                               DAG.getConstantFP(0.0, dl, Op.getValueType()));
8518     if (IsStrict)
8519       return DAG.getMergeValues({Sel, Chain}, dl);
8520     else
8521       return Sel;
8522   }
8523 
8524   // If we have direct moves, we can do all the conversion, skip the store/load
8525   // however, without FPCVT we can't do most conversions.
8526   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8527       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8528     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8529 
8530   assert((IsSigned || Subtarget.hasFPCVT()) &&
8531          "UINT_TO_FP is supported only with FPCVT");
8532 
8533   if (Src.getValueType() == MVT::i64) {
8534     SDValue SINT = Src;
8535     // When converting to single-precision, we actually need to convert
8536     // to double-precision first and then round to single-precision.
8537     // To avoid double-rounding effects during that operation, we have
8538     // to prepare the input operand.  Bits that might be truncated when
8539     // converting to double-precision are replaced by a bit that won't
8540     // be lost at this stage, but is below the single-precision rounding
8541     // position.
8542     //
8543     // However, if -enable-unsafe-fp-math is in effect, accept double
8544     // rounding to avoid the extra overhead.
8545     if (Op.getValueType() == MVT::f32 &&
8546         !Subtarget.hasFPCVT() &&
8547         !DAG.getTarget().Options.UnsafeFPMath) {
8548 
8549       // Twiddle input to make sure the low 11 bits are zero.  (If this
8550       // is the case, we are guaranteed the value will fit into the 53 bit
8551       // mantissa of an IEEE double-precision value without rounding.)
8552       // If any of those low 11 bits were not zero originally, make sure
8553       // bit 12 (value 2048) is set instead, so that the final rounding
8554       // to single-precision gets the correct result.
8555       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8556                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8557       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8558                           Round, DAG.getConstant(2047, dl, MVT::i64));
8559       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8560       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8561                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8562 
8563       // However, we cannot use that value unconditionally: if the magnitude
8564       // of the input value is small, the bit-twiddling we did above might
8565       // end up visibly changing the output.  Fortunately, in that case, we
8566       // don't need to twiddle bits since the original input will convert
8567       // exactly to double-precision floating-point already.  Therefore,
8568       // construct a conditional to use the original value if the top 11
8569       // bits are all sign-bit copies, and use the rounded value computed
8570       // above otherwise.
8571       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8572                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8573       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8574                          Cond, DAG.getConstant(1, dl, MVT::i64));
8575       Cond = DAG.getSetCC(
8576           dl,
8577           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8578           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8579 
8580       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8581     }
8582 
8583     ReuseLoadInfo RLI;
8584     SDValue Bits;
8585 
8586     MachineFunction &MF = DAG.getMachineFunction();
8587     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8588       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8589                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8590       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8591     } else if (Subtarget.hasLFIWAX() &&
8592                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8593       MachineMemOperand *MMO =
8594         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8595                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8596       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8597       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8598                                      DAG.getVTList(MVT::f64, MVT::Other),
8599                                      Ops, MVT::i32, MMO);
8600       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8601     } else if (Subtarget.hasFPCVT() &&
8602                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8603       MachineMemOperand *MMO =
8604         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8605                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8606       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8607       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8608                                      DAG.getVTList(MVT::f64, MVT::Other),
8609                                      Ops, MVT::i32, MMO);
8610       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8611     } else if (((Subtarget.hasLFIWAX() &&
8612                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8613                 (Subtarget.hasFPCVT() &&
8614                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8615                SINT.getOperand(0).getValueType() == MVT::i32) {
8616       MachineFrameInfo &MFI = MF.getFrameInfo();
8617       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8618 
8619       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8620       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8621 
8622       SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8623                                    MachinePointerInfo::getFixedStack(
8624                                        DAG.getMachineFunction(), FrameIdx));
8625       Chain = Store;
8626 
8627       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8628              "Expected an i32 store");
8629 
8630       RLI.Ptr = FIdx;
8631       RLI.Chain = Chain;
8632       RLI.MPI =
8633           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8634       RLI.Alignment = Align(4);
8635 
8636       MachineMemOperand *MMO =
8637         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8638                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8639       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8640       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8641                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8642                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8643                                      Ops, MVT::i32, MMO);
8644       Chain = Bits.getValue(1);
8645     } else
8646       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8647 
8648     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8649     if (IsStrict)
8650       Chain = FP.getValue(1);
8651 
8652     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8653       if (IsStrict)
8654         FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8655                          DAG.getVTList(MVT::f32, MVT::Other),
8656                          {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8657       else
8658         FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8659                          DAG.getIntPtrConstant(0, dl));
8660     }
8661     return FP;
8662   }
8663 
8664   assert(Src.getValueType() == MVT::i32 &&
8665          "Unhandled INT_TO_FP type in custom expander!");
8666   // Since we only generate this in 64-bit mode, we can take advantage of
8667   // 64-bit registers.  In particular, sign extend the input value into the
8668   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8669   // then lfd it and fcfid it.
8670   MachineFunction &MF = DAG.getMachineFunction();
8671   MachineFrameInfo &MFI = MF.getFrameInfo();
8672   EVT PtrVT = getPointerTy(MF.getDataLayout());
8673 
8674   SDValue Ld;
8675   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8676     ReuseLoadInfo RLI;
8677     bool ReusingLoad;
8678     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8679       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8680       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8681 
8682       SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
8683                                    MachinePointerInfo::getFixedStack(
8684                                        DAG.getMachineFunction(), FrameIdx));
8685       Chain = Store;
8686 
8687       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8688              "Expected an i32 store");
8689 
8690       RLI.Ptr = FIdx;
8691       RLI.Chain = Chain;
8692       RLI.MPI =
8693           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8694       RLI.Alignment = Align(4);
8695     }
8696 
8697     MachineMemOperand *MMO =
8698       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8699                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8700     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8701     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8702                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8703                                  MVT::i32, MMO);
8704     Chain = Ld.getValue(1);
8705     if (ReusingLoad)
8706       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8707   } else {
8708     assert(Subtarget.isPPC64() &&
8709            "i32->FP without LFIWAX supported only on PPC64");
8710 
8711     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8712     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8713 
8714     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8715 
8716     // STD the extended value into the stack slot.
8717     SDValue Store = DAG.getStore(
8718         Chain, dl, Ext64, FIdx,
8719         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8720     Chain = Store;
8721 
8722     // Load the value as a double.
8723     Ld = DAG.getLoad(
8724         MVT::f64, dl, Chain, FIdx,
8725         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8726     Chain = Ld.getValue(1);
8727   }
8728 
8729   // FCFID it and return it.
8730   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
8731   if (IsStrict)
8732     Chain = FP.getValue(1);
8733   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8734     if (IsStrict)
8735       FP = DAG.getNode(ISD::STRICT_FP_ROUND, dl,
8736                        DAG.getVTList(MVT::f32, MVT::Other),
8737                        {Chain, FP, DAG.getIntPtrConstant(0, dl)}, Flags);
8738     else
8739       FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8740                        DAG.getIntPtrConstant(0, dl));
8741   }
8742   return FP;
8743 }
8744 
8745 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8746                                             SelectionDAG &DAG) const {
8747   SDLoc dl(Op);
8748   /*
8749    The rounding mode is in bits 30:31 of FPSR, and has the following
8750    settings:
8751      00 Round to nearest
8752      01 Round to 0
8753      10 Round to +inf
8754      11 Round to -inf
8755 
8756   FLT_ROUNDS, on the other hand, expects the following:
8757     -1 Undefined
8758      0 Round to 0
8759      1 Round to nearest
8760      2 Round to +inf
8761      3 Round to -inf
8762 
8763   To perform the conversion, we do:
8764     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8765   */
8766 
8767   MachineFunction &MF = DAG.getMachineFunction();
8768   EVT VT = Op.getValueType();
8769   EVT PtrVT = getPointerTy(MF.getDataLayout());
8770 
8771   // Save FP Control Word to register
8772   SDValue Chain = Op.getOperand(0);
8773   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8774   Chain = MFFS.getValue(1);
8775 
8776   SDValue CWD;
8777   if (isTypeLegal(MVT::i64)) {
8778     CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
8779                       DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
8780   } else {
8781     // Save FP register to stack slot
8782     int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8783     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8784     Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8785 
8786     // Load FP Control Word from low 32 bits of stack slot.
8787     assert(hasBigEndianPartOrdering(MVT::i64, MF.getDataLayout()) &&
8788            "Stack slot adjustment is valid only on big endian subtargets!");
8789     SDValue Four = DAG.getConstant(4, dl, PtrVT);
8790     SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8791     CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8792     Chain = CWD.getValue(1);
8793   }
8794 
8795   // Transform as necessary
8796   SDValue CWD1 =
8797     DAG.getNode(ISD::AND, dl, MVT::i32,
8798                 CWD, DAG.getConstant(3, dl, MVT::i32));
8799   SDValue CWD2 =
8800     DAG.getNode(ISD::SRL, dl, MVT::i32,
8801                 DAG.getNode(ISD::AND, dl, MVT::i32,
8802                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8803                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8804                             DAG.getConstant(3, dl, MVT::i32)),
8805                 DAG.getConstant(1, dl, MVT::i32));
8806 
8807   SDValue RetVal =
8808     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8809 
8810   RetVal =
8811       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8812                   dl, VT, RetVal);
8813 
8814   return DAG.getMergeValues({RetVal, Chain}, dl);
8815 }
8816 
8817 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8818   EVT VT = Op.getValueType();
8819   unsigned BitWidth = VT.getSizeInBits();
8820   SDLoc dl(Op);
8821   assert(Op.getNumOperands() == 3 &&
8822          VT == Op.getOperand(1).getValueType() &&
8823          "Unexpected SHL!");
8824 
8825   // Expand into a bunch of logical ops.  Note that these ops
8826   // depend on the PPC behavior for oversized shift amounts.
8827   SDValue Lo = Op.getOperand(0);
8828   SDValue Hi = Op.getOperand(1);
8829   SDValue Amt = Op.getOperand(2);
8830   EVT AmtVT = Amt.getValueType();
8831 
8832   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8833                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8834   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8835   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8836   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8837   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8838                              DAG.getConstant(-BitWidth, dl, AmtVT));
8839   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8840   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8841   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8842   SDValue OutOps[] = { OutLo, OutHi };
8843   return DAG.getMergeValues(OutOps, dl);
8844 }
8845 
8846 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8847   EVT VT = Op.getValueType();
8848   SDLoc dl(Op);
8849   unsigned BitWidth = VT.getSizeInBits();
8850   assert(Op.getNumOperands() == 3 &&
8851          VT == Op.getOperand(1).getValueType() &&
8852          "Unexpected SRL!");
8853 
8854   // Expand into a bunch of logical ops.  Note that these ops
8855   // depend on the PPC behavior for oversized shift amounts.
8856   SDValue Lo = Op.getOperand(0);
8857   SDValue Hi = Op.getOperand(1);
8858   SDValue Amt = Op.getOperand(2);
8859   EVT AmtVT = Amt.getValueType();
8860 
8861   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8862                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8863   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8864   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8865   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8866   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8867                              DAG.getConstant(-BitWidth, dl, AmtVT));
8868   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8869   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8870   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8871   SDValue OutOps[] = { OutLo, OutHi };
8872   return DAG.getMergeValues(OutOps, dl);
8873 }
8874 
8875 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8876   SDLoc dl(Op);
8877   EVT VT = Op.getValueType();
8878   unsigned BitWidth = VT.getSizeInBits();
8879   assert(Op.getNumOperands() == 3 &&
8880          VT == Op.getOperand(1).getValueType() &&
8881          "Unexpected SRA!");
8882 
8883   // Expand into a bunch of logical ops, followed by a select_cc.
8884   SDValue Lo = Op.getOperand(0);
8885   SDValue Hi = Op.getOperand(1);
8886   SDValue Amt = Op.getOperand(2);
8887   EVT AmtVT = Amt.getValueType();
8888 
8889   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8890                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8891   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8892   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8893   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8894   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8895                              DAG.getConstant(-BitWidth, dl, AmtVT));
8896   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8897   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8898   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8899                                   Tmp4, Tmp6, ISD::SETLE);
8900   SDValue OutOps[] = { OutLo, OutHi };
8901   return DAG.getMergeValues(OutOps, dl);
8902 }
8903 
8904 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8905                                             SelectionDAG &DAG) const {
8906   SDLoc dl(Op);
8907   EVT VT = Op.getValueType();
8908   unsigned BitWidth = VT.getSizeInBits();
8909 
8910   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8911   SDValue X = Op.getOperand(0);
8912   SDValue Y = Op.getOperand(1);
8913   SDValue Z = Op.getOperand(2);
8914   EVT AmtVT = Z.getValueType();
8915 
8916   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8917   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8918   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8919   // on PowerPC shift by BW being well defined.
8920   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8921                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8922   SDValue SubZ =
8923       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8924   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8925   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8926   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8927 }
8928 
8929 //===----------------------------------------------------------------------===//
8930 // Vector related lowering.
8931 //
8932 
8933 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8934 /// element size of SplatSize. Cast the result to VT.
8935 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8936                                       SelectionDAG &DAG, const SDLoc &dl) {
8937   static const MVT VTys[] = { // canonical VT to use for each size.
8938     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8939   };
8940 
8941   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8942 
8943   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8944   if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
8945     SplatSize = 1;
8946     Val = 0xFF;
8947   }
8948 
8949   EVT CanonicalVT = VTys[SplatSize-1];
8950 
8951   // Build a canonical splat for this value.
8952   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8953 }
8954 
8955 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8956 /// specified intrinsic ID.
8957 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8958                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8959   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8960   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8961                      DAG.getConstant(IID, dl, MVT::i32), Op);
8962 }
8963 
8964 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8965 /// specified intrinsic ID.
8966 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8967                                 SelectionDAG &DAG, const SDLoc &dl,
8968                                 EVT DestVT = MVT::Other) {
8969   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8970   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8971                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8972 }
8973 
8974 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8975 /// specified intrinsic ID.
8976 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8977                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8978                                 EVT DestVT = MVT::Other) {
8979   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8980   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8981                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8982 }
8983 
8984 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8985 /// amount.  The result has the specified value type.
8986 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8987                            SelectionDAG &DAG, const SDLoc &dl) {
8988   // Force LHS/RHS to be the right type.
8989   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8990   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8991 
8992   int Ops[16];
8993   for (unsigned i = 0; i != 16; ++i)
8994     Ops[i] = i + Amt;
8995   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8996   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8997 }
8998 
8999 /// Do we have an efficient pattern in a .td file for this node?
9000 ///
9001 /// \param V - pointer to the BuildVectorSDNode being matched
9002 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9003 ///
9004 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9005 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9006 /// the opposite is true (expansion is beneficial) are:
9007 /// - The node builds a vector out of integers that are not 32 or 64-bits
9008 /// - The node builds a vector out of constants
9009 /// - The node is a "load-and-splat"
9010 /// In all other cases, we will choose to keep the BUILD_VECTOR.
9011 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
9012                                             bool HasDirectMove,
9013                                             bool HasP8Vector) {
9014   EVT VecVT = V->getValueType(0);
9015   bool RightType = VecVT == MVT::v2f64 ||
9016     (HasP8Vector && VecVT == MVT::v4f32) ||
9017     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9018   if (!RightType)
9019     return false;
9020 
9021   bool IsSplat = true;
9022   bool IsLoad = false;
9023   SDValue Op0 = V->getOperand(0);
9024 
9025   // This function is called in a block that confirms the node is not a constant
9026   // splat. So a constant BUILD_VECTOR here means the vector is built out of
9027   // different constants.
9028   if (V->isConstant())
9029     return false;
9030   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9031     if (V->getOperand(i).isUndef())
9032       return false;
9033     // We want to expand nodes that represent load-and-splat even if the
9034     // loaded value is a floating point truncation or conversion to int.
9035     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9036         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9037          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9038         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9039          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9040         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9041          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9042       IsLoad = true;
9043     // If the operands are different or the input is not a load and has more
9044     // uses than just this BV node, then it isn't a splat.
9045     if (V->getOperand(i) != Op0 ||
9046         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9047       IsSplat = false;
9048   }
9049   return !(IsSplat && IsLoad);
9050 }
9051 
9052 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9053 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9054 
9055   SDLoc dl(Op);
9056   SDValue Op0 = Op->getOperand(0);
9057 
9058   if ((Op.getValueType() != MVT::f128) ||
9059       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9060       (Op0.getOperand(0).getValueType() != MVT::i64) ||
9061       (Op0.getOperand(1).getValueType() != MVT::i64))
9062     return SDValue();
9063 
9064   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
9065                      Op0.getOperand(1));
9066 }
9067 
9068 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9069   const SDValue *InputLoad = &Op;
9070   if (InputLoad->getOpcode() == ISD::BITCAST)
9071     InputLoad = &InputLoad->getOperand(0);
9072   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9073       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9074     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9075     InputLoad = &InputLoad->getOperand(0);
9076   }
9077   if (InputLoad->getOpcode() != ISD::LOAD)
9078     return nullptr;
9079   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9080   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
9081 }
9082 
9083 // Convert the argument APFloat to a single precision APFloat if there is no
9084 // loss in information during the conversion to single precision APFloat and the
9085 // resulting number is not a denormal number. Return true if successful.
9086 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
9087   APFloat APFloatToConvert = ArgAPFloat;
9088   bool LosesInfo = true;
9089   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9090                            &LosesInfo);
9091   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9092   if (Success)
9093     ArgAPFloat = APFloatToConvert;
9094   return Success;
9095 }
9096 
9097 // Bitcast the argument APInt to a double and convert it to a single precision
9098 // APFloat, bitcast the APFloat to an APInt and assign it to the original
9099 // argument if there is no loss in information during the conversion from
9100 // double to single precision APFloat and the resulting number is not a denormal
9101 // number. Return true if successful.
9102 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
9103   double DpValue = ArgAPInt.bitsToDouble();
9104   APFloat APFloatDp(DpValue);
9105   bool Success = convertToNonDenormSingle(APFloatDp);
9106   if (Success)
9107     ArgAPInt = APFloatDp.bitcastToAPInt();
9108   return Success;
9109 }
9110 
9111 // Nondestructive check for convertTonNonDenormSingle.
9112 bool llvm::checkConvertToNonDenormSingle(APFloat &ArgAPFloat) {
9113   // Only convert if it loses info, since XXSPLTIDP should
9114   // handle the other case.
9115   APFloat APFloatToConvert = ArgAPFloat;
9116   bool LosesInfo = true;
9117   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
9118                            &LosesInfo);
9119 
9120   return (!LosesInfo && !APFloatToConvert.isDenormal());
9121 }
9122 
9123 static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9124                              unsigned &Opcode) {
9125   LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9126   if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9127     return false;
9128 
9129   EVT Ty = Op->getValueType(0);
9130   // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9131   // as we cannot handle extending loads for these types.
9132   if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9133       ISD::isNON_EXTLoad(InputNode))
9134     return true;
9135 
9136   EVT MemVT = InputNode->getMemoryVT();
9137   // For v8i16 and v16i8 types, extending loads can be handled as long as the
9138   // memory VT is the same vector element VT type.
9139   // The loads feeding into the v8i16 and v16i8 types will be extending because
9140   // scalar i8/i16 are not legal types.
9141   if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9142       (MemVT == Ty.getVectorElementType()))
9143     return true;
9144 
9145   if (Ty == MVT::v2i64) {
9146     // Check the extend type, when the input type is i32, and the output vector
9147     // type is v2i64.
9148     if (MemVT == MVT::i32) {
9149       if (ISD::isZEXTLoad(InputNode))
9150         Opcode = PPCISD::ZEXT_LD_SPLAT;
9151       if (ISD::isSEXTLoad(InputNode))
9152         Opcode = PPCISD::SEXT_LD_SPLAT;
9153     }
9154     return true;
9155   }
9156   return false;
9157 }
9158 
9159 // If this is a case we can't handle, return null and let the default
9160 // expansion code take care of it.  If we CAN select this case, and if it
9161 // selects to a single instruction, return Op.  Otherwise, if we can codegen
9162 // this case more efficiently than a constant pool load, lower it to the
9163 // sequence of ops that should be used.
9164 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9165                                              SelectionDAG &DAG) const {
9166   SDLoc dl(Op);
9167   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9168   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9169 
9170   // Check if this is a splat of a constant value.
9171   APInt APSplatBits, APSplatUndef;
9172   unsigned SplatBitSize;
9173   bool HasAnyUndefs;
9174   bool BVNIsConstantSplat =
9175       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9176                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9177 
9178   // If it is a splat of a double, check if we can shrink it to a 32 bit
9179   // non-denormal float which when converted back to double gives us the same
9180   // double. This is to exploit the XXSPLTIDP instruction.
9181   // If we lose precision, we use XXSPLTI32DX.
9182   if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9183       Subtarget.hasPrefixInstrs()) {
9184     // Check the type first to short-circuit so we don't modify APSplatBits if
9185     // this block isn't executed.
9186     if ((Op->getValueType(0) == MVT::v2f64) &&
9187         convertToNonDenormSingle(APSplatBits)) {
9188       SDValue SplatNode = DAG.getNode(
9189           PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9190           DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9191       return DAG.getBitcast(Op.getValueType(), SplatNode);
9192     } else {
9193       // We may lose precision, so we have to use XXSPLTI32DX.
9194 
9195       uint32_t Hi =
9196           (uint32_t)((APSplatBits.getZExtValue() & 0xFFFFFFFF00000000LL) >> 32);
9197       uint32_t Lo =
9198           (uint32_t)(APSplatBits.getZExtValue() & 0xFFFFFFFF);
9199       SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9200 
9201       if (!Hi || !Lo)
9202         // If either load is 0, then we should generate XXLXOR to set to 0.
9203         SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9204 
9205       if (Hi)
9206         SplatNode = DAG.getNode(
9207             PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9208             DAG.getTargetConstant(0, dl, MVT::i32),
9209             DAG.getTargetConstant(Hi, dl, MVT::i32));
9210 
9211       if (Lo)
9212         SplatNode =
9213             DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9214                         DAG.getTargetConstant(1, dl, MVT::i32),
9215                         DAG.getTargetConstant(Lo, dl, MVT::i32));
9216 
9217       return DAG.getBitcast(Op.getValueType(), SplatNode);
9218     }
9219   }
9220 
9221   if (!BVNIsConstantSplat || SplatBitSize > 32) {
9222     unsigned NewOpcode = PPCISD::LD_SPLAT;
9223 
9224     // Handle load-and-splat patterns as we have instructions that will do this
9225     // in one go.
9226     if (DAG.isSplatValue(Op, true) &&
9227         isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9228       const SDValue *InputLoad = &Op.getOperand(0);
9229       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9230 
9231       // If the input load is an extending load, it will be an i32 -> i64
9232       // extending load and isValidSplatLoad() will update NewOpcode.
9233       unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9234       unsigned ElementSize =
9235           MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9236 
9237       assert(((ElementSize == 2 * MemorySize)
9238                   ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9239                      NewOpcode == PPCISD::SEXT_LD_SPLAT)
9240                   : (NewOpcode == PPCISD::LD_SPLAT)) &&
9241              "Unmatched element size and opcode!\n");
9242 
9243       // Checking for a single use of this load, we have to check for vector
9244       // width (128 bits) / ElementSize uses (since each operand of the
9245       // BUILD_VECTOR is a separate use of the value.
9246       unsigned NumUsesOfInputLD = 128 / ElementSize;
9247       for (SDValue BVInOp : Op->ops())
9248         if (BVInOp.isUndef())
9249           NumUsesOfInputLD--;
9250 
9251       // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9252       // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9253       // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9254       // 15", but funciton IsValidSplatLoad() now will only return true when
9255       // the data at index 0 is not nullptr. So we will not get into trouble for
9256       // these cases.
9257       //
9258       // case 1 - lfiwzx/lfiwax
9259       // 1.1: load result is i32 and is sign/zero extend to i64;
9260       // 1.2: build a v2i64 vector type with above loaded value;
9261       // 1.3: the vector has only one value at index 0, others are all undef;
9262       // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9263       if (NumUsesOfInputLD == 1 &&
9264           (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9265            !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9266            Subtarget.hasLFIWAX()))
9267         return SDValue();
9268 
9269       // case 2 - lxvr[hb]x
9270       // 2.1: load result is at most i16;
9271       // 2.2: build a vector with above loaded value;
9272       // 2.3: the vector has only one value at index 0, others are all undef;
9273       // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9274       if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9275           Subtarget.isISA3_1() && ElementSize <= 16)
9276         return SDValue();
9277 
9278       assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9279       if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9280           Subtarget.hasVSX()) {
9281         SDValue Ops[] = {
9282           LD->getChain(),    // Chain
9283           LD->getBasePtr(),  // Ptr
9284           DAG.getValueType(Op.getValueType()) // VT
9285         };
9286         SDValue LdSplt = DAG.getMemIntrinsicNode(
9287             NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9288             LD->getMemoryVT(), LD->getMemOperand());
9289         // Replace all uses of the output chain of the original load with the
9290         // output chain of the new load.
9291         DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9292                                       LdSplt.getValue(1));
9293         return LdSplt;
9294       }
9295     }
9296 
9297     // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9298     // 32-bits can be lowered to VSX instructions under certain conditions.
9299     // Without VSX, there is no pattern more efficient than expanding the node.
9300     if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9301         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9302                                         Subtarget.hasP8Vector()))
9303       return Op;
9304     return SDValue();
9305   }
9306 
9307   uint64_t SplatBits = APSplatBits.getZExtValue();
9308   uint64_t SplatUndef = APSplatUndef.getZExtValue();
9309   unsigned SplatSize = SplatBitSize / 8;
9310 
9311   // First, handle single instruction cases.
9312 
9313   // All zeros?
9314   if (SplatBits == 0) {
9315     // Canonicalize all zero vectors to be v4i32.
9316     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9317       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9318       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9319     }
9320     return Op;
9321   }
9322 
9323   // We have XXSPLTIW for constant splats four bytes wide.
9324   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9325   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9326   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9327   // turned into a 4-byte splat of 0xABABABAB.
9328   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9329     return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9330                                   Op.getValueType(), DAG, dl);
9331 
9332   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9333     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9334                                   dl);
9335 
9336   // We have XXSPLTIB for constant splats one byte wide.
9337   if (Subtarget.hasP9Vector() && SplatSize == 1)
9338     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9339                                   dl);
9340 
9341   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9342   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9343                     (32-SplatBitSize));
9344   if (SextVal >= -16 && SextVal <= 15)
9345     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9346                                   dl);
9347 
9348   // Two instruction sequences.
9349 
9350   // If this value is in the range [-32,30] and is even, use:
9351   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9352   // If this value is in the range [17,31] and is odd, use:
9353   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9354   // If this value is in the range [-31,-17] and is odd, use:
9355   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9356   // Note the last two are three-instruction sequences.
9357   if (SextVal >= -32 && SextVal <= 31) {
9358     // To avoid having these optimizations undone by constant folding,
9359     // we convert to a pseudo that will be expanded later into one of
9360     // the above forms.
9361     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9362     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9363               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9364     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9365     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9366     if (VT == Op.getValueType())
9367       return RetVal;
9368     else
9369       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9370   }
9371 
9372   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9373   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9374   // for fneg/fabs.
9375   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9376     // Make -1 and vspltisw -1:
9377     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9378 
9379     // Make the VSLW intrinsic, computing 0x8000_0000.
9380     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9381                                    OnesV, DAG, dl);
9382 
9383     // xor by OnesV to invert it.
9384     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9385     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9386   }
9387 
9388   // Check to see if this is a wide variety of vsplti*, binop self cases.
9389   static const signed char SplatCsts[] = {
9390     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9391     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9392   };
9393 
9394   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9395     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9396     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9397     int i = SplatCsts[idx];
9398 
9399     // Figure out what shift amount will be used by altivec if shifted by i in
9400     // this splat size.
9401     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9402 
9403     // vsplti + shl self.
9404     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9405       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9406       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9407         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9408         Intrinsic::ppc_altivec_vslw
9409       };
9410       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9411       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9412     }
9413 
9414     // vsplti + srl self.
9415     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9416       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9417       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9418         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9419         Intrinsic::ppc_altivec_vsrw
9420       };
9421       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9422       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9423     }
9424 
9425     // vsplti + rol self.
9426     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9427                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9428       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9429       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9430         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9431         Intrinsic::ppc_altivec_vrlw
9432       };
9433       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9434       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9435     }
9436 
9437     // t = vsplti c, result = vsldoi t, t, 1
9438     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9439       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9440       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9441       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9442     }
9443     // t = vsplti c, result = vsldoi t, t, 2
9444     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9445       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9446       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9447       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9448     }
9449     // t = vsplti c, result = vsldoi t, t, 3
9450     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9451       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9452       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9453       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9454     }
9455   }
9456 
9457   return SDValue();
9458 }
9459 
9460 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9461 /// the specified operations to build the shuffle.
9462 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9463                                       SDValue RHS, SelectionDAG &DAG,
9464                                       const SDLoc &dl) {
9465   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9466   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9467   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9468 
9469   enum {
9470     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9471     OP_VMRGHW,
9472     OP_VMRGLW,
9473     OP_VSPLTISW0,
9474     OP_VSPLTISW1,
9475     OP_VSPLTISW2,
9476     OP_VSPLTISW3,
9477     OP_VSLDOI4,
9478     OP_VSLDOI8,
9479     OP_VSLDOI12
9480   };
9481 
9482   if (OpNum == OP_COPY) {
9483     if (LHSID == (1*9+2)*9+3) return LHS;
9484     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9485     return RHS;
9486   }
9487 
9488   SDValue OpLHS, OpRHS;
9489   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9490   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9491 
9492   int ShufIdxs[16];
9493   switch (OpNum) {
9494   default: llvm_unreachable("Unknown i32 permute!");
9495   case OP_VMRGHW:
9496     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9497     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9498     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9499     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9500     break;
9501   case OP_VMRGLW:
9502     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9503     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9504     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9505     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9506     break;
9507   case OP_VSPLTISW0:
9508     for (unsigned i = 0; i != 16; ++i)
9509       ShufIdxs[i] = (i&3)+0;
9510     break;
9511   case OP_VSPLTISW1:
9512     for (unsigned i = 0; i != 16; ++i)
9513       ShufIdxs[i] = (i&3)+4;
9514     break;
9515   case OP_VSPLTISW2:
9516     for (unsigned i = 0; i != 16; ++i)
9517       ShufIdxs[i] = (i&3)+8;
9518     break;
9519   case OP_VSPLTISW3:
9520     for (unsigned i = 0; i != 16; ++i)
9521       ShufIdxs[i] = (i&3)+12;
9522     break;
9523   case OP_VSLDOI4:
9524     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9525   case OP_VSLDOI8:
9526     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9527   case OP_VSLDOI12:
9528     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9529   }
9530   EVT VT = OpLHS.getValueType();
9531   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9532   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9533   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9534   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9535 }
9536 
9537 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9538 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9539 /// SDValue.
9540 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9541                                            SelectionDAG &DAG) const {
9542   const unsigned BytesInVector = 16;
9543   bool IsLE = Subtarget.isLittleEndian();
9544   SDLoc dl(N);
9545   SDValue V1 = N->getOperand(0);
9546   SDValue V2 = N->getOperand(1);
9547   unsigned ShiftElts = 0, InsertAtByte = 0;
9548   bool Swap = false;
9549 
9550   // Shifts required to get the byte we want at element 7.
9551   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9552                                    0, 15, 14, 13, 12, 11, 10, 9};
9553   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9554                                 1, 2,  3,  4,  5,  6,  7,  8};
9555 
9556   ArrayRef<int> Mask = N->getMask();
9557   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9558 
9559   // For each mask element, find out if we're just inserting something
9560   // from V2 into V1 or vice versa.
9561   // Possible permutations inserting an element from V2 into V1:
9562   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9563   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9564   //   ...
9565   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9566   // Inserting from V1 into V2 will be similar, except mask range will be
9567   // [16,31].
9568 
9569   bool FoundCandidate = false;
9570   // If both vector operands for the shuffle are the same vector, the mask
9571   // will contain only elements from the first one and the second one will be
9572   // undef.
9573   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9574   // Go through the mask of half-words to find an element that's being moved
9575   // from one vector to the other.
9576   for (unsigned i = 0; i < BytesInVector; ++i) {
9577     unsigned CurrentElement = Mask[i];
9578     // If 2nd operand is undefined, we should only look for element 7 in the
9579     // Mask.
9580     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9581       continue;
9582 
9583     bool OtherElementsInOrder = true;
9584     // Examine the other elements in the Mask to see if they're in original
9585     // order.
9586     for (unsigned j = 0; j < BytesInVector; ++j) {
9587       if (j == i)
9588         continue;
9589       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9590       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9591       // in which we always assume we're always picking from the 1st operand.
9592       int MaskOffset =
9593           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9594       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9595         OtherElementsInOrder = false;
9596         break;
9597       }
9598     }
9599     // If other elements are in original order, we record the number of shifts
9600     // we need to get the element we want into element 7. Also record which byte
9601     // in the vector we should insert into.
9602     if (OtherElementsInOrder) {
9603       // If 2nd operand is undefined, we assume no shifts and no swapping.
9604       if (V2.isUndef()) {
9605         ShiftElts = 0;
9606         Swap = false;
9607       } else {
9608         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9609         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9610                          : BigEndianShifts[CurrentElement & 0xF];
9611         Swap = CurrentElement < BytesInVector;
9612       }
9613       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9614       FoundCandidate = true;
9615       break;
9616     }
9617   }
9618 
9619   if (!FoundCandidate)
9620     return SDValue();
9621 
9622   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9623   // optionally with VECSHL if shift is required.
9624   if (Swap)
9625     std::swap(V1, V2);
9626   if (V2.isUndef())
9627     V2 = V1;
9628   if (ShiftElts) {
9629     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9630                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9631     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9632                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9633   }
9634   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9635                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9636 }
9637 
9638 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9639 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9640 /// SDValue.
9641 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9642                                            SelectionDAG &DAG) const {
9643   const unsigned NumHalfWords = 8;
9644   const unsigned BytesInVector = NumHalfWords * 2;
9645   // Check that the shuffle is on half-words.
9646   if (!isNByteElemShuffleMask(N, 2, 1))
9647     return SDValue();
9648 
9649   bool IsLE = Subtarget.isLittleEndian();
9650   SDLoc dl(N);
9651   SDValue V1 = N->getOperand(0);
9652   SDValue V2 = N->getOperand(1);
9653   unsigned ShiftElts = 0, InsertAtByte = 0;
9654   bool Swap = false;
9655 
9656   // Shifts required to get the half-word we want at element 3.
9657   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9658   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9659 
9660   uint32_t Mask = 0;
9661   uint32_t OriginalOrderLow = 0x1234567;
9662   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9663   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9664   // 32-bit space, only need 4-bit nibbles per element.
9665   for (unsigned i = 0; i < NumHalfWords; ++i) {
9666     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9667     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9668   }
9669 
9670   // For each mask element, find out if we're just inserting something
9671   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9672   // from V2 into V1:
9673   //   X, 1, 2, 3, 4, 5, 6, 7
9674   //   0, X, 2, 3, 4, 5, 6, 7
9675   //   0, 1, X, 3, 4, 5, 6, 7
9676   //   0, 1, 2, X, 4, 5, 6, 7
9677   //   0, 1, 2, 3, X, 5, 6, 7
9678   //   0, 1, 2, 3, 4, X, 6, 7
9679   //   0, 1, 2, 3, 4, 5, X, 7
9680   //   0, 1, 2, 3, 4, 5, 6, X
9681   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9682 
9683   bool FoundCandidate = false;
9684   // Go through the mask of half-words to find an element that's being moved
9685   // from one vector to the other.
9686   for (unsigned i = 0; i < NumHalfWords; ++i) {
9687     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9688     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9689     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9690     uint32_t TargetOrder = 0x0;
9691 
9692     // If both vector operands for the shuffle are the same vector, the mask
9693     // will contain only elements from the first one and the second one will be
9694     // undef.
9695     if (V2.isUndef()) {
9696       ShiftElts = 0;
9697       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9698       TargetOrder = OriginalOrderLow;
9699       Swap = false;
9700       // Skip if not the correct element or mask of other elements don't equal
9701       // to our expected order.
9702       if (MaskOneElt == VINSERTHSrcElem &&
9703           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9704         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9705         FoundCandidate = true;
9706         break;
9707       }
9708     } else { // If both operands are defined.
9709       // Target order is [8,15] if the current mask is between [0,7].
9710       TargetOrder =
9711           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9712       // Skip if mask of other elements don't equal our expected order.
9713       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9714         // We only need the last 3 bits for the number of shifts.
9715         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9716                          : BigEndianShifts[MaskOneElt & 0x7];
9717         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9718         Swap = MaskOneElt < NumHalfWords;
9719         FoundCandidate = true;
9720         break;
9721       }
9722     }
9723   }
9724 
9725   if (!FoundCandidate)
9726     return SDValue();
9727 
9728   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9729   // optionally with VECSHL if shift is required.
9730   if (Swap)
9731     std::swap(V1, V2);
9732   if (V2.isUndef())
9733     V2 = V1;
9734   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9735   if (ShiftElts) {
9736     // Double ShiftElts because we're left shifting on v16i8 type.
9737     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9738                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9739     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9740     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9741                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9742     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9743   }
9744   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9745   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9746                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9747   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9748 }
9749 
9750 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9751 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9752 /// return the default SDValue.
9753 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9754                                               SelectionDAG &DAG) const {
9755   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9756   // to v16i8. Peek through the bitcasts to get the actual operands.
9757   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9758   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9759 
9760   auto ShuffleMask = SVN->getMask();
9761   SDValue VecShuffle(SVN, 0);
9762   SDLoc DL(SVN);
9763 
9764   // Check that we have a four byte shuffle.
9765   if (!isNByteElemShuffleMask(SVN, 4, 1))
9766     return SDValue();
9767 
9768   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9769   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9770     std::swap(LHS, RHS);
9771     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9772     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9773   }
9774 
9775   // Ensure that the RHS is a vector of constants.
9776   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9777   if (!BVN)
9778     return SDValue();
9779 
9780   // Check if RHS is a splat of 4-bytes (or smaller).
9781   APInt APSplatValue, APSplatUndef;
9782   unsigned SplatBitSize;
9783   bool HasAnyUndefs;
9784   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9785                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9786       SplatBitSize > 32)
9787     return SDValue();
9788 
9789   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9790   // The instruction splats a constant C into two words of the source vector
9791   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9792   // Thus we check that the shuffle mask is the equivalent  of
9793   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9794   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9795   // within each word are consecutive, so we only need to check the first byte.
9796   SDValue Index;
9797   bool IsLE = Subtarget.isLittleEndian();
9798   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9799       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9800        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9801     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9802   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9803            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9804             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9805     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9806   else
9807     return SDValue();
9808 
9809   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9810   // for XXSPLTI32DX.
9811   unsigned SplatVal = APSplatValue.getZExtValue();
9812   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9813     SplatVal |= (SplatVal << SplatBitSize);
9814 
9815   SDValue SplatNode = DAG.getNode(
9816       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9817       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9818   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9819 }
9820 
9821 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9822 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9823 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9824 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9825 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9826   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9827   assert(Op.getValueType() == MVT::v1i128 &&
9828          "Only set v1i128 as custom, other type shouldn't reach here!");
9829   SDLoc dl(Op);
9830   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9831   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9832   unsigned SHLAmt = N1.getConstantOperandVal(0);
9833   if (SHLAmt % 8 == 0) {
9834     std::array<int, 16> Mask;
9835     std::iota(Mask.begin(), Mask.end(), 0);
9836     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9837     if (SDValue Shuffle =
9838             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9839                                  DAG.getUNDEF(MVT::v16i8), Mask))
9840       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9841   }
9842   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9843   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9844                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9845   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9846                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9847   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9848   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9849 }
9850 
9851 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9852 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9853 /// return the code it can be lowered into.  Worst case, it can always be
9854 /// lowered into a vperm.
9855 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9856                                                SelectionDAG &DAG) const {
9857   SDLoc dl(Op);
9858   SDValue V1 = Op.getOperand(0);
9859   SDValue V2 = Op.getOperand(1);
9860   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9861 
9862   // Any nodes that were combined in the target-independent combiner prior
9863   // to vector legalization will not be sent to the target combine. Try to
9864   // combine it here.
9865   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9866     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9867       return NewShuffle;
9868     Op = NewShuffle;
9869     SVOp = cast<ShuffleVectorSDNode>(Op);
9870     V1 = Op.getOperand(0);
9871     V2 = Op.getOperand(1);
9872   }
9873   EVT VT = Op.getValueType();
9874   bool isLittleEndian = Subtarget.isLittleEndian();
9875 
9876   unsigned ShiftElts, InsertAtByte;
9877   bool Swap = false;
9878 
9879   // If this is a load-and-splat, we can do that with a single instruction
9880   // in some cases. However if the load has multiple uses, we don't want to
9881   // combine it because that will just produce multiple loads.
9882   bool IsPermutedLoad = false;
9883   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9884   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9885       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9886       InputLoad->hasOneUse()) {
9887     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9888     int SplatIdx =
9889       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9890 
9891     // The splat index for permuted loads will be in the left half of the vector
9892     // which is strictly wider than the loaded value by 8 bytes. So we need to
9893     // adjust the splat index to point to the correct address in memory.
9894     if (IsPermutedLoad) {
9895       assert((isLittleEndian || IsFourByte) &&
9896              "Unexpected size for permuted load on big endian target");
9897       SplatIdx += IsFourByte ? 2 : 1;
9898       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9899              "Splat of a value outside of the loaded memory");
9900     }
9901 
9902     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9903     // For 4-byte load-and-splat, we need Power9.
9904     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9905       uint64_t Offset = 0;
9906       if (IsFourByte)
9907         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9908       else
9909         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9910 
9911       // If the width of the load is the same as the width of the splat,
9912       // loading with an offset would load the wrong memory.
9913       if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
9914         Offset = 0;
9915 
9916       SDValue BasePtr = LD->getBasePtr();
9917       if (Offset != 0)
9918         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9919                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9920       SDValue Ops[] = {
9921         LD->getChain(),    // Chain
9922         BasePtr,           // BasePtr
9923         DAG.getValueType(Op.getValueType()) // VT
9924       };
9925       SDVTList VTL =
9926         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9927       SDValue LdSplt =
9928         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9929                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9930       DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
9931       if (LdSplt.getValueType() != SVOp->getValueType(0))
9932         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9933       return LdSplt;
9934     }
9935   }
9936   if (Subtarget.hasP9Vector() &&
9937       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9938                            isLittleEndian)) {
9939     if (Swap)
9940       std::swap(V1, V2);
9941     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9942     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9943     if (ShiftElts) {
9944       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9945                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9946       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9947                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9948       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9949     }
9950     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9951                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9952     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9953   }
9954 
9955   if (Subtarget.hasPrefixInstrs()) {
9956     SDValue SplatInsertNode;
9957     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9958       return SplatInsertNode;
9959   }
9960 
9961   if (Subtarget.hasP9Altivec()) {
9962     SDValue NewISDNode;
9963     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9964       return NewISDNode;
9965 
9966     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9967       return NewISDNode;
9968   }
9969 
9970   if (Subtarget.hasVSX() &&
9971       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9972     if (Swap)
9973       std::swap(V1, V2);
9974     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9975     SDValue Conv2 =
9976         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9977 
9978     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9979                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9980     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9981   }
9982 
9983   if (Subtarget.hasVSX() &&
9984     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9985     if (Swap)
9986       std::swap(V1, V2);
9987     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9988     SDValue Conv2 =
9989         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9990 
9991     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9992                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9993     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9994   }
9995 
9996   if (Subtarget.hasP9Vector()) {
9997      if (PPC::isXXBRHShuffleMask(SVOp)) {
9998       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9999       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10000       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10001     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10002       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10003       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10004       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10005     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10006       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10007       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10008       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10009     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10010       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10011       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10012       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10013     }
10014   }
10015 
10016   if (Subtarget.hasVSX()) {
10017     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10018       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10019 
10020       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10021       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10022                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
10023       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10024     }
10025 
10026     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10027     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10028       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10029       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10030       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10031     }
10032   }
10033 
10034   // Cases that are handled by instructions that take permute immediates
10035   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10036   // selected by the instruction selector.
10037   if (V2.isUndef()) {
10038     if (PPC::isSplatShuffleMask(SVOp, 1) ||
10039         PPC::isSplatShuffleMask(SVOp, 2) ||
10040         PPC::isSplatShuffleMask(SVOp, 4) ||
10041         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10042         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10043         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10044         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10045         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10046         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10047         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10048         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10049         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10050         (Subtarget.hasP8Altivec() && (
10051          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10052          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10053          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10054       return Op;
10055     }
10056   }
10057 
10058   // Altivec has a variety of "shuffle immediates" that take two vector inputs
10059   // and produce a fixed permutation.  If any of these match, do not lower to
10060   // VPERM.
10061   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10062   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10063       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10064       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10065       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10066       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10067       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10068       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10069       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10070       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10071       (Subtarget.hasP8Altivec() && (
10072        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10073        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10074        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10075     return Op;
10076 
10077   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
10078   // perfect shuffle table to emit an optimal matching sequence.
10079   ArrayRef<int> PermMask = SVOp->getMask();
10080 
10081   if (!DisablePerfectShuffle && !isLittleEndian) {
10082     unsigned PFIndexes[4];
10083     bool isFourElementShuffle = true;
10084     for (unsigned i = 0; i != 4 && isFourElementShuffle;
10085          ++i) {                           // Element number
10086       unsigned EltNo = 8;                 // Start out undef.
10087       for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10088         if (PermMask[i * 4 + j] < 0)
10089           continue; // Undef, ignore it.
10090 
10091         unsigned ByteSource = PermMask[i * 4 + j];
10092         if ((ByteSource & 3) != j) {
10093           isFourElementShuffle = false;
10094           break;
10095         }
10096 
10097         if (EltNo == 8) {
10098           EltNo = ByteSource / 4;
10099         } else if (EltNo != ByteSource / 4) {
10100           isFourElementShuffle = false;
10101           break;
10102         }
10103       }
10104       PFIndexes[i] = EltNo;
10105     }
10106 
10107     // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10108     // perfect shuffle vector to determine if it is cost effective to do this as
10109     // discrete instructions, or whether we should use a vperm.
10110     // For now, we skip this for little endian until such time as we have a
10111     // little-endian perfect shuffle table.
10112     if (isFourElementShuffle) {
10113       // Compute the index in the perfect shuffle table.
10114       unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10115                               PFIndexes[2] * 9 + PFIndexes[3];
10116 
10117       unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10118       unsigned Cost = (PFEntry >> 30);
10119 
10120       // Determining when to avoid vperm is tricky.  Many things affect the cost
10121       // of vperm, particularly how many times the perm mask needs to be
10122       // computed. For example, if the perm mask can be hoisted out of a loop or
10123       // is already used (perhaps because there are multiple permutes with the
10124       // same shuffle mask?) the vperm has a cost of 1.  OTOH, hoisting the
10125       // permute mask out of the loop requires an extra register.
10126       //
10127       // As a compromise, we only emit discrete instructions if the shuffle can
10128       // be generated in 3 or fewer operations.  When we have loop information
10129       // available, if this block is within a loop, we should avoid using vperm
10130       // for 3-operation perms and use a constant pool load instead.
10131       if (Cost < 3)
10132         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10133     }
10134   }
10135 
10136   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10137   // vector that will get spilled to the constant pool.
10138   if (V2.isUndef()) V2 = V1;
10139 
10140   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10141   // that it is in input element units, not in bytes.  Convert now.
10142 
10143   // For little endian, the order of the input vectors is reversed, and
10144   // the permutation mask is complemented with respect to 31.  This is
10145   // necessary to produce proper semantics with the big-endian-biased vperm
10146   // instruction.
10147   EVT EltVT = V1.getValueType().getVectorElementType();
10148   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
10149 
10150   SmallVector<SDValue, 16> ResultMask;
10151   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10152     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10153 
10154     for (unsigned j = 0; j != BytesPerElement; ++j)
10155       if (isLittleEndian)
10156         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
10157                                              dl, MVT::i32));
10158       else
10159         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
10160                                              MVT::i32));
10161   }
10162 
10163   ShufflesHandledWithVPERM++;
10164   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10165   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
10166   LLVM_DEBUG(SVOp->dump());
10167   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
10168   LLVM_DEBUG(VPermMask.dump());
10169 
10170   if (isLittleEndian)
10171     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10172                        V2, V1, VPermMask);
10173   else
10174     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
10175                        V1, V2, VPermMask);
10176 }
10177 
10178 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10179 /// vector comparison.  If it is, return true and fill in Opc/isDot with
10180 /// information about the intrinsic.
10181 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10182                                  bool &isDot, const PPCSubtarget &Subtarget) {
10183   unsigned IntrinsicID =
10184       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
10185   CompareOpc = -1;
10186   isDot = false;
10187   switch (IntrinsicID) {
10188   default:
10189     return false;
10190   // Comparison predicates.
10191   case Intrinsic::ppc_altivec_vcmpbfp_p:
10192     CompareOpc = 966;
10193     isDot = true;
10194     break;
10195   case Intrinsic::ppc_altivec_vcmpeqfp_p:
10196     CompareOpc = 198;
10197     isDot = true;
10198     break;
10199   case Intrinsic::ppc_altivec_vcmpequb_p:
10200     CompareOpc = 6;
10201     isDot = true;
10202     break;
10203   case Intrinsic::ppc_altivec_vcmpequh_p:
10204     CompareOpc = 70;
10205     isDot = true;
10206     break;
10207   case Intrinsic::ppc_altivec_vcmpequw_p:
10208     CompareOpc = 134;
10209     isDot = true;
10210     break;
10211   case Intrinsic::ppc_altivec_vcmpequd_p:
10212     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10213       CompareOpc = 199;
10214       isDot = true;
10215     } else
10216       return false;
10217     break;
10218   case Intrinsic::ppc_altivec_vcmpneb_p:
10219   case Intrinsic::ppc_altivec_vcmpneh_p:
10220   case Intrinsic::ppc_altivec_vcmpnew_p:
10221   case Intrinsic::ppc_altivec_vcmpnezb_p:
10222   case Intrinsic::ppc_altivec_vcmpnezh_p:
10223   case Intrinsic::ppc_altivec_vcmpnezw_p:
10224     if (Subtarget.hasP9Altivec()) {
10225       switch (IntrinsicID) {
10226       default:
10227         llvm_unreachable("Unknown comparison intrinsic.");
10228       case Intrinsic::ppc_altivec_vcmpneb_p:
10229         CompareOpc = 7;
10230         break;
10231       case Intrinsic::ppc_altivec_vcmpneh_p:
10232         CompareOpc = 71;
10233         break;
10234       case Intrinsic::ppc_altivec_vcmpnew_p:
10235         CompareOpc = 135;
10236         break;
10237       case Intrinsic::ppc_altivec_vcmpnezb_p:
10238         CompareOpc = 263;
10239         break;
10240       case Intrinsic::ppc_altivec_vcmpnezh_p:
10241         CompareOpc = 327;
10242         break;
10243       case Intrinsic::ppc_altivec_vcmpnezw_p:
10244         CompareOpc = 391;
10245         break;
10246       }
10247       isDot = true;
10248     } else
10249       return false;
10250     break;
10251   case Intrinsic::ppc_altivec_vcmpgefp_p:
10252     CompareOpc = 454;
10253     isDot = true;
10254     break;
10255   case Intrinsic::ppc_altivec_vcmpgtfp_p:
10256     CompareOpc = 710;
10257     isDot = true;
10258     break;
10259   case Intrinsic::ppc_altivec_vcmpgtsb_p:
10260     CompareOpc = 774;
10261     isDot = true;
10262     break;
10263   case Intrinsic::ppc_altivec_vcmpgtsh_p:
10264     CompareOpc = 838;
10265     isDot = true;
10266     break;
10267   case Intrinsic::ppc_altivec_vcmpgtsw_p:
10268     CompareOpc = 902;
10269     isDot = true;
10270     break;
10271   case Intrinsic::ppc_altivec_vcmpgtsd_p:
10272     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10273       CompareOpc = 967;
10274       isDot = true;
10275     } else
10276       return false;
10277     break;
10278   case Intrinsic::ppc_altivec_vcmpgtub_p:
10279     CompareOpc = 518;
10280     isDot = true;
10281     break;
10282   case Intrinsic::ppc_altivec_vcmpgtuh_p:
10283     CompareOpc = 582;
10284     isDot = true;
10285     break;
10286   case Intrinsic::ppc_altivec_vcmpgtuw_p:
10287     CompareOpc = 646;
10288     isDot = true;
10289     break;
10290   case Intrinsic::ppc_altivec_vcmpgtud_p:
10291     if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10292       CompareOpc = 711;
10293       isDot = true;
10294     } else
10295       return false;
10296     break;
10297 
10298   case Intrinsic::ppc_altivec_vcmpequq:
10299   case Intrinsic::ppc_altivec_vcmpgtsq:
10300   case Intrinsic::ppc_altivec_vcmpgtuq:
10301     if (!Subtarget.isISA3_1())
10302       return false;
10303     switch (IntrinsicID) {
10304     default:
10305       llvm_unreachable("Unknown comparison intrinsic.");
10306     case Intrinsic::ppc_altivec_vcmpequq:
10307       CompareOpc = 455;
10308       break;
10309     case Intrinsic::ppc_altivec_vcmpgtsq:
10310       CompareOpc = 903;
10311       break;
10312     case Intrinsic::ppc_altivec_vcmpgtuq:
10313       CompareOpc = 647;
10314       break;
10315     }
10316     break;
10317 
10318   // VSX predicate comparisons use the same infrastructure
10319   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10320   case Intrinsic::ppc_vsx_xvcmpgedp_p:
10321   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10322   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10323   case Intrinsic::ppc_vsx_xvcmpgesp_p:
10324   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10325     if (Subtarget.hasVSX()) {
10326       switch (IntrinsicID) {
10327       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
10328         CompareOpc = 99;
10329         break;
10330       case Intrinsic::ppc_vsx_xvcmpgedp_p:
10331         CompareOpc = 115;
10332         break;
10333       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10334         CompareOpc = 107;
10335         break;
10336       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10337         CompareOpc = 67;
10338         break;
10339       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10340         CompareOpc = 83;
10341         break;
10342       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10343         CompareOpc = 75;
10344         break;
10345       }
10346       isDot = true;
10347     } else
10348       return false;
10349     break;
10350 
10351   // Normal Comparisons.
10352   case Intrinsic::ppc_altivec_vcmpbfp:
10353     CompareOpc = 966;
10354     break;
10355   case Intrinsic::ppc_altivec_vcmpeqfp:
10356     CompareOpc = 198;
10357     break;
10358   case Intrinsic::ppc_altivec_vcmpequb:
10359     CompareOpc = 6;
10360     break;
10361   case Intrinsic::ppc_altivec_vcmpequh:
10362     CompareOpc = 70;
10363     break;
10364   case Intrinsic::ppc_altivec_vcmpequw:
10365     CompareOpc = 134;
10366     break;
10367   case Intrinsic::ppc_altivec_vcmpequd:
10368     if (Subtarget.hasP8Altivec())
10369       CompareOpc = 199;
10370     else
10371       return false;
10372     break;
10373   case Intrinsic::ppc_altivec_vcmpneb:
10374   case Intrinsic::ppc_altivec_vcmpneh:
10375   case Intrinsic::ppc_altivec_vcmpnew:
10376   case Intrinsic::ppc_altivec_vcmpnezb:
10377   case Intrinsic::ppc_altivec_vcmpnezh:
10378   case Intrinsic::ppc_altivec_vcmpnezw:
10379     if (Subtarget.hasP9Altivec())
10380       switch (IntrinsicID) {
10381       default:
10382         llvm_unreachable("Unknown comparison intrinsic.");
10383       case Intrinsic::ppc_altivec_vcmpneb:
10384         CompareOpc = 7;
10385         break;
10386       case Intrinsic::ppc_altivec_vcmpneh:
10387         CompareOpc = 71;
10388         break;
10389       case Intrinsic::ppc_altivec_vcmpnew:
10390         CompareOpc = 135;
10391         break;
10392       case Intrinsic::ppc_altivec_vcmpnezb:
10393         CompareOpc = 263;
10394         break;
10395       case Intrinsic::ppc_altivec_vcmpnezh:
10396         CompareOpc = 327;
10397         break;
10398       case Intrinsic::ppc_altivec_vcmpnezw:
10399         CompareOpc = 391;
10400         break;
10401       }
10402     else
10403       return false;
10404     break;
10405   case Intrinsic::ppc_altivec_vcmpgefp:
10406     CompareOpc = 454;
10407     break;
10408   case Intrinsic::ppc_altivec_vcmpgtfp:
10409     CompareOpc = 710;
10410     break;
10411   case Intrinsic::ppc_altivec_vcmpgtsb:
10412     CompareOpc = 774;
10413     break;
10414   case Intrinsic::ppc_altivec_vcmpgtsh:
10415     CompareOpc = 838;
10416     break;
10417   case Intrinsic::ppc_altivec_vcmpgtsw:
10418     CompareOpc = 902;
10419     break;
10420   case Intrinsic::ppc_altivec_vcmpgtsd:
10421     if (Subtarget.hasP8Altivec())
10422       CompareOpc = 967;
10423     else
10424       return false;
10425     break;
10426   case Intrinsic::ppc_altivec_vcmpgtub:
10427     CompareOpc = 518;
10428     break;
10429   case Intrinsic::ppc_altivec_vcmpgtuh:
10430     CompareOpc = 582;
10431     break;
10432   case Intrinsic::ppc_altivec_vcmpgtuw:
10433     CompareOpc = 646;
10434     break;
10435   case Intrinsic::ppc_altivec_vcmpgtud:
10436     if (Subtarget.hasP8Altivec())
10437       CompareOpc = 711;
10438     else
10439       return false;
10440     break;
10441   case Intrinsic::ppc_altivec_vcmpequq_p:
10442   case Intrinsic::ppc_altivec_vcmpgtsq_p:
10443   case Intrinsic::ppc_altivec_vcmpgtuq_p:
10444     if (!Subtarget.isISA3_1())
10445       return false;
10446     switch (IntrinsicID) {
10447     default:
10448       llvm_unreachable("Unknown comparison intrinsic.");
10449     case Intrinsic::ppc_altivec_vcmpequq_p:
10450       CompareOpc = 455;
10451       break;
10452     case Intrinsic::ppc_altivec_vcmpgtsq_p:
10453       CompareOpc = 903;
10454       break;
10455     case Intrinsic::ppc_altivec_vcmpgtuq_p:
10456       CompareOpc = 647;
10457       break;
10458     }
10459     isDot = true;
10460     break;
10461   }
10462   return true;
10463 }
10464 
10465 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10466 /// lower, do it, otherwise return null.
10467 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10468                                                    SelectionDAG &DAG) const {
10469   unsigned IntrinsicID =
10470     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10471 
10472   SDLoc dl(Op);
10473 
10474   switch (IntrinsicID) {
10475   case Intrinsic::thread_pointer:
10476     // Reads the thread pointer register, used for __builtin_thread_pointer.
10477     if (Subtarget.isPPC64())
10478       return DAG.getRegister(PPC::X13, MVT::i64);
10479     return DAG.getRegister(PPC::R2, MVT::i32);
10480 
10481   case Intrinsic::ppc_mma_disassemble_acc:
10482   case Intrinsic::ppc_vsx_disassemble_pair: {
10483     int NumVecs = 2;
10484     SDValue WideVec = Op.getOperand(1);
10485     if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
10486       NumVecs = 4;
10487       WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
10488     }
10489     SmallVector<SDValue, 4> RetOps;
10490     for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
10491       SDValue Extract = DAG.getNode(
10492           PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
10493           DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
10494                                                      : VecNo,
10495                           dl, getPointerTy(DAG.getDataLayout())));
10496       RetOps.push_back(Extract);
10497     }
10498     return DAG.getMergeValues(RetOps, dl);
10499   }
10500 
10501   case Intrinsic::ppc_unpack_longdouble: {
10502     auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10503     assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
10504            "Argument of long double unpack must be 0 or 1!");
10505     return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
10506                        DAG.getConstant(!!(Idx->getSExtValue()), dl,
10507                                        Idx->getValueType(0)));
10508   }
10509 
10510   case Intrinsic::ppc_compare_exp_lt:
10511   case Intrinsic::ppc_compare_exp_gt:
10512   case Intrinsic::ppc_compare_exp_eq:
10513   case Intrinsic::ppc_compare_exp_uo: {
10514     unsigned Pred;
10515     switch (IntrinsicID) {
10516     case Intrinsic::ppc_compare_exp_lt:
10517       Pred = PPC::PRED_LT;
10518       break;
10519     case Intrinsic::ppc_compare_exp_gt:
10520       Pred = PPC::PRED_GT;
10521       break;
10522     case Intrinsic::ppc_compare_exp_eq:
10523       Pred = PPC::PRED_EQ;
10524       break;
10525     case Intrinsic::ppc_compare_exp_uo:
10526       Pred = PPC::PRED_UN;
10527       break;
10528     }
10529     return SDValue(
10530         DAG.getMachineNode(
10531             PPC::SELECT_CC_I4, dl, MVT::i32,
10532             {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
10533                                         Op.getOperand(1), Op.getOperand(2)),
10534                      0),
10535              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10536              DAG.getTargetConstant(Pred, dl, MVT::i32)}),
10537         0);
10538   }
10539   case Intrinsic::ppc_test_data_class_d:
10540   case Intrinsic::ppc_test_data_class_f: {
10541     unsigned CmprOpc = PPC::XSTSTDCDP;
10542     if (IntrinsicID == Intrinsic::ppc_test_data_class_f)
10543       CmprOpc = PPC::XSTSTDCSP;
10544     return SDValue(
10545         DAG.getMachineNode(
10546             PPC::SELECT_CC_I4, dl, MVT::i32,
10547             {SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32, Op.getOperand(2),
10548                                         Op.getOperand(1)),
10549                      0),
10550              DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
10551              DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
10552         0);
10553   }
10554   case Intrinsic::ppc_fnmsub: {
10555     EVT VT = Op.getOperand(1).getValueType();
10556     if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
10557       return DAG.getNode(
10558           ISD::FNEG, dl, VT,
10559           DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
10560                       DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
10561     return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
10562                        Op.getOperand(2), Op.getOperand(3));
10563   }
10564   case Intrinsic::ppc_convert_f128_to_ppcf128:
10565   case Intrinsic::ppc_convert_ppcf128_to_f128: {
10566     RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
10567                             ? RTLIB::CONVERT_PPCF128_F128
10568                             : RTLIB::CONVERT_F128_PPCF128;
10569     MakeLibCallOptions CallOptions;
10570     std::pair<SDValue, SDValue> Result =
10571         makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
10572                     dl, SDValue());
10573     return Result.first;
10574   }
10575   }
10576 
10577   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10578   // opcode number of the comparison.
10579   int CompareOpc;
10580   bool isDot;
10581   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10582     return SDValue();    // Don't custom lower most intrinsics.
10583 
10584   // If this is a non-dot comparison, make the VCMP node and we are done.
10585   if (!isDot) {
10586     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10587                               Op.getOperand(1), Op.getOperand(2),
10588                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10589     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10590   }
10591 
10592   // Create the PPCISD altivec 'dot' comparison node.
10593   SDValue Ops[] = {
10594     Op.getOperand(2),  // LHS
10595     Op.getOperand(3),  // RHS
10596     DAG.getConstant(CompareOpc, dl, MVT::i32)
10597   };
10598   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10599   SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
10600 
10601   // Now that we have the comparison, emit a copy from the CR to a GPR.
10602   // This is flagged to the above dot comparison.
10603   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10604                                 DAG.getRegister(PPC::CR6, MVT::i32),
10605                                 CompNode.getValue(1));
10606 
10607   // Unpack the result based on how the target uses it.
10608   unsigned BitNo;   // Bit # of CR6.
10609   bool InvertBit;   // Invert result?
10610   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10611   default:  // Can't happen, don't crash on invalid number though.
10612   case 0:   // Return the value of the EQ bit of CR6.
10613     BitNo = 0; InvertBit = false;
10614     break;
10615   case 1:   // Return the inverted value of the EQ bit of CR6.
10616     BitNo = 0; InvertBit = true;
10617     break;
10618   case 2:   // Return the value of the LT bit of CR6.
10619     BitNo = 2; InvertBit = false;
10620     break;
10621   case 3:   // Return the inverted value of the LT bit of CR6.
10622     BitNo = 2; InvertBit = true;
10623     break;
10624   }
10625 
10626   // Shift the bit into the low position.
10627   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10628                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10629   // Isolate the bit.
10630   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10631                       DAG.getConstant(1, dl, MVT::i32));
10632 
10633   // If we are supposed to, toggle the bit.
10634   if (InvertBit)
10635     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10636                         DAG.getConstant(1, dl, MVT::i32));
10637   return Flags;
10638 }
10639 
10640 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10641                                                SelectionDAG &DAG) const {
10642   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10643   // the beginning of the argument list.
10644   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10645   SDLoc DL(Op);
10646   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10647   case Intrinsic::ppc_cfence: {
10648     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10649     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10650     SDValue Val = Op.getOperand(ArgStart + 1);
10651     EVT Ty = Val.getValueType();
10652     if (Ty == MVT::i128) {
10653       // FIXME: Testing one of two paired registers is sufficient to guarantee
10654       // ordering?
10655       Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
10656     }
10657     return SDValue(
10658         DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10659                            DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Val),
10660                            Op.getOperand(0)),
10661         0);
10662   }
10663   default:
10664     break;
10665   }
10666   return SDValue();
10667 }
10668 
10669 // Lower scalar BSWAP64 to xxbrd.
10670 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10671   SDLoc dl(Op);
10672   if (!Subtarget.isPPC64())
10673     return Op;
10674   // MTVSRDD
10675   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10676                    Op.getOperand(0));
10677   // XXBRD
10678   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10679   // MFVSRD
10680   int VectorIndex = 0;
10681   if (Subtarget.isLittleEndian())
10682     VectorIndex = 1;
10683   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10684                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10685   return Op;
10686 }
10687 
10688 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10689 // compared to a value that is atomically loaded (atomic loads zero-extend).
10690 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10691                                                 SelectionDAG &DAG) const {
10692   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10693          "Expecting an atomic compare-and-swap here.");
10694   SDLoc dl(Op);
10695   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10696   EVT MemVT = AtomicNode->getMemoryVT();
10697   if (MemVT.getSizeInBits() >= 32)
10698     return Op;
10699 
10700   SDValue CmpOp = Op.getOperand(2);
10701   // If this is already correctly zero-extended, leave it alone.
10702   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10703   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10704     return Op;
10705 
10706   // Clear the high bits of the compare operand.
10707   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10708   SDValue NewCmpOp =
10709     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10710                 DAG.getConstant(MaskVal, dl, MVT::i32));
10711 
10712   // Replace the existing compare operand with the properly zero-extended one.
10713   SmallVector<SDValue, 4> Ops;
10714   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10715     Ops.push_back(AtomicNode->getOperand(i));
10716   Ops[2] = NewCmpOp;
10717   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10718   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10719   auto NodeTy =
10720     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10721   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10722 }
10723 
10724 SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
10725                                                   SelectionDAG &DAG) const {
10726   AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
10727   EVT MemVT = N->getMemoryVT();
10728   assert(MemVT.getSimpleVT() == MVT::i128 &&
10729          "Expect quadword atomic operations");
10730   SDLoc dl(N);
10731   unsigned Opc = N->getOpcode();
10732   switch (Opc) {
10733   case ISD::ATOMIC_LOAD: {
10734     // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
10735     // lowered to ppc instructions by pattern matching instruction selector.
10736     SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
10737     SmallVector<SDValue, 4> Ops{
10738         N->getOperand(0),
10739         DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
10740     for (int I = 1, E = N->getNumOperands(); I < E; ++I)
10741       Ops.push_back(N->getOperand(I));
10742     SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
10743                                                 Ops, MemVT, N->getMemOperand());
10744     SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
10745     SDValue ValHi =
10746         DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
10747     ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
10748                         DAG.getConstant(64, dl, MVT::i32));
10749     SDValue Val =
10750         DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
10751     return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
10752                        {Val, LoadedVal.getValue(2)});
10753   }
10754   case ISD::ATOMIC_STORE: {
10755     // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
10756     // lowered to ppc instructions by pattern matching instruction selector.
10757     SDVTList Tys = DAG.getVTList(MVT::Other);
10758     SmallVector<SDValue, 4> Ops{
10759         N->getOperand(0),
10760         DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
10761     SDValue Val = N->getOperand(2);
10762     SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
10763     SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
10764                                 DAG.getConstant(64, dl, MVT::i32));
10765     ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
10766     Ops.push_back(ValLo);
10767     Ops.push_back(ValHi);
10768     Ops.push_back(N->getOperand(1));
10769     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
10770                                    N->getMemOperand());
10771   }
10772   default:
10773     llvm_unreachable("Unexpected atomic opcode");
10774   }
10775 }
10776 
10777 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10778                                                  SelectionDAG &DAG) const {
10779   SDLoc dl(Op);
10780   // Create a stack slot that is 16-byte aligned.
10781   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10782   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10783   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10784   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10785 
10786   // Store the input value into Value#0 of the stack slot.
10787   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10788                                MachinePointerInfo());
10789   // Load it out.
10790   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10791 }
10792 
10793 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10794                                                   SelectionDAG &DAG) const {
10795   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10796          "Should only be called for ISD::INSERT_VECTOR_ELT");
10797 
10798   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10799 
10800   EVT VT = Op.getValueType();
10801   SDLoc dl(Op);
10802   SDValue V1 = Op.getOperand(0);
10803   SDValue V2 = Op.getOperand(1);
10804 
10805   if (VT == MVT::v2f64 && C)
10806     return Op;
10807 
10808   if (Subtarget.hasP9Vector()) {
10809     // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
10810     // because on P10, it allows this specific insert_vector_elt load pattern to
10811     // utilize the refactored load and store infrastructure in order to exploit
10812     // prefixed loads.
10813     // On targets with inexpensive direct moves (Power9 and up), a
10814     // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
10815     // load since a single precision load will involve conversion to double
10816     // precision on the load followed by another conversion to single precision.
10817     if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
10818         (isa<LoadSDNode>(V2))) {
10819       SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
10820       SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
10821       SDValue InsVecElt =
10822           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
10823                       BitcastLoad, Op.getOperand(2));
10824       return DAG.getBitcast(MVT::v4f32, InsVecElt);
10825     }
10826   }
10827 
10828   if (Subtarget.isISA3_1()) {
10829     if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
10830       return SDValue();
10831     // On P10, we have legal lowering for constant and variable indices for
10832     // all vectors.
10833     if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
10834         VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
10835       return Op;
10836   }
10837 
10838   // Before P10, we have legal lowering for constant indices but not for
10839   // variable ones.
10840   if (!C)
10841     return SDValue();
10842 
10843   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10844   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10845     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10846     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10847     unsigned InsertAtElement = C->getZExtValue();
10848     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10849     if (Subtarget.isLittleEndian()) {
10850       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10851     }
10852     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10853                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10854   }
10855   return Op;
10856 }
10857 
10858 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
10859                                            SelectionDAG &DAG) const {
10860   SDLoc dl(Op);
10861   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
10862   SDValue LoadChain = LN->getChain();
10863   SDValue BasePtr = LN->getBasePtr();
10864   EVT VT = Op.getValueType();
10865 
10866   if (VT != MVT::v256i1 && VT != MVT::v512i1)
10867     return Op;
10868 
10869   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10870   // Here we create 2 or 4 v16i8 loads to load the pair or accumulator value in
10871   // 2 or 4 vsx registers.
10872   assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
10873          "Type unsupported without MMA");
10874   assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10875          "Type unsupported without paired vector support");
10876   Align Alignment = LN->getAlign();
10877   SmallVector<SDValue, 4> Loads;
10878   SmallVector<SDValue, 4> LoadChains;
10879   unsigned NumVecs = VT.getSizeInBits() / 128;
10880   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10881     SDValue Load =
10882         DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
10883                     LN->getPointerInfo().getWithOffset(Idx * 16),
10884                     commonAlignment(Alignment, Idx * 16),
10885                     LN->getMemOperand()->getFlags(), LN->getAAInfo());
10886     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10887                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10888     Loads.push_back(Load);
10889     LoadChains.push_back(Load.getValue(1));
10890   }
10891   if (Subtarget.isLittleEndian()) {
10892     std::reverse(Loads.begin(), Loads.end());
10893     std::reverse(LoadChains.begin(), LoadChains.end());
10894   }
10895   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10896   SDValue Value =
10897       DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
10898                   dl, VT, Loads);
10899   SDValue RetOps[] = {Value, TF};
10900   return DAG.getMergeValues(RetOps, dl);
10901 }
10902 
10903 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10904                                             SelectionDAG &DAG) const {
10905   SDLoc dl(Op);
10906   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10907   SDValue StoreChain = SN->getChain();
10908   SDValue BasePtr = SN->getBasePtr();
10909   SDValue Value = SN->getValue();
10910   EVT StoreVT = Value.getValueType();
10911 
10912   if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
10913     return Op;
10914 
10915   // Type v256i1 is used for pairs and v512i1 is used for accumulators.
10916   // Here we create 2 or 4 v16i8 stores to store the pair or accumulator
10917   // underlying registers individually.
10918   assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
10919          "Type unsupported without MMA");
10920   assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
10921          "Type unsupported without paired vector support");
10922   Align Alignment = SN->getAlign();
10923   SmallVector<SDValue, 4> Stores;
10924   unsigned NumVecs = 2;
10925   if (StoreVT == MVT::v512i1) {
10926     Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
10927     NumVecs = 4;
10928   }
10929   for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
10930     unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
10931     SDValue Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
10932                               DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
10933     SDValue Store =
10934         DAG.getStore(StoreChain, dl, Elt, BasePtr,
10935                      SN->getPointerInfo().getWithOffset(Idx * 16),
10936                      commonAlignment(Alignment, Idx * 16),
10937                      SN->getMemOperand()->getFlags(), SN->getAAInfo());
10938     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10939                           DAG.getConstant(16, dl, BasePtr.getValueType()));
10940     Stores.push_back(Store);
10941   }
10942   SDValue TF = DAG.getTokenFactor(dl, Stores);
10943   return TF;
10944 }
10945 
10946 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10947   SDLoc dl(Op);
10948   if (Op.getValueType() == MVT::v4i32) {
10949     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10950 
10951     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10952     // +16 as shift amt.
10953     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10954     SDValue RHSSwap =   // = vrlw RHS, 16
10955       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10956 
10957     // Shrinkify inputs to v8i16.
10958     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10959     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10960     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10961 
10962     // Low parts multiplied together, generating 32-bit results (we ignore the
10963     // top parts).
10964     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10965                                         LHS, RHS, DAG, dl, MVT::v4i32);
10966 
10967     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10968                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10969     // Shift the high parts up 16 bits.
10970     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10971                               Neg16, DAG, dl);
10972     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10973   } else if (Op.getValueType() == MVT::v16i8) {
10974     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10975     bool isLittleEndian = Subtarget.isLittleEndian();
10976 
10977     // Multiply the even 8-bit parts, producing 16-bit sums.
10978     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10979                                            LHS, RHS, DAG, dl, MVT::v8i16);
10980     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10981 
10982     // Multiply the odd 8-bit parts, producing 16-bit sums.
10983     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10984                                           LHS, RHS, DAG, dl, MVT::v8i16);
10985     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10986 
10987     // Merge the results together.  Because vmuleub and vmuloub are
10988     // instructions with a big-endian bias, we must reverse the
10989     // element numbering and reverse the meaning of "odd" and "even"
10990     // when generating little endian code.
10991     int Ops[16];
10992     for (unsigned i = 0; i != 8; ++i) {
10993       if (isLittleEndian) {
10994         Ops[i*2  ] = 2*i;
10995         Ops[i*2+1] = 2*i+16;
10996       } else {
10997         Ops[i*2  ] = 2*i+1;
10998         Ops[i*2+1] = 2*i+1+16;
10999       }
11000     }
11001     if (isLittleEndian)
11002       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
11003     else
11004       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
11005   } else {
11006     llvm_unreachable("Unknown mul to lower!");
11007   }
11008 }
11009 
11010 SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11011   bool IsStrict = Op->isStrictFPOpcode();
11012   if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
11013       !Subtarget.hasP9Vector())
11014     return SDValue();
11015 
11016   return Op;
11017 }
11018 
11019 // Custom lowering for fpext vf32 to v2f64
11020 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11021 
11022   assert(Op.getOpcode() == ISD::FP_EXTEND &&
11023          "Should only be called for ISD::FP_EXTEND");
11024 
11025   // FIXME: handle extends from half precision float vectors on P9.
11026   // We only want to custom lower an extend from v2f32 to v2f64.
11027   if (Op.getValueType() != MVT::v2f64 ||
11028       Op.getOperand(0).getValueType() != MVT::v2f32)
11029     return SDValue();
11030 
11031   SDLoc dl(Op);
11032   SDValue Op0 = Op.getOperand(0);
11033 
11034   switch (Op0.getOpcode()) {
11035   default:
11036     return SDValue();
11037   case ISD::EXTRACT_SUBVECTOR: {
11038     assert(Op0.getNumOperands() == 2 &&
11039            isa<ConstantSDNode>(Op0->getOperand(1)) &&
11040            "Node should have 2 operands with second one being a constant!");
11041 
11042     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
11043       return SDValue();
11044 
11045     // Custom lower is only done for high or low doubleword.
11046     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
11047     if (Idx % 2 != 0)
11048       return SDValue();
11049 
11050     // Since input is v4f32, at this point Idx is either 0 or 2.
11051     // Shift to get the doubleword position we want.
11052     int DWord = Idx >> 1;
11053 
11054     // High and low word positions are different on little endian.
11055     if (Subtarget.isLittleEndian())
11056       DWord ^= 0x1;
11057 
11058     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
11059                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
11060   }
11061   case ISD::FADD:
11062   case ISD::FMUL:
11063   case ISD::FSUB: {
11064     SDValue NewLoad[2];
11065     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
11066       // Ensure both input are loads.
11067       SDValue LdOp = Op0.getOperand(i);
11068       if (LdOp.getOpcode() != ISD::LOAD)
11069         return SDValue();
11070       // Generate new load node.
11071       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
11072       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11073       NewLoad[i] = DAG.getMemIntrinsicNode(
11074           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11075           LD->getMemoryVT(), LD->getMemOperand());
11076     }
11077     SDValue NewOp =
11078         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
11079                     NewLoad[1], Op0.getNode()->getFlags());
11080     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
11081                        DAG.getConstant(0, dl, MVT::i32));
11082   }
11083   case ISD::LOAD: {
11084     LoadSDNode *LD = cast<LoadSDNode>(Op0);
11085     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
11086     SDValue NewLd = DAG.getMemIntrinsicNode(
11087         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
11088         LD->getMemoryVT(), LD->getMemOperand());
11089     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
11090                        DAG.getConstant(0, dl, MVT::i32));
11091   }
11092   }
11093   llvm_unreachable("ERROR:Should return for all cases within swtich.");
11094 }
11095 
11096 /// LowerOperation - Provide custom lowering hooks for some operations.
11097 ///
11098 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11099   switch (Op.getOpcode()) {
11100   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
11101   case ISD::FPOW:               return lowerPow(Op, DAG);
11102   case ISD::FSIN:               return lowerSin(Op, DAG);
11103   case ISD::FCOS:               return lowerCos(Op, DAG);
11104   case ISD::FLOG:               return lowerLog(Op, DAG);
11105   case ISD::FLOG10:             return lowerLog10(Op, DAG);
11106   case ISD::FEXP:               return lowerExp(Op, DAG);
11107   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
11108   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
11109   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
11110   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
11111   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
11112   case ISD::STRICT_FSETCC:
11113   case ISD::STRICT_FSETCCS:
11114   case ISD::SETCC:              return LowerSETCC(Op, DAG);
11115   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
11116   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
11117 
11118   case ISD::INLINEASM:
11119   case ISD::INLINEASM_BR:       return LowerINLINEASM(Op, DAG);
11120   // Variable argument lowering.
11121   case ISD::VASTART:            return LowerVASTART(Op, DAG);
11122   case ISD::VAARG:              return LowerVAARG(Op, DAG);
11123   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
11124 
11125   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
11126   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11127   case ISD::GET_DYNAMIC_AREA_OFFSET:
11128     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
11129 
11130   // Exception handling lowering.
11131   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
11132   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
11133   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
11134 
11135   case ISD::LOAD:               return LowerLOAD(Op, DAG);
11136   case ISD::STORE:              return LowerSTORE(Op, DAG);
11137   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
11138   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
11139   case ISD::STRICT_FP_TO_UINT:
11140   case ISD::STRICT_FP_TO_SINT:
11141   case ISD::FP_TO_UINT:
11142   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
11143   case ISD::STRICT_UINT_TO_FP:
11144   case ISD::STRICT_SINT_TO_FP:
11145   case ISD::UINT_TO_FP:
11146   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
11147   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
11148 
11149   // Lower 64-bit shifts.
11150   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
11151   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
11152   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
11153 
11154   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
11155   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
11156 
11157   // Vector-related lowering.
11158   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
11159   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
11160   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11161   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
11162   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
11163   case ISD::MUL:                return LowerMUL(Op, DAG);
11164   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
11165   case ISD::STRICT_FP_ROUND:
11166   case ISD::FP_ROUND:
11167     return LowerFP_ROUND(Op, DAG);
11168   case ISD::ROTL:               return LowerROTL(Op, DAG);
11169 
11170   // For counter-based loop handling.
11171   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
11172 
11173   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
11174 
11175   // Frame & Return address.
11176   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
11177   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
11178 
11179   case ISD::INTRINSIC_VOID:
11180     return LowerINTRINSIC_VOID(Op, DAG);
11181   case ISD::BSWAP:
11182     return LowerBSWAP(Op, DAG);
11183   case ISD::ATOMIC_CMP_SWAP:
11184     return LowerATOMIC_CMP_SWAP(Op, DAG);
11185   case ISD::ATOMIC_STORE:
11186     return LowerATOMIC_LOAD_STORE(Op, DAG);
11187   }
11188 }
11189 
11190 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
11191                                            SmallVectorImpl<SDValue>&Results,
11192                                            SelectionDAG &DAG) const {
11193   SDLoc dl(N);
11194   switch (N->getOpcode()) {
11195   default:
11196     llvm_unreachable("Do not know how to custom type legalize this operation!");
11197   case ISD::ATOMIC_LOAD: {
11198     SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
11199     Results.push_back(Res);
11200     Results.push_back(Res.getValue(1));
11201     break;
11202   }
11203   case ISD::READCYCLECOUNTER: {
11204     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11205     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
11206 
11207     Results.push_back(
11208         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
11209     Results.push_back(RTB.getValue(2));
11210     break;
11211   }
11212   case ISD::INTRINSIC_W_CHAIN: {
11213     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
11214         Intrinsic::loop_decrement)
11215       break;
11216 
11217     assert(N->getValueType(0) == MVT::i1 &&
11218            "Unexpected result type for CTR decrement intrinsic");
11219     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
11220                                  N->getValueType(0));
11221     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
11222     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
11223                                  N->getOperand(1));
11224 
11225     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
11226     Results.push_back(NewInt.getValue(1));
11227     break;
11228   }
11229   case ISD::INTRINSIC_WO_CHAIN: {
11230     switch (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()) {
11231     case Intrinsic::ppc_pack_longdouble:
11232       Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
11233                                     N->getOperand(2), N->getOperand(1)));
11234       break;
11235     case Intrinsic::ppc_fnmsub:
11236     case Intrinsic::ppc_convert_f128_to_ppcf128:
11237       Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
11238       break;
11239     }
11240     break;
11241   }
11242   case ISD::VAARG: {
11243     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
11244       return;
11245 
11246     EVT VT = N->getValueType(0);
11247 
11248     if (VT == MVT::i64) {
11249       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
11250 
11251       Results.push_back(NewNode);
11252       Results.push_back(NewNode.getValue(1));
11253     }
11254     return;
11255   }
11256   case ISD::STRICT_FP_TO_SINT:
11257   case ISD::STRICT_FP_TO_UINT:
11258   case ISD::FP_TO_SINT:
11259   case ISD::FP_TO_UINT: {
11260     // LowerFP_TO_INT() can only handle f32 and f64.
11261     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
11262         MVT::ppcf128)
11263       return;
11264     SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
11265     Results.push_back(LoweredValue);
11266     if (N->isStrictFPOpcode())
11267       Results.push_back(LoweredValue.getValue(1));
11268     return;
11269   }
11270   case ISD::TRUNCATE: {
11271     if (!N->getValueType(0).isVector())
11272       return;
11273     SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
11274     if (Lowered)
11275       Results.push_back(Lowered);
11276     return;
11277   }
11278   case ISD::FSHL:
11279   case ISD::FSHR:
11280     // Don't handle funnel shifts here.
11281     return;
11282   case ISD::BITCAST:
11283     // Don't handle bitcast here.
11284     return;
11285   case ISD::FP_EXTEND:
11286     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
11287     if (Lowered)
11288       Results.push_back(Lowered);
11289     return;
11290   }
11291 }
11292 
11293 //===----------------------------------------------------------------------===//
11294 //  Other Lowering Code
11295 //===----------------------------------------------------------------------===//
11296 
11297 static Instruction *callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id) {
11298   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11299   Function *Func = Intrinsic::getDeclaration(M, Id);
11300   return Builder.CreateCall(Func, {});
11301 }
11302 
11303 // The mappings for emitLeading/TrailingFence is taken from
11304 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11305 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11306                                                  Instruction *Inst,
11307                                                  AtomicOrdering Ord) const {
11308   if (Ord == AtomicOrdering::SequentiallyConsistent)
11309     return callIntrinsic(Builder, Intrinsic::ppc_sync);
11310   if (isReleaseOrStronger(Ord))
11311     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11312   return nullptr;
11313 }
11314 
11315 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11316                                                   Instruction *Inst,
11317                                                   AtomicOrdering Ord) const {
11318   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
11319     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
11320     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
11321     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
11322     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
11323       return Builder.CreateCall(
11324           Intrinsic::getDeclaration(
11325               Builder.GetInsertBlock()->getParent()->getParent(),
11326               Intrinsic::ppc_cfence, {Inst->getType()}),
11327           {Inst});
11328     // FIXME: Can use isync for rmw operation.
11329     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
11330   }
11331   return nullptr;
11332 }
11333 
11334 MachineBasicBlock *
11335 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
11336                                     unsigned AtomicSize,
11337                                     unsigned BinOpcode,
11338                                     unsigned CmpOpcode,
11339                                     unsigned CmpPred) const {
11340   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11341   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11342 
11343   auto LoadMnemonic = PPC::LDARX;
11344   auto StoreMnemonic = PPC::STDCX;
11345   switch (AtomicSize) {
11346   default:
11347     llvm_unreachable("Unexpected size of atomic entity");
11348   case 1:
11349     LoadMnemonic = PPC::LBARX;
11350     StoreMnemonic = PPC::STBCX;
11351     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11352     break;
11353   case 2:
11354     LoadMnemonic = PPC::LHARX;
11355     StoreMnemonic = PPC::STHCX;
11356     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
11357     break;
11358   case 4:
11359     LoadMnemonic = PPC::LWARX;
11360     StoreMnemonic = PPC::STWCX;
11361     break;
11362   case 8:
11363     LoadMnemonic = PPC::LDARX;
11364     StoreMnemonic = PPC::STDCX;
11365     break;
11366   }
11367 
11368   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11369   MachineFunction *F = BB->getParent();
11370   MachineFunction::iterator It = ++BB->getIterator();
11371 
11372   Register dest = MI.getOperand(0).getReg();
11373   Register ptrA = MI.getOperand(1).getReg();
11374   Register ptrB = MI.getOperand(2).getReg();
11375   Register incr = MI.getOperand(3).getReg();
11376   DebugLoc dl = MI.getDebugLoc();
11377 
11378   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11379   MachineBasicBlock *loop2MBB =
11380     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11381   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11382   F->insert(It, loopMBB);
11383   if (CmpOpcode)
11384     F->insert(It, loop2MBB);
11385   F->insert(It, exitMBB);
11386   exitMBB->splice(exitMBB->begin(), BB,
11387                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11388   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11389 
11390   MachineRegisterInfo &RegInfo = F->getRegInfo();
11391   Register TmpReg = (!BinOpcode) ? incr :
11392     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
11393                                            : &PPC::GPRCRegClass);
11394 
11395   //  thisMBB:
11396   //   ...
11397   //   fallthrough --> loopMBB
11398   BB->addSuccessor(loopMBB);
11399 
11400   //  loopMBB:
11401   //   l[wd]arx dest, ptr
11402   //   add r0, dest, incr
11403   //   st[wd]cx. r0, ptr
11404   //   bne- loopMBB
11405   //   fallthrough --> exitMBB
11406 
11407   // For max/min...
11408   //  loopMBB:
11409   //   l[wd]arx dest, ptr
11410   //   cmpl?[wd] incr, dest
11411   //   bgt exitMBB
11412   //  loop2MBB:
11413   //   st[wd]cx. dest, ptr
11414   //   bne- loopMBB
11415   //   fallthrough --> exitMBB
11416 
11417   BB = loopMBB;
11418   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
11419     .addReg(ptrA).addReg(ptrB);
11420   if (BinOpcode)
11421     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
11422   if (CmpOpcode) {
11423     // Signed comparisons of byte or halfword values must be sign-extended.
11424     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
11425       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11426       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
11427               ExtReg).addReg(dest);
11428       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11429         .addReg(incr).addReg(ExtReg);
11430     } else
11431       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11432         .addReg(incr).addReg(dest);
11433 
11434     BuildMI(BB, dl, TII->get(PPC::BCC))
11435       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
11436     BB->addSuccessor(loop2MBB);
11437     BB->addSuccessor(exitMBB);
11438     BB = loop2MBB;
11439   }
11440   BuildMI(BB, dl, TII->get(StoreMnemonic))
11441     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
11442   BuildMI(BB, dl, TII->get(PPC::BCC))
11443     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
11444   BB->addSuccessor(loopMBB);
11445   BB->addSuccessor(exitMBB);
11446 
11447   //  exitMBB:
11448   //   ...
11449   BB = exitMBB;
11450   return BB;
11451 }
11452 
11453 static bool isSignExtended(MachineInstr &MI, const PPCInstrInfo *TII) {
11454   switch(MI.getOpcode()) {
11455   default:
11456     return false;
11457   case PPC::COPY:
11458     return TII->isSignExtended(MI);
11459   case PPC::LHA:
11460   case PPC::LHA8:
11461   case PPC::LHAU:
11462   case PPC::LHAU8:
11463   case PPC::LHAUX:
11464   case PPC::LHAUX8:
11465   case PPC::LHAX:
11466   case PPC::LHAX8:
11467   case PPC::LWA:
11468   case PPC::LWAUX:
11469   case PPC::LWAX:
11470   case PPC::LWAX_32:
11471   case PPC::LWA_32:
11472   case PPC::PLHA:
11473   case PPC::PLHA8:
11474   case PPC::PLHA8pc:
11475   case PPC::PLHApc:
11476   case PPC::PLWA:
11477   case PPC::PLWA8:
11478   case PPC::PLWA8pc:
11479   case PPC::PLWApc:
11480   case PPC::EXTSB:
11481   case PPC::EXTSB8:
11482   case PPC::EXTSB8_32_64:
11483   case PPC::EXTSB8_rec:
11484   case PPC::EXTSB_rec:
11485   case PPC::EXTSH:
11486   case PPC::EXTSH8:
11487   case PPC::EXTSH8_32_64:
11488   case PPC::EXTSH8_rec:
11489   case PPC::EXTSH_rec:
11490   case PPC::EXTSW:
11491   case PPC::EXTSWSLI:
11492   case PPC::EXTSWSLI_32_64:
11493   case PPC::EXTSWSLI_32_64_rec:
11494   case PPC::EXTSWSLI_rec:
11495   case PPC::EXTSW_32:
11496   case PPC::EXTSW_32_64:
11497   case PPC::EXTSW_32_64_rec:
11498   case PPC::EXTSW_rec:
11499   case PPC::SRAW:
11500   case PPC::SRAWI:
11501   case PPC::SRAWI_rec:
11502   case PPC::SRAW_rec:
11503     return true;
11504   }
11505   return false;
11506 }
11507 
11508 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
11509     MachineInstr &MI, MachineBasicBlock *BB,
11510     bool is8bit, // operation
11511     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
11512   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
11513   const PPCInstrInfo *TII = Subtarget.getInstrInfo();
11514 
11515   // If this is a signed comparison and the value being compared is not known
11516   // to be sign extended, sign extend it here.
11517   DebugLoc dl = MI.getDebugLoc();
11518   MachineFunction *F = BB->getParent();
11519   MachineRegisterInfo &RegInfo = F->getRegInfo();
11520   Register incr = MI.getOperand(3).getReg();
11521   bool IsSignExtended = Register::isVirtualRegister(incr) &&
11522     isSignExtended(*RegInfo.getVRegDef(incr), TII);
11523 
11524   if (CmpOpcode == PPC::CMPW && !IsSignExtended) {
11525     Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11526     BuildMI(*BB, MI, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueReg)
11527         .addReg(MI.getOperand(3).getReg());
11528     MI.getOperand(3).setReg(ValueReg);
11529   }
11530   // If we support part-word atomic mnemonics, just use them
11531   if (Subtarget.hasPartwordAtomics())
11532     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
11533                             CmpPred);
11534 
11535   // In 64 bit mode we have to use 64 bits for addresses, even though the
11536   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
11537   // registers without caring whether they're 32 or 64, but here we're
11538   // doing actual arithmetic on the addresses.
11539   bool is64bit = Subtarget.isPPC64();
11540   bool isLittleEndian = Subtarget.isLittleEndian();
11541   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11542 
11543   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11544   MachineFunction::iterator It = ++BB->getIterator();
11545 
11546   Register dest = MI.getOperand(0).getReg();
11547   Register ptrA = MI.getOperand(1).getReg();
11548   Register ptrB = MI.getOperand(2).getReg();
11549 
11550   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
11551   MachineBasicBlock *loop2MBB =
11552       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
11553   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11554   F->insert(It, loopMBB);
11555   if (CmpOpcode)
11556     F->insert(It, loop2MBB);
11557   F->insert(It, exitMBB);
11558   exitMBB->splice(exitMBB->begin(), BB,
11559                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
11560   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11561 
11562   const TargetRegisterClass *RC =
11563       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11564   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11565 
11566   Register PtrReg = RegInfo.createVirtualRegister(RC);
11567   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11568   Register ShiftReg =
11569       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11570   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
11571   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11572   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11573   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11574   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11575   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
11576   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11577   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11578   Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
11579   Register Ptr1Reg;
11580   Register TmpReg =
11581       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
11582 
11583   //  thisMBB:
11584   //   ...
11585   //   fallthrough --> loopMBB
11586   BB->addSuccessor(loopMBB);
11587 
11588   // The 4-byte load must be aligned, while a char or short may be
11589   // anywhere in the word.  Hence all this nasty bookkeeping code.
11590   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11591   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11592   //   xori shift, shift1, 24 [16]
11593   //   rlwinm ptr, ptr1, 0, 0, 29
11594   //   slw incr2, incr, shift
11595   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11596   //   slw mask, mask2, shift
11597   //  loopMBB:
11598   //   lwarx tmpDest, ptr
11599   //   add tmp, tmpDest, incr2
11600   //   andc tmp2, tmpDest, mask
11601   //   and tmp3, tmp, mask
11602   //   or tmp4, tmp3, tmp2
11603   //   stwcx. tmp4, ptr
11604   //   bne- loopMBB
11605   //   fallthrough --> exitMBB
11606   //   srw SrwDest, tmpDest, shift
11607   //   rlwinm SrwDest, SrwDest, 0, 24 [16], 31
11608   if (ptrA != ZeroReg) {
11609     Ptr1Reg = RegInfo.createVirtualRegister(RC);
11610     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11611         .addReg(ptrA)
11612         .addReg(ptrB);
11613   } else {
11614     Ptr1Reg = ptrB;
11615   }
11616   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11617   // mode.
11618   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11619       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11620       .addImm(3)
11621       .addImm(27)
11622       .addImm(is8bit ? 28 : 27);
11623   if (!isLittleEndian)
11624     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11625         .addReg(Shift1Reg)
11626         .addImm(is8bit ? 24 : 16);
11627   if (is64bit)
11628     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11629         .addReg(Ptr1Reg)
11630         .addImm(0)
11631         .addImm(61);
11632   else
11633     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11634         .addReg(Ptr1Reg)
11635         .addImm(0)
11636         .addImm(0)
11637         .addImm(29);
11638   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
11639   if (is8bit)
11640     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11641   else {
11642     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11643     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11644         .addReg(Mask3Reg)
11645         .addImm(65535);
11646   }
11647   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11648       .addReg(Mask2Reg)
11649       .addReg(ShiftReg);
11650 
11651   BB = loopMBB;
11652   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11653       .addReg(ZeroReg)
11654       .addReg(PtrReg);
11655   if (BinOpcode)
11656     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
11657         .addReg(Incr2Reg)
11658         .addReg(TmpDestReg);
11659   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11660       .addReg(TmpDestReg)
11661       .addReg(MaskReg);
11662   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
11663   if (CmpOpcode) {
11664     // For unsigned comparisons, we can directly compare the shifted values.
11665     // For signed comparisons we shift and sign extend.
11666     Register SReg = RegInfo.createVirtualRegister(GPRC);
11667     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
11668         .addReg(TmpDestReg)
11669         .addReg(MaskReg);
11670     unsigned ValueReg = SReg;
11671     unsigned CmpReg = Incr2Reg;
11672     if (CmpOpcode == PPC::CMPW) {
11673       ValueReg = RegInfo.createVirtualRegister(GPRC);
11674       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
11675           .addReg(SReg)
11676           .addReg(ShiftReg);
11677       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
11678       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
11679           .addReg(ValueReg);
11680       ValueReg = ValueSReg;
11681       CmpReg = incr;
11682     }
11683     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
11684         .addReg(CmpReg)
11685         .addReg(ValueReg);
11686     BuildMI(BB, dl, TII->get(PPC::BCC))
11687         .addImm(CmpPred)
11688         .addReg(PPC::CR0)
11689         .addMBB(exitMBB);
11690     BB->addSuccessor(loop2MBB);
11691     BB->addSuccessor(exitMBB);
11692     BB = loop2MBB;
11693   }
11694   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
11695   BuildMI(BB, dl, TII->get(PPC::STWCX))
11696       .addReg(Tmp4Reg)
11697       .addReg(ZeroReg)
11698       .addReg(PtrReg);
11699   BuildMI(BB, dl, TII->get(PPC::BCC))
11700       .addImm(PPC::PRED_NE)
11701       .addReg(PPC::CR0)
11702       .addMBB(loopMBB);
11703   BB->addSuccessor(loopMBB);
11704   BB->addSuccessor(exitMBB);
11705 
11706   //  exitMBB:
11707   //   ...
11708   BB = exitMBB;
11709   // Since the shift amount is not a constant, we need to clear
11710   // the upper bits with a separate RLWINM.
11711   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
11712       .addReg(SrwDestReg)
11713       .addImm(0)
11714       .addImm(is8bit ? 24 : 16)
11715       .addImm(31);
11716   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
11717       .addReg(TmpDestReg)
11718       .addReg(ShiftReg);
11719   return BB;
11720 }
11721 
11722 llvm::MachineBasicBlock *
11723 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11724                                     MachineBasicBlock *MBB) const {
11725   DebugLoc DL = MI.getDebugLoc();
11726   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11727   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11728 
11729   MachineFunction *MF = MBB->getParent();
11730   MachineRegisterInfo &MRI = MF->getRegInfo();
11731 
11732   const BasicBlock *BB = MBB->getBasicBlock();
11733   MachineFunction::iterator I = ++MBB->getIterator();
11734 
11735   Register DstReg = MI.getOperand(0).getReg();
11736   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11737   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11738   Register mainDstReg = MRI.createVirtualRegister(RC);
11739   Register restoreDstReg = MRI.createVirtualRegister(RC);
11740 
11741   MVT PVT = getPointerTy(MF->getDataLayout());
11742   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11743          "Invalid Pointer Size!");
11744   // For v = setjmp(buf), we generate
11745   //
11746   // thisMBB:
11747   //  SjLjSetup mainMBB
11748   //  bl mainMBB
11749   //  v_restore = 1
11750   //  b sinkMBB
11751   //
11752   // mainMBB:
11753   //  buf[LabelOffset] = LR
11754   //  v_main = 0
11755   //
11756   // sinkMBB:
11757   //  v = phi(main, restore)
11758   //
11759 
11760   MachineBasicBlock *thisMBB = MBB;
11761   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11762   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11763   MF->insert(I, mainMBB);
11764   MF->insert(I, sinkMBB);
11765 
11766   MachineInstrBuilder MIB;
11767 
11768   // Transfer the remainder of BB and its successor edges to sinkMBB.
11769   sinkMBB->splice(sinkMBB->begin(), MBB,
11770                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11771   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11772 
11773   // Note that the structure of the jmp_buf used here is not compatible
11774   // with that used by libc, and is not designed to be. Specifically, it
11775   // stores only those 'reserved' registers that LLVM does not otherwise
11776   // understand how to spill. Also, by convention, by the time this
11777   // intrinsic is called, Clang has already stored the frame address in the
11778   // first slot of the buffer and stack address in the third. Following the
11779   // X86 target code, we'll store the jump address in the second slot. We also
11780   // need to save the TOC pointer (R2) to handle jumps between shared
11781   // libraries, and that will be stored in the fourth slot. The thread
11782   // identifier (R13) is not affected.
11783 
11784   // thisMBB:
11785   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11786   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11787   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11788 
11789   // Prepare IP either in reg.
11790   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11791   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11792   Register BufReg = MI.getOperand(1).getReg();
11793 
11794   if (Subtarget.is64BitELFABI()) {
11795     setUsesTOCBasePtr(*MBB->getParent());
11796     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11797               .addReg(PPC::X2)
11798               .addImm(TOCOffset)
11799               .addReg(BufReg)
11800               .cloneMemRefs(MI);
11801   }
11802 
11803   // Naked functions never have a base pointer, and so we use r1. For all
11804   // other functions, this decision must be delayed until during PEI.
11805   unsigned BaseReg;
11806   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11807     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11808   else
11809     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11810 
11811   MIB = BuildMI(*thisMBB, MI, DL,
11812                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11813             .addReg(BaseReg)
11814             .addImm(BPOffset)
11815             .addReg(BufReg)
11816             .cloneMemRefs(MI);
11817 
11818   // Setup
11819   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11820   MIB.addRegMask(TRI->getNoPreservedMask());
11821 
11822   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11823 
11824   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11825           .addMBB(mainMBB);
11826   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11827 
11828   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11829   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11830 
11831   // mainMBB:
11832   //  mainDstReg = 0
11833   MIB =
11834       BuildMI(mainMBB, DL,
11835               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11836 
11837   // Store IP
11838   if (Subtarget.isPPC64()) {
11839     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11840             .addReg(LabelReg)
11841             .addImm(LabelOffset)
11842             .addReg(BufReg);
11843   } else {
11844     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11845             .addReg(LabelReg)
11846             .addImm(LabelOffset)
11847             .addReg(BufReg);
11848   }
11849   MIB.cloneMemRefs(MI);
11850 
11851   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11852   mainMBB->addSuccessor(sinkMBB);
11853 
11854   // sinkMBB:
11855   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11856           TII->get(PPC::PHI), DstReg)
11857     .addReg(mainDstReg).addMBB(mainMBB)
11858     .addReg(restoreDstReg).addMBB(thisMBB);
11859 
11860   MI.eraseFromParent();
11861   return sinkMBB;
11862 }
11863 
11864 MachineBasicBlock *
11865 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11866                                      MachineBasicBlock *MBB) const {
11867   DebugLoc DL = MI.getDebugLoc();
11868   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11869 
11870   MachineFunction *MF = MBB->getParent();
11871   MachineRegisterInfo &MRI = MF->getRegInfo();
11872 
11873   MVT PVT = getPointerTy(MF->getDataLayout());
11874   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11875          "Invalid Pointer Size!");
11876 
11877   const TargetRegisterClass *RC =
11878     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11879   Register Tmp = MRI.createVirtualRegister(RC);
11880   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11881   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11882   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11883   unsigned BP =
11884       (PVT == MVT::i64)
11885           ? PPC::X30
11886           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11887                                                               : PPC::R30);
11888 
11889   MachineInstrBuilder MIB;
11890 
11891   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11892   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11893   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11894   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11895 
11896   Register BufReg = MI.getOperand(0).getReg();
11897 
11898   // Reload FP (the jumped-to function may not have had a
11899   // frame pointer, and if so, then its r31 will be restored
11900   // as necessary).
11901   if (PVT == MVT::i64) {
11902     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11903             .addImm(0)
11904             .addReg(BufReg);
11905   } else {
11906     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11907             .addImm(0)
11908             .addReg(BufReg);
11909   }
11910   MIB.cloneMemRefs(MI);
11911 
11912   // Reload IP
11913   if (PVT == MVT::i64) {
11914     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11915             .addImm(LabelOffset)
11916             .addReg(BufReg);
11917   } else {
11918     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11919             .addImm(LabelOffset)
11920             .addReg(BufReg);
11921   }
11922   MIB.cloneMemRefs(MI);
11923 
11924   // Reload SP
11925   if (PVT == MVT::i64) {
11926     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11927             .addImm(SPOffset)
11928             .addReg(BufReg);
11929   } else {
11930     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11931             .addImm(SPOffset)
11932             .addReg(BufReg);
11933   }
11934   MIB.cloneMemRefs(MI);
11935 
11936   // Reload BP
11937   if (PVT == MVT::i64) {
11938     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11939             .addImm(BPOffset)
11940             .addReg(BufReg);
11941   } else {
11942     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11943             .addImm(BPOffset)
11944             .addReg(BufReg);
11945   }
11946   MIB.cloneMemRefs(MI);
11947 
11948   // Reload TOC
11949   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11950     setUsesTOCBasePtr(*MBB->getParent());
11951     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11952               .addImm(TOCOffset)
11953               .addReg(BufReg)
11954               .cloneMemRefs(MI);
11955   }
11956 
11957   // Jump
11958   BuildMI(*MBB, MI, DL,
11959           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11960   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11961 
11962   MI.eraseFromParent();
11963   return MBB;
11964 }
11965 
11966 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11967   // If the function specifically requests inline stack probes, emit them.
11968   if (MF.getFunction().hasFnAttribute("probe-stack"))
11969     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11970            "inline-asm";
11971   return false;
11972 }
11973 
11974 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11975   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11976   unsigned StackAlign = TFI->getStackAlignment();
11977   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11978          "Unexpected stack alignment");
11979   // The default stack probe size is 4096 if the function has no
11980   // stack-probe-size attribute.
11981   unsigned StackProbeSize = 4096;
11982   const Function &Fn = MF.getFunction();
11983   if (Fn.hasFnAttribute("stack-probe-size"))
11984     Fn.getFnAttribute("stack-probe-size")
11985         .getValueAsString()
11986         .getAsInteger(0, StackProbeSize);
11987   // Round down to the stack alignment.
11988   StackProbeSize &= ~(StackAlign - 1);
11989   return StackProbeSize ? StackProbeSize : StackAlign;
11990 }
11991 
11992 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11993 // into three phases. In the first phase, it uses pseudo instruction
11994 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11995 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11996 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11997 // MaxCallFrameSize so that it can calculate correct data area pointer.
11998 MachineBasicBlock *
11999 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
12000                                     MachineBasicBlock *MBB) const {
12001   const bool isPPC64 = Subtarget.isPPC64();
12002   MachineFunction *MF = MBB->getParent();
12003   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12004   DebugLoc DL = MI.getDebugLoc();
12005   const unsigned ProbeSize = getStackProbeSize(*MF);
12006   const BasicBlock *ProbedBB = MBB->getBasicBlock();
12007   MachineRegisterInfo &MRI = MF->getRegInfo();
12008   // The CFG of probing stack looks as
12009   //         +-----+
12010   //         | MBB |
12011   //         +--+--+
12012   //            |
12013   //       +----v----+
12014   //  +--->+ TestMBB +---+
12015   //  |    +----+----+   |
12016   //  |         |        |
12017   //  |   +-----v----+   |
12018   //  +---+ BlockMBB |   |
12019   //      +----------+   |
12020   //                     |
12021   //       +---------+   |
12022   //       | TailMBB +<--+
12023   //       +---------+
12024   // In MBB, calculate previous frame pointer and final stack pointer.
12025   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
12026   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
12027   // TailMBB is spliced via \p MI.
12028   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
12029   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
12030   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
12031 
12032   MachineFunction::iterator MBBIter = ++MBB->getIterator();
12033   MF->insert(MBBIter, TestMBB);
12034   MF->insert(MBBIter, BlockMBB);
12035   MF->insert(MBBIter, TailMBB);
12036 
12037   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
12038   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12039 
12040   Register DstReg = MI.getOperand(0).getReg();
12041   Register NegSizeReg = MI.getOperand(1).getReg();
12042   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
12043   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12044   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12045   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12046 
12047   // Since value of NegSizeReg might be realigned in prologepilog, insert a
12048   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
12049   // NegSize.
12050   unsigned ProbeOpc;
12051   if (!MRI.hasOneNonDBGUse(NegSizeReg))
12052     ProbeOpc =
12053         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
12054   else
12055     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
12056     // and NegSizeReg will be allocated in the same phyreg to avoid
12057     // redundant copy when NegSizeReg has only one use which is current MI and
12058     // will be replaced by PREPARE_PROBED_ALLOCA then.
12059     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
12060                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
12061   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
12062       .addDef(ActualNegSizeReg)
12063       .addReg(NegSizeReg)
12064       .add(MI.getOperand(2))
12065       .add(MI.getOperand(3));
12066 
12067   // Calculate final stack pointer, which equals to SP + ActualNegSize.
12068   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
12069           FinalStackPtr)
12070       .addReg(SPReg)
12071       .addReg(ActualNegSizeReg);
12072 
12073   // Materialize a scratch register for update.
12074   int64_t NegProbeSize = -(int64_t)ProbeSize;
12075   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
12076   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12077   if (!isInt<16>(NegProbeSize)) {
12078     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12079     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
12080         .addImm(NegProbeSize >> 16);
12081     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
12082             ScratchReg)
12083         .addReg(TempReg)
12084         .addImm(NegProbeSize & 0xFFFF);
12085   } else
12086     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
12087         .addImm(NegProbeSize);
12088 
12089   {
12090     // Probing leading residual part.
12091     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12092     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
12093         .addReg(ActualNegSizeReg)
12094         .addReg(ScratchReg);
12095     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12096     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
12097         .addReg(Div)
12098         .addReg(ScratchReg);
12099     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12100     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
12101         .addReg(Mul)
12102         .addReg(ActualNegSizeReg);
12103     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12104         .addReg(FramePointer)
12105         .addReg(SPReg)
12106         .addReg(NegMod);
12107   }
12108 
12109   {
12110     // Remaining part should be multiple of ProbeSize.
12111     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
12112     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
12113         .addReg(SPReg)
12114         .addReg(FinalStackPtr);
12115     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
12116         .addImm(PPC::PRED_EQ)
12117         .addReg(CmpResult)
12118         .addMBB(TailMBB);
12119     TestMBB->addSuccessor(BlockMBB);
12120     TestMBB->addSuccessor(TailMBB);
12121   }
12122 
12123   {
12124     // Touch the block.
12125     // |P...|P...|P...
12126     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
12127         .addReg(FramePointer)
12128         .addReg(SPReg)
12129         .addReg(ScratchReg);
12130     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
12131     BlockMBB->addSuccessor(TestMBB);
12132   }
12133 
12134   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
12135   // DYNAREAOFFSET pseudo instruction to get the future result.
12136   Register MaxCallFrameSizeReg =
12137       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
12138   BuildMI(TailMBB, DL,
12139           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
12140           MaxCallFrameSizeReg)
12141       .add(MI.getOperand(2))
12142       .add(MI.getOperand(3));
12143   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
12144       .addReg(SPReg)
12145       .addReg(MaxCallFrameSizeReg);
12146 
12147   // Splice instructions after MI to TailMBB.
12148   TailMBB->splice(TailMBB->end(), MBB,
12149                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
12150   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
12151   MBB->addSuccessor(TestMBB);
12152 
12153   // Delete the pseudo instruction.
12154   MI.eraseFromParent();
12155 
12156   ++NumDynamicAllocaProbed;
12157   return TailMBB;
12158 }
12159 
12160 MachineBasicBlock *
12161 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
12162                                                MachineBasicBlock *BB) const {
12163   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
12164       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
12165     if (Subtarget.is64BitELFABI() &&
12166         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
12167         !Subtarget.isUsingPCRelativeCalls()) {
12168       // Call lowering should have added an r2 operand to indicate a dependence
12169       // on the TOC base pointer value. It can't however, because there is no
12170       // way to mark the dependence as implicit there, and so the stackmap code
12171       // will confuse it with a regular operand. Instead, add the dependence
12172       // here.
12173       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
12174     }
12175 
12176     return emitPatchPoint(MI, BB);
12177   }
12178 
12179   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
12180       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
12181     return emitEHSjLjSetJmp(MI, BB);
12182   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
12183              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
12184     return emitEHSjLjLongJmp(MI, BB);
12185   }
12186 
12187   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12188 
12189   // To "insert" these instructions we actually have to insert their
12190   // control-flow patterns.
12191   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12192   MachineFunction::iterator It = ++BB->getIterator();
12193 
12194   MachineFunction *F = BB->getParent();
12195   MachineRegisterInfo &MRI = F->getRegInfo();
12196 
12197   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12198       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
12199       MI.getOpcode() == PPC::SELECT_I8) {
12200     SmallVector<MachineOperand, 2> Cond;
12201     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
12202         MI.getOpcode() == PPC::SELECT_CC_I8)
12203       Cond.push_back(MI.getOperand(4));
12204     else
12205       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
12206     Cond.push_back(MI.getOperand(1));
12207 
12208     DebugLoc dl = MI.getDebugLoc();
12209     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
12210                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
12211   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
12212              MI.getOpcode() == PPC::SELECT_CC_F8 ||
12213              MI.getOpcode() == PPC::SELECT_CC_F16 ||
12214              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
12215              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
12216              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
12217              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
12218              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
12219              MI.getOpcode() == PPC::SELECT_CC_SPE ||
12220              MI.getOpcode() == PPC::SELECT_F4 ||
12221              MI.getOpcode() == PPC::SELECT_F8 ||
12222              MI.getOpcode() == PPC::SELECT_F16 ||
12223              MI.getOpcode() == PPC::SELECT_SPE ||
12224              MI.getOpcode() == PPC::SELECT_SPE4 ||
12225              MI.getOpcode() == PPC::SELECT_VRRC ||
12226              MI.getOpcode() == PPC::SELECT_VSFRC ||
12227              MI.getOpcode() == PPC::SELECT_VSSRC ||
12228              MI.getOpcode() == PPC::SELECT_VSRC) {
12229     // The incoming instruction knows the destination vreg to set, the
12230     // condition code register to branch on, the true/false values to
12231     // select between, and a branch opcode to use.
12232 
12233     //  thisMBB:
12234     //  ...
12235     //   TrueVal = ...
12236     //   cmpTY ccX, r1, r2
12237     //   bCC copy1MBB
12238     //   fallthrough --> copy0MBB
12239     MachineBasicBlock *thisMBB = BB;
12240     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12241     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12242     DebugLoc dl = MI.getDebugLoc();
12243     F->insert(It, copy0MBB);
12244     F->insert(It, sinkMBB);
12245 
12246     // Transfer the remainder of BB and its successor edges to sinkMBB.
12247     sinkMBB->splice(sinkMBB->begin(), BB,
12248                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12249     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12250 
12251     // Next, add the true and fallthrough blocks as its successors.
12252     BB->addSuccessor(copy0MBB);
12253     BB->addSuccessor(sinkMBB);
12254 
12255     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
12256         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
12257         MI.getOpcode() == PPC::SELECT_F16 ||
12258         MI.getOpcode() == PPC::SELECT_SPE4 ||
12259         MI.getOpcode() == PPC::SELECT_SPE ||
12260         MI.getOpcode() == PPC::SELECT_VRRC ||
12261         MI.getOpcode() == PPC::SELECT_VSFRC ||
12262         MI.getOpcode() == PPC::SELECT_VSSRC ||
12263         MI.getOpcode() == PPC::SELECT_VSRC) {
12264       BuildMI(BB, dl, TII->get(PPC::BC))
12265           .addReg(MI.getOperand(1).getReg())
12266           .addMBB(sinkMBB);
12267     } else {
12268       unsigned SelectPred = MI.getOperand(4).getImm();
12269       BuildMI(BB, dl, TII->get(PPC::BCC))
12270           .addImm(SelectPred)
12271           .addReg(MI.getOperand(1).getReg())
12272           .addMBB(sinkMBB);
12273     }
12274 
12275     //  copy0MBB:
12276     //   %FalseValue = ...
12277     //   # fallthrough to sinkMBB
12278     BB = copy0MBB;
12279 
12280     // Update machine-CFG edges
12281     BB->addSuccessor(sinkMBB);
12282 
12283     //  sinkMBB:
12284     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12285     //  ...
12286     BB = sinkMBB;
12287     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
12288         .addReg(MI.getOperand(3).getReg())
12289         .addMBB(copy0MBB)
12290         .addReg(MI.getOperand(2).getReg())
12291         .addMBB(thisMBB);
12292   } else if (MI.getOpcode() == PPC::ReadTB) {
12293     // To read the 64-bit time-base register on a 32-bit target, we read the
12294     // two halves. Should the counter have wrapped while it was being read, we
12295     // need to try again.
12296     // ...
12297     // readLoop:
12298     // mfspr Rx,TBU # load from TBU
12299     // mfspr Ry,TB  # load from TB
12300     // mfspr Rz,TBU # load from TBU
12301     // cmpw crX,Rx,Rz # check if 'old'='new'
12302     // bne readLoop   # branch if they're not equal
12303     // ...
12304 
12305     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
12306     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12307     DebugLoc dl = MI.getDebugLoc();
12308     F->insert(It, readMBB);
12309     F->insert(It, sinkMBB);
12310 
12311     // Transfer the remainder of BB and its successor edges to sinkMBB.
12312     sinkMBB->splice(sinkMBB->begin(), BB,
12313                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12314     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12315 
12316     BB->addSuccessor(readMBB);
12317     BB = readMBB;
12318 
12319     MachineRegisterInfo &RegInfo = F->getRegInfo();
12320     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
12321     Register LoReg = MI.getOperand(0).getReg();
12322     Register HiReg = MI.getOperand(1).getReg();
12323 
12324     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
12325     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
12326     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
12327 
12328     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12329 
12330     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
12331         .addReg(HiReg)
12332         .addReg(ReadAgainReg);
12333     BuildMI(BB, dl, TII->get(PPC::BCC))
12334         .addImm(PPC::PRED_NE)
12335         .addReg(CmpReg)
12336         .addMBB(readMBB);
12337 
12338     BB->addSuccessor(readMBB);
12339     BB->addSuccessor(sinkMBB);
12340   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
12341     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
12342   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
12343     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
12344   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
12345     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
12346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
12347     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
12348 
12349   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
12350     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
12351   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
12352     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
12353   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
12354     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
12355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
12356     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
12357 
12358   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
12359     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
12360   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
12361     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
12362   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
12363     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
12364   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
12365     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
12366 
12367   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
12368     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
12369   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
12370     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
12371   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
12372     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
12373   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
12374     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
12375 
12376   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
12377     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
12378   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
12379     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
12380   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
12381     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
12382   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
12383     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
12384 
12385   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
12386     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
12387   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
12388     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
12389   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
12390     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
12391   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
12392     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
12393 
12394   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
12395     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
12396   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
12397     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
12398   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
12399     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
12400   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
12401     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
12402 
12403   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
12404     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
12405   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
12406     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
12407   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
12408     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
12409   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
12410     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
12411 
12412   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
12413     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
12414   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
12415     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
12416   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
12417     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
12418   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
12419     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
12420 
12421   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
12422     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
12423   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
12424     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
12425   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
12426     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
12427   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
12428     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
12429 
12430   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
12431     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
12432   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
12433     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
12434   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
12435     BB = EmitAtomicBinary(MI, BB, 4, 0);
12436   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
12437     BB = EmitAtomicBinary(MI, BB, 8, 0);
12438   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
12439            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
12440            (Subtarget.hasPartwordAtomics() &&
12441             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
12442            (Subtarget.hasPartwordAtomics() &&
12443             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
12444     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
12445 
12446     auto LoadMnemonic = PPC::LDARX;
12447     auto StoreMnemonic = PPC::STDCX;
12448     switch (MI.getOpcode()) {
12449     default:
12450       llvm_unreachable("Compare and swap of unknown size");
12451     case PPC::ATOMIC_CMP_SWAP_I8:
12452       LoadMnemonic = PPC::LBARX;
12453       StoreMnemonic = PPC::STBCX;
12454       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12455       break;
12456     case PPC::ATOMIC_CMP_SWAP_I16:
12457       LoadMnemonic = PPC::LHARX;
12458       StoreMnemonic = PPC::STHCX;
12459       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
12460       break;
12461     case PPC::ATOMIC_CMP_SWAP_I32:
12462       LoadMnemonic = PPC::LWARX;
12463       StoreMnemonic = PPC::STWCX;
12464       break;
12465     case PPC::ATOMIC_CMP_SWAP_I64:
12466       LoadMnemonic = PPC::LDARX;
12467       StoreMnemonic = PPC::STDCX;
12468       break;
12469     }
12470     Register dest = MI.getOperand(0).getReg();
12471     Register ptrA = MI.getOperand(1).getReg();
12472     Register ptrB = MI.getOperand(2).getReg();
12473     Register oldval = MI.getOperand(3).getReg();
12474     Register newval = MI.getOperand(4).getReg();
12475     DebugLoc dl = MI.getDebugLoc();
12476 
12477     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12478     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12479     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12480     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12481     F->insert(It, loop1MBB);
12482     F->insert(It, loop2MBB);
12483     F->insert(It, midMBB);
12484     F->insert(It, exitMBB);
12485     exitMBB->splice(exitMBB->begin(), BB,
12486                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12487     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12488 
12489     //  thisMBB:
12490     //   ...
12491     //   fallthrough --> loopMBB
12492     BB->addSuccessor(loop1MBB);
12493 
12494     // loop1MBB:
12495     //   l[bhwd]arx dest, ptr
12496     //   cmp[wd] dest, oldval
12497     //   bne- midMBB
12498     // loop2MBB:
12499     //   st[bhwd]cx. newval, ptr
12500     //   bne- loopMBB
12501     //   b exitBB
12502     // midMBB:
12503     //   st[bhwd]cx. dest, ptr
12504     // exitBB:
12505     BB = loop1MBB;
12506     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
12507     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
12508         .addReg(oldval)
12509         .addReg(dest);
12510     BuildMI(BB, dl, TII->get(PPC::BCC))
12511         .addImm(PPC::PRED_NE)
12512         .addReg(PPC::CR0)
12513         .addMBB(midMBB);
12514     BB->addSuccessor(loop2MBB);
12515     BB->addSuccessor(midMBB);
12516 
12517     BB = loop2MBB;
12518     BuildMI(BB, dl, TII->get(StoreMnemonic))
12519         .addReg(newval)
12520         .addReg(ptrA)
12521         .addReg(ptrB);
12522     BuildMI(BB, dl, TII->get(PPC::BCC))
12523         .addImm(PPC::PRED_NE)
12524         .addReg(PPC::CR0)
12525         .addMBB(loop1MBB);
12526     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12527     BB->addSuccessor(loop1MBB);
12528     BB->addSuccessor(exitMBB);
12529 
12530     BB = midMBB;
12531     BuildMI(BB, dl, TII->get(StoreMnemonic))
12532         .addReg(dest)
12533         .addReg(ptrA)
12534         .addReg(ptrB);
12535     BB->addSuccessor(exitMBB);
12536 
12537     //  exitMBB:
12538     //   ...
12539     BB = exitMBB;
12540   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
12541              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
12542     // We must use 64-bit registers for addresses when targeting 64-bit,
12543     // since we're actually doing arithmetic on them.  Other registers
12544     // can be 32-bit.
12545     bool is64bit = Subtarget.isPPC64();
12546     bool isLittleEndian = Subtarget.isLittleEndian();
12547     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
12548 
12549     Register dest = MI.getOperand(0).getReg();
12550     Register ptrA = MI.getOperand(1).getReg();
12551     Register ptrB = MI.getOperand(2).getReg();
12552     Register oldval = MI.getOperand(3).getReg();
12553     Register newval = MI.getOperand(4).getReg();
12554     DebugLoc dl = MI.getDebugLoc();
12555 
12556     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
12557     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
12558     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
12559     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
12560     F->insert(It, loop1MBB);
12561     F->insert(It, loop2MBB);
12562     F->insert(It, midMBB);
12563     F->insert(It, exitMBB);
12564     exitMBB->splice(exitMBB->begin(), BB,
12565                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
12566     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
12567 
12568     MachineRegisterInfo &RegInfo = F->getRegInfo();
12569     const TargetRegisterClass *RC =
12570         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
12571     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
12572 
12573     Register PtrReg = RegInfo.createVirtualRegister(RC);
12574     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
12575     Register ShiftReg =
12576         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
12577     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
12578     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
12579     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
12580     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
12581     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
12582     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
12583     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
12584     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
12585     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
12586     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
12587     Register Ptr1Reg;
12588     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
12589     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
12590     //  thisMBB:
12591     //   ...
12592     //   fallthrough --> loopMBB
12593     BB->addSuccessor(loop1MBB);
12594 
12595     // The 4-byte load must be aligned, while a char or short may be
12596     // anywhere in the word.  Hence all this nasty bookkeeping code.
12597     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
12598     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
12599     //   xori shift, shift1, 24 [16]
12600     //   rlwinm ptr, ptr1, 0, 0, 29
12601     //   slw newval2, newval, shift
12602     //   slw oldval2, oldval,shift
12603     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
12604     //   slw mask, mask2, shift
12605     //   and newval3, newval2, mask
12606     //   and oldval3, oldval2, mask
12607     // loop1MBB:
12608     //   lwarx tmpDest, ptr
12609     //   and tmp, tmpDest, mask
12610     //   cmpw tmp, oldval3
12611     //   bne- midMBB
12612     // loop2MBB:
12613     //   andc tmp2, tmpDest, mask
12614     //   or tmp4, tmp2, newval3
12615     //   stwcx. tmp4, ptr
12616     //   bne- loop1MBB
12617     //   b exitBB
12618     // midMBB:
12619     //   stwcx. tmpDest, ptr
12620     // exitBB:
12621     //   srw dest, tmpDest, shift
12622     if (ptrA != ZeroReg) {
12623       Ptr1Reg = RegInfo.createVirtualRegister(RC);
12624       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
12625           .addReg(ptrA)
12626           .addReg(ptrB);
12627     } else {
12628       Ptr1Reg = ptrB;
12629     }
12630 
12631     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
12632     // mode.
12633     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
12634         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
12635         .addImm(3)
12636         .addImm(27)
12637         .addImm(is8bit ? 28 : 27);
12638     if (!isLittleEndian)
12639       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
12640           .addReg(Shift1Reg)
12641           .addImm(is8bit ? 24 : 16);
12642     if (is64bit)
12643       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
12644           .addReg(Ptr1Reg)
12645           .addImm(0)
12646           .addImm(61);
12647     else
12648       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
12649           .addReg(Ptr1Reg)
12650           .addImm(0)
12651           .addImm(0)
12652           .addImm(29);
12653     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
12654         .addReg(newval)
12655         .addReg(ShiftReg);
12656     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
12657         .addReg(oldval)
12658         .addReg(ShiftReg);
12659     if (is8bit)
12660       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
12661     else {
12662       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
12663       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
12664           .addReg(Mask3Reg)
12665           .addImm(65535);
12666     }
12667     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
12668         .addReg(Mask2Reg)
12669         .addReg(ShiftReg);
12670     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
12671         .addReg(NewVal2Reg)
12672         .addReg(MaskReg);
12673     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
12674         .addReg(OldVal2Reg)
12675         .addReg(MaskReg);
12676 
12677     BB = loop1MBB;
12678     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
12679         .addReg(ZeroReg)
12680         .addReg(PtrReg);
12681     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
12682         .addReg(TmpDestReg)
12683         .addReg(MaskReg);
12684     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
12685         .addReg(TmpReg)
12686         .addReg(OldVal3Reg);
12687     BuildMI(BB, dl, TII->get(PPC::BCC))
12688         .addImm(PPC::PRED_NE)
12689         .addReg(PPC::CR0)
12690         .addMBB(midMBB);
12691     BB->addSuccessor(loop2MBB);
12692     BB->addSuccessor(midMBB);
12693 
12694     BB = loop2MBB;
12695     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
12696         .addReg(TmpDestReg)
12697         .addReg(MaskReg);
12698     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
12699         .addReg(Tmp2Reg)
12700         .addReg(NewVal3Reg);
12701     BuildMI(BB, dl, TII->get(PPC::STWCX))
12702         .addReg(Tmp4Reg)
12703         .addReg(ZeroReg)
12704         .addReg(PtrReg);
12705     BuildMI(BB, dl, TII->get(PPC::BCC))
12706         .addImm(PPC::PRED_NE)
12707         .addReg(PPC::CR0)
12708         .addMBB(loop1MBB);
12709     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
12710     BB->addSuccessor(loop1MBB);
12711     BB->addSuccessor(exitMBB);
12712 
12713     BB = midMBB;
12714     BuildMI(BB, dl, TII->get(PPC::STWCX))
12715         .addReg(TmpDestReg)
12716         .addReg(ZeroReg)
12717         .addReg(PtrReg);
12718     BB->addSuccessor(exitMBB);
12719 
12720     //  exitMBB:
12721     //   ...
12722     BB = exitMBB;
12723     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12724         .addReg(TmpReg)
12725         .addReg(ShiftReg);
12726   } else if (MI.getOpcode() == PPC::FADDrtz) {
12727     // This pseudo performs an FADD with rounding mode temporarily forced
12728     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12729     // is not modeled at the SelectionDAG level.
12730     Register Dest = MI.getOperand(0).getReg();
12731     Register Src1 = MI.getOperand(1).getReg();
12732     Register Src2 = MI.getOperand(2).getReg();
12733     DebugLoc dl = MI.getDebugLoc();
12734 
12735     MachineRegisterInfo &RegInfo = F->getRegInfo();
12736     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12737 
12738     // Save FPSCR value.
12739     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12740 
12741     // Set rounding mode to round-to-zero.
12742     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12743         .addImm(31)
12744         .addReg(PPC::RM, RegState::ImplicitDefine);
12745 
12746     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12747         .addImm(30)
12748         .addReg(PPC::RM, RegState::ImplicitDefine);
12749 
12750     // Perform addition.
12751     auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
12752                    .addReg(Src1)
12753                    .addReg(Src2);
12754     if (MI.getFlag(MachineInstr::NoFPExcept))
12755       MIB.setMIFlag(MachineInstr::NoFPExcept);
12756 
12757     // Restore FPSCR value.
12758     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12759   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12760              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12761              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12762              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12763     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12764                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12765                           ? PPC::ANDI8_rec
12766                           : PPC::ANDI_rec;
12767     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12768                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12769 
12770     MachineRegisterInfo &RegInfo = F->getRegInfo();
12771     Register Dest = RegInfo.createVirtualRegister(
12772         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12773 
12774     DebugLoc Dl = MI.getDebugLoc();
12775     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12776         .addReg(MI.getOperand(1).getReg())
12777         .addImm(1);
12778     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12779             MI.getOperand(0).getReg())
12780         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12781   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12782     DebugLoc Dl = MI.getDebugLoc();
12783     MachineRegisterInfo &RegInfo = F->getRegInfo();
12784     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12785     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12786     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12787             MI.getOperand(0).getReg())
12788         .addReg(CRReg);
12789   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12790     DebugLoc Dl = MI.getDebugLoc();
12791     unsigned Imm = MI.getOperand(1).getImm();
12792     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12793     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12794             MI.getOperand(0).getReg())
12795         .addReg(PPC::CR0EQ);
12796   } else if (MI.getOpcode() == PPC::SETRNDi) {
12797     DebugLoc dl = MI.getDebugLoc();
12798     Register OldFPSCRReg = MI.getOperand(0).getReg();
12799 
12800     // Save FPSCR value.
12801     if (MRI.use_empty(OldFPSCRReg))
12802       BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12803     else
12804       BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12805 
12806     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12807     // the following settings:
12808     //   00 Round to nearest
12809     //   01 Round to 0
12810     //   10 Round to +inf
12811     //   11 Round to -inf
12812 
12813     // When the operand is immediate, using the two least significant bits of
12814     // the immediate to set the bits 62:63 of FPSCR.
12815     unsigned Mode = MI.getOperand(1).getImm();
12816     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12817         .addImm(31)
12818         .addReg(PPC::RM, RegState::ImplicitDefine);
12819 
12820     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12821         .addImm(30)
12822         .addReg(PPC::RM, RegState::ImplicitDefine);
12823   } else if (MI.getOpcode() == PPC::SETRND) {
12824     DebugLoc dl = MI.getDebugLoc();
12825 
12826     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12827     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12828     // If the target doesn't have DirectMove, we should use stack to do the
12829     // conversion, because the target doesn't have the instructions like mtvsrd
12830     // or mfvsrd to do this conversion directly.
12831     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12832       if (Subtarget.hasDirectMove()) {
12833         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12834           .addReg(SrcReg);
12835       } else {
12836         // Use stack to do the register copy.
12837         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12838         MachineRegisterInfo &RegInfo = F->getRegInfo();
12839         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12840         if (RC == &PPC::F8RCRegClass) {
12841           // Copy register from F8RCRegClass to G8RCRegclass.
12842           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12843                  "Unsupported RegClass.");
12844 
12845           StoreOp = PPC::STFD;
12846           LoadOp = PPC::LD;
12847         } else {
12848           // Copy register from G8RCRegClass to F8RCRegclass.
12849           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12850                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12851                  "Unsupported RegClass.");
12852         }
12853 
12854         MachineFrameInfo &MFI = F->getFrameInfo();
12855         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12856 
12857         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12858             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12859             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12860             MFI.getObjectAlign(FrameIdx));
12861 
12862         // Store the SrcReg into the stack.
12863         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12864           .addReg(SrcReg)
12865           .addImm(0)
12866           .addFrameIndex(FrameIdx)
12867           .addMemOperand(MMOStore);
12868 
12869         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12870             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12871             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12872             MFI.getObjectAlign(FrameIdx));
12873 
12874         // Load from the stack where SrcReg is stored, and save to DestReg,
12875         // so we have done the RegClass conversion from RegClass::SrcReg to
12876         // RegClass::DestReg.
12877         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12878           .addImm(0)
12879           .addFrameIndex(FrameIdx)
12880           .addMemOperand(MMOLoad);
12881       }
12882     };
12883 
12884     Register OldFPSCRReg = MI.getOperand(0).getReg();
12885 
12886     // Save FPSCR value.
12887     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12888 
12889     // When the operand is gprc register, use two least significant bits of the
12890     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12891     //
12892     // copy OldFPSCRTmpReg, OldFPSCRReg
12893     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12894     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12895     // copy NewFPSCRReg, NewFPSCRTmpReg
12896     // mtfsf 255, NewFPSCRReg
12897     MachineOperand SrcOp = MI.getOperand(1);
12898     MachineRegisterInfo &RegInfo = F->getRegInfo();
12899     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12900 
12901     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12902 
12903     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12904     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12905 
12906     // The first operand of INSERT_SUBREG should be a register which has
12907     // subregisters, we only care about its RegClass, so we should use an
12908     // IMPLICIT_DEF register.
12909     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12910     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12911       .addReg(ImDefReg)
12912       .add(SrcOp)
12913       .addImm(1);
12914 
12915     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12916     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12917       .addReg(OldFPSCRTmpReg)
12918       .addReg(ExtSrcReg)
12919       .addImm(0)
12920       .addImm(62);
12921 
12922     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12923     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12924 
12925     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12926     // bits of FPSCR.
12927     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12928       .addImm(255)
12929       .addReg(NewFPSCRReg)
12930       .addImm(0)
12931       .addImm(0);
12932   } else if (MI.getOpcode() == PPC::SETFLM) {
12933     DebugLoc Dl = MI.getDebugLoc();
12934 
12935     // Result of setflm is previous FPSCR content, so we need to save it first.
12936     Register OldFPSCRReg = MI.getOperand(0).getReg();
12937     if (MRI.use_empty(OldFPSCRReg))
12938       BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
12939     else
12940       BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12941 
12942     // Put bits in 32:63 to FPSCR.
12943     Register NewFPSCRReg = MI.getOperand(1).getReg();
12944     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12945         .addImm(255)
12946         .addReg(NewFPSCRReg)
12947         .addImm(0)
12948         .addImm(0);
12949   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12950              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12951     return emitProbedAlloca(MI, BB);
12952   } else if (MI.getOpcode() == PPC::SPLIT_QUADWORD) {
12953     DebugLoc DL = MI.getDebugLoc();
12954     Register Src = MI.getOperand(2).getReg();
12955     Register Lo = MI.getOperand(0).getReg();
12956     Register Hi = MI.getOperand(1).getReg();
12957     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12958         .addDef(Lo)
12959         .addUse(Src, 0, PPC::sub_gp8_x1);
12960     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
12961         .addDef(Hi)
12962         .addUse(Src, 0, PPC::sub_gp8_x0);
12963   } else if (MI.getOpcode() == PPC::LQX_PSEUDO ||
12964              MI.getOpcode() == PPC::STQX_PSEUDO) {
12965     DebugLoc DL = MI.getDebugLoc();
12966     // Ptr is used as the ptr_rc_no_r0 part
12967     // of LQ/STQ's memory operand and adding result of RA and RB,
12968     // so it has to be g8rc_and_g8rc_nox0.
12969     Register Ptr =
12970         F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
12971     Register Val = MI.getOperand(0).getReg();
12972     Register RA = MI.getOperand(1).getReg();
12973     Register RB = MI.getOperand(2).getReg();
12974     BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
12975     BuildMI(*BB, MI, DL,
12976             MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
12977                                               : TII->get(PPC::STQ))
12978         .addReg(Val, MI.getOpcode() == PPC::LQX_PSEUDO ? RegState::Define : 0)
12979         .addImm(0)
12980         .addReg(Ptr);
12981   } else {
12982     llvm_unreachable("Unexpected instr type to insert");
12983   }
12984 
12985   MI.eraseFromParent(); // The pseudo instruction is gone now.
12986   return BB;
12987 }
12988 
12989 //===----------------------------------------------------------------------===//
12990 // Target Optimization Hooks
12991 //===----------------------------------------------------------------------===//
12992 
12993 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12994   // For the estimates, convergence is quadratic, so we essentially double the
12995   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12996   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12997   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12998   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12999   if (VT.getScalarType() == MVT::f64)
13000     RefinementSteps++;
13001   return RefinementSteps;
13002 }
13003 
13004 SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
13005                                             const DenormalMode &Mode) const {
13006   // We only have VSX Vector Test for software Square Root.
13007   EVT VT = Op.getValueType();
13008   if (!isTypeLegal(MVT::i1) ||
13009       (VT != MVT::f64 &&
13010        ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
13011     return TargetLowering::getSqrtInputTest(Op, DAG, Mode);
13012 
13013   SDLoc DL(Op);
13014   // The output register of FTSQRT is CR field.
13015   SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op);
13016   // ftsqrt BF,FRB
13017   // Let e_b be the unbiased exponent of the double-precision
13018   // floating-point operand in register FRB.
13019   // fe_flag is set to 1 if either of the following conditions occurs.
13020   //   - The double-precision floating-point operand in register FRB is a zero,
13021   //     a NaN, or an infinity, or a negative value.
13022   //   - e_b is less than or equal to -970.
13023   // Otherwise fe_flag is set to 0.
13024   // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
13025   // not eligible for iteration. (zero/negative/infinity/nan or unbiased
13026   // exponent is less than -970)
13027   SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
13028   return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
13029                                     FTSQRT, SRIdxVal),
13030                  0);
13031 }
13032 
13033 SDValue
13034 PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
13035                                                SelectionDAG &DAG) const {
13036   // We only have VSX Vector Square Root.
13037   EVT VT = Op.getValueType();
13038   if (VT != MVT::f64 &&
13039       ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
13040     return TargetLowering::getSqrtResultForDenormInput(Op, DAG);
13041 
13042   return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
13043 }
13044 
13045 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
13046                                            int Enabled, int &RefinementSteps,
13047                                            bool &UseOneConstNR,
13048                                            bool Reciprocal) const {
13049   EVT VT = Operand.getValueType();
13050   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
13051       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
13052       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13053       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13054     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13055       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13056 
13057     // The Newton-Raphson computation with a single constant does not provide
13058     // enough accuracy on some CPUs.
13059     UseOneConstNR = !Subtarget.needsTwoConstNR();
13060     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
13061   }
13062   return SDValue();
13063 }
13064 
13065 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
13066                                             int Enabled,
13067                                             int &RefinementSteps) const {
13068   EVT VT = Operand.getValueType();
13069   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
13070       (VT == MVT::f64 && Subtarget.hasFRE()) ||
13071       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
13072       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
13073     if (RefinementSteps == ReciprocalEstimate::Unspecified)
13074       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
13075     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
13076   }
13077   return SDValue();
13078 }
13079 
13080 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
13081   // Note: This functionality is used only when unsafe-fp-math is enabled, and
13082   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
13083   // enabled for division), this functionality is redundant with the default
13084   // combiner logic (once the division -> reciprocal/multiply transformation
13085   // has taken place). As a result, this matters more for older cores than for
13086   // newer ones.
13087 
13088   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
13089   // reciprocal if there are two or more FDIVs (for embedded cores with only
13090   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
13091   switch (Subtarget.getCPUDirective()) {
13092   default:
13093     return 3;
13094   case PPC::DIR_440:
13095   case PPC::DIR_A2:
13096   case PPC::DIR_E500:
13097   case PPC::DIR_E500mc:
13098   case PPC::DIR_E5500:
13099     return 2;
13100   }
13101 }
13102 
13103 // isConsecutiveLSLoc needs to work even if all adds have not yet been
13104 // collapsed, and so we need to look through chains of them.
13105 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
13106                                      int64_t& Offset, SelectionDAG &DAG) {
13107   if (DAG.isBaseWithConstantOffset(Loc)) {
13108     Base = Loc.getOperand(0);
13109     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
13110 
13111     // The base might itself be a base plus an offset, and if so, accumulate
13112     // that as well.
13113     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
13114   }
13115 }
13116 
13117 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
13118                             unsigned Bytes, int Dist,
13119                             SelectionDAG &DAG) {
13120   if (VT.getSizeInBits() / 8 != Bytes)
13121     return false;
13122 
13123   SDValue BaseLoc = Base->getBasePtr();
13124   if (Loc.getOpcode() == ISD::FrameIndex) {
13125     if (BaseLoc.getOpcode() != ISD::FrameIndex)
13126       return false;
13127     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
13128     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
13129     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
13130     int FS  = MFI.getObjectSize(FI);
13131     int BFS = MFI.getObjectSize(BFI);
13132     if (FS != BFS || FS != (int)Bytes) return false;
13133     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
13134   }
13135 
13136   SDValue Base1 = Loc, Base2 = BaseLoc;
13137   int64_t Offset1 = 0, Offset2 = 0;
13138   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
13139   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
13140   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
13141     return true;
13142 
13143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13144   const GlobalValue *GV1 = nullptr;
13145   const GlobalValue *GV2 = nullptr;
13146   Offset1 = 0;
13147   Offset2 = 0;
13148   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
13149   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
13150   if (isGA1 && isGA2 && GV1 == GV2)
13151     return Offset1 == (Offset2 + Dist*Bytes);
13152   return false;
13153 }
13154 
13155 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
13156 // not enforce equality of the chain operands.
13157 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
13158                             unsigned Bytes, int Dist,
13159                             SelectionDAG &DAG) {
13160   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
13161     EVT VT = LS->getMemoryVT();
13162     SDValue Loc = LS->getBasePtr();
13163     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
13164   }
13165 
13166   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
13167     EVT VT;
13168     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13169     default: return false;
13170     case Intrinsic::ppc_altivec_lvx:
13171     case Intrinsic::ppc_altivec_lvxl:
13172     case Intrinsic::ppc_vsx_lxvw4x:
13173     case Intrinsic::ppc_vsx_lxvw4x_be:
13174       VT = MVT::v4i32;
13175       break;
13176     case Intrinsic::ppc_vsx_lxvd2x:
13177     case Intrinsic::ppc_vsx_lxvd2x_be:
13178       VT = MVT::v2f64;
13179       break;
13180     case Intrinsic::ppc_altivec_lvebx:
13181       VT = MVT::i8;
13182       break;
13183     case Intrinsic::ppc_altivec_lvehx:
13184       VT = MVT::i16;
13185       break;
13186     case Intrinsic::ppc_altivec_lvewx:
13187       VT = MVT::i32;
13188       break;
13189     }
13190 
13191     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
13192   }
13193 
13194   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
13195     EVT VT;
13196     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
13197     default: return false;
13198     case Intrinsic::ppc_altivec_stvx:
13199     case Intrinsic::ppc_altivec_stvxl:
13200     case Intrinsic::ppc_vsx_stxvw4x:
13201       VT = MVT::v4i32;
13202       break;
13203     case Intrinsic::ppc_vsx_stxvd2x:
13204       VT = MVT::v2f64;
13205       break;
13206     case Intrinsic::ppc_vsx_stxvw4x_be:
13207       VT = MVT::v4i32;
13208       break;
13209     case Intrinsic::ppc_vsx_stxvd2x_be:
13210       VT = MVT::v2f64;
13211       break;
13212     case Intrinsic::ppc_altivec_stvebx:
13213       VT = MVT::i8;
13214       break;
13215     case Intrinsic::ppc_altivec_stvehx:
13216       VT = MVT::i16;
13217       break;
13218     case Intrinsic::ppc_altivec_stvewx:
13219       VT = MVT::i32;
13220       break;
13221     }
13222 
13223     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
13224   }
13225 
13226   return false;
13227 }
13228 
13229 // Return true is there is a nearyby consecutive load to the one provided
13230 // (regardless of alignment). We search up and down the chain, looking though
13231 // token factors and other loads (but nothing else). As a result, a true result
13232 // indicates that it is safe to create a new consecutive load adjacent to the
13233 // load provided.
13234 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
13235   SDValue Chain = LD->getChain();
13236   EVT VT = LD->getMemoryVT();
13237 
13238   SmallSet<SDNode *, 16> LoadRoots;
13239   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
13240   SmallSet<SDNode *, 16> Visited;
13241 
13242   // First, search up the chain, branching to follow all token-factor operands.
13243   // If we find a consecutive load, then we're done, otherwise, record all
13244   // nodes just above the top-level loads and token factors.
13245   while (!Queue.empty()) {
13246     SDNode *ChainNext = Queue.pop_back_val();
13247     if (!Visited.insert(ChainNext).second)
13248       continue;
13249 
13250     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
13251       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13252         return true;
13253 
13254       if (!Visited.count(ChainLD->getChain().getNode()))
13255         Queue.push_back(ChainLD->getChain().getNode());
13256     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
13257       for (const SDUse &O : ChainNext->ops())
13258         if (!Visited.count(O.getNode()))
13259           Queue.push_back(O.getNode());
13260     } else
13261       LoadRoots.insert(ChainNext);
13262   }
13263 
13264   // Second, search down the chain, starting from the top-level nodes recorded
13265   // in the first phase. These top-level nodes are the nodes just above all
13266   // loads and token factors. Starting with their uses, recursively look though
13267   // all loads (just the chain uses) and token factors to find a consecutive
13268   // load.
13269   Visited.clear();
13270   Queue.clear();
13271 
13272   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
13273        IE = LoadRoots.end(); I != IE; ++I) {
13274     Queue.push_back(*I);
13275 
13276     while (!Queue.empty()) {
13277       SDNode *LoadRoot = Queue.pop_back_val();
13278       if (!Visited.insert(LoadRoot).second)
13279         continue;
13280 
13281       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
13282         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
13283           return true;
13284 
13285       for (SDNode *U : LoadRoot->uses())
13286         if (((isa<MemSDNode>(U) &&
13287               cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
13288              U->getOpcode() == ISD::TokenFactor) &&
13289             !Visited.count(U))
13290           Queue.push_back(U);
13291     }
13292   }
13293 
13294   return false;
13295 }
13296 
13297 /// This function is called when we have proved that a SETCC node can be replaced
13298 /// by subtraction (and other supporting instructions) so that the result of
13299 /// comparison is kept in a GPR instead of CR. This function is purely for
13300 /// codegen purposes and has some flags to guide the codegen process.
13301 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
13302                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
13303   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13304 
13305   // Zero extend the operands to the largest legal integer. Originally, they
13306   // must be of a strictly smaller size.
13307   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
13308                          DAG.getConstant(Size, DL, MVT::i32));
13309   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
13310                          DAG.getConstant(Size, DL, MVT::i32));
13311 
13312   // Swap if needed. Depends on the condition code.
13313   if (Swap)
13314     std::swap(Op0, Op1);
13315 
13316   // Subtract extended integers.
13317   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
13318 
13319   // Move the sign bit to the least significant position and zero out the rest.
13320   // Now the least significant bit carries the result of original comparison.
13321   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
13322                              DAG.getConstant(Size - 1, DL, MVT::i32));
13323   auto Final = Shifted;
13324 
13325   // Complement the result if needed. Based on the condition code.
13326   if (Complement)
13327     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
13328                         DAG.getConstant(1, DL, MVT::i64));
13329 
13330   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
13331 }
13332 
13333 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
13334                                                   DAGCombinerInfo &DCI) const {
13335   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
13336 
13337   SelectionDAG &DAG = DCI.DAG;
13338   SDLoc DL(N);
13339 
13340   // Size of integers being compared has a critical role in the following
13341   // analysis, so we prefer to do this when all types are legal.
13342   if (!DCI.isAfterLegalizeDAG())
13343     return SDValue();
13344 
13345   // If all users of SETCC extend its value to a legal integer type
13346   // then we replace SETCC with a subtraction
13347   for (const SDNode *U : N->uses())
13348     if (U->getOpcode() != ISD::ZERO_EXTEND)
13349       return SDValue();
13350 
13351   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13352   auto OpSize = N->getOperand(0).getValueSizeInBits();
13353 
13354   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
13355 
13356   if (OpSize < Size) {
13357     switch (CC) {
13358     default: break;
13359     case ISD::SETULT:
13360       return generateEquivalentSub(N, Size, false, false, DL, DAG);
13361     case ISD::SETULE:
13362       return generateEquivalentSub(N, Size, true, true, DL, DAG);
13363     case ISD::SETUGT:
13364       return generateEquivalentSub(N, Size, false, true, DL, DAG);
13365     case ISD::SETUGE:
13366       return generateEquivalentSub(N, Size, true, false, DL, DAG);
13367     }
13368   }
13369 
13370   return SDValue();
13371 }
13372 
13373 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
13374                                                   DAGCombinerInfo &DCI) const {
13375   SelectionDAG &DAG = DCI.DAG;
13376   SDLoc dl(N);
13377 
13378   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
13379   // If we're tracking CR bits, we need to be careful that we don't have:
13380   //   trunc(binary-ops(zext(x), zext(y)))
13381   // or
13382   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
13383   // such that we're unnecessarily moving things into GPRs when it would be
13384   // better to keep them in CR bits.
13385 
13386   // Note that trunc here can be an actual i1 trunc, or can be the effective
13387   // truncation that comes from a setcc or select_cc.
13388   if (N->getOpcode() == ISD::TRUNCATE &&
13389       N->getValueType(0) != MVT::i1)
13390     return SDValue();
13391 
13392   if (N->getOperand(0).getValueType() != MVT::i32 &&
13393       N->getOperand(0).getValueType() != MVT::i64)
13394     return SDValue();
13395 
13396   if (N->getOpcode() == ISD::SETCC ||
13397       N->getOpcode() == ISD::SELECT_CC) {
13398     // If we're looking at a comparison, then we need to make sure that the
13399     // high bits (all except for the first) don't matter the result.
13400     ISD::CondCode CC =
13401       cast<CondCodeSDNode>(N->getOperand(
13402         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
13403     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
13404 
13405     if (ISD::isSignedIntSetCC(CC)) {
13406       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
13407           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
13408         return SDValue();
13409     } else if (ISD::isUnsignedIntSetCC(CC)) {
13410       if (!DAG.MaskedValueIsZero(N->getOperand(0),
13411                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
13412           !DAG.MaskedValueIsZero(N->getOperand(1),
13413                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
13414         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
13415                                              : SDValue());
13416     } else {
13417       // This is neither a signed nor an unsigned comparison, just make sure
13418       // that the high bits are equal.
13419       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
13420       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
13421 
13422       // We don't really care about what is known about the first bit (if
13423       // anything), so pretend that it is known zero for both to ensure they can
13424       // be compared as constants.
13425       Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
13426       Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
13427 
13428       if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
13429           Op1Known.getConstant() != Op2Known.getConstant())
13430         return SDValue();
13431     }
13432   }
13433 
13434   // We now know that the higher-order bits are irrelevant, we just need to
13435   // make sure that all of the intermediate operations are bit operations, and
13436   // all inputs are extensions.
13437   if (N->getOperand(0).getOpcode() != ISD::AND &&
13438       N->getOperand(0).getOpcode() != ISD::OR  &&
13439       N->getOperand(0).getOpcode() != ISD::XOR &&
13440       N->getOperand(0).getOpcode() != ISD::SELECT &&
13441       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
13442       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
13443       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
13444       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
13445       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
13446     return SDValue();
13447 
13448   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
13449       N->getOperand(1).getOpcode() != ISD::AND &&
13450       N->getOperand(1).getOpcode() != ISD::OR  &&
13451       N->getOperand(1).getOpcode() != ISD::XOR &&
13452       N->getOperand(1).getOpcode() != ISD::SELECT &&
13453       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
13454       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
13455       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
13456       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
13457       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
13458     return SDValue();
13459 
13460   SmallVector<SDValue, 4> Inputs;
13461   SmallVector<SDValue, 8> BinOps, PromOps;
13462   SmallPtrSet<SDNode *, 16> Visited;
13463 
13464   for (unsigned i = 0; i < 2; ++i) {
13465     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13466           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13467           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13468           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13469         isa<ConstantSDNode>(N->getOperand(i)))
13470       Inputs.push_back(N->getOperand(i));
13471     else
13472       BinOps.push_back(N->getOperand(i));
13473 
13474     if (N->getOpcode() == ISD::TRUNCATE)
13475       break;
13476   }
13477 
13478   // Visit all inputs, collect all binary operations (and, or, xor and
13479   // select) that are all fed by extensions.
13480   while (!BinOps.empty()) {
13481     SDValue BinOp = BinOps.pop_back_val();
13482 
13483     if (!Visited.insert(BinOp.getNode()).second)
13484       continue;
13485 
13486     PromOps.push_back(BinOp);
13487 
13488     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13489       // The condition of the select is not promoted.
13490       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13491         continue;
13492       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13493         continue;
13494 
13495       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13496             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13497             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
13498            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
13499           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13500         Inputs.push_back(BinOp.getOperand(i));
13501       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13502                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13503                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13504                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13505                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
13506                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13507                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
13508                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
13509                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
13510         BinOps.push_back(BinOp.getOperand(i));
13511       } else {
13512         // We have an input that is not an extension or another binary
13513         // operation; we'll abort this transformation.
13514         return SDValue();
13515       }
13516     }
13517   }
13518 
13519   // Make sure that this is a self-contained cluster of operations (which
13520   // is not quite the same thing as saying that everything has only one
13521   // use).
13522   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13523     if (isa<ConstantSDNode>(Inputs[i]))
13524       continue;
13525 
13526     for (const SDNode *User : Inputs[i].getNode()->uses()) {
13527       if (User != N && !Visited.count(User))
13528         return SDValue();
13529 
13530       // Make sure that we're not going to promote the non-output-value
13531       // operand(s) or SELECT or SELECT_CC.
13532       // FIXME: Although we could sometimes handle this, and it does occur in
13533       // practice that one of the condition inputs to the select is also one of
13534       // the outputs, we currently can't deal with this.
13535       if (User->getOpcode() == ISD::SELECT) {
13536         if (User->getOperand(0) == Inputs[i])
13537           return SDValue();
13538       } else if (User->getOpcode() == ISD::SELECT_CC) {
13539         if (User->getOperand(0) == Inputs[i] ||
13540             User->getOperand(1) == Inputs[i])
13541           return SDValue();
13542       }
13543     }
13544   }
13545 
13546   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13547     for (const SDNode *User : PromOps[i].getNode()->uses()) {
13548       if (User != N && !Visited.count(User))
13549         return SDValue();
13550 
13551       // Make sure that we're not going to promote the non-output-value
13552       // operand(s) or SELECT or SELECT_CC.
13553       // FIXME: Although we could sometimes handle this, and it does occur in
13554       // practice that one of the condition inputs to the select is also one of
13555       // the outputs, we currently can't deal with this.
13556       if (User->getOpcode() == ISD::SELECT) {
13557         if (User->getOperand(0) == PromOps[i])
13558           return SDValue();
13559       } else if (User->getOpcode() == ISD::SELECT_CC) {
13560         if (User->getOperand(0) == PromOps[i] ||
13561             User->getOperand(1) == PromOps[i])
13562           return SDValue();
13563       }
13564     }
13565   }
13566 
13567   // Replace all inputs with the extension operand.
13568   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13569     // Constants may have users outside the cluster of to-be-promoted nodes,
13570     // and so we need to replace those as we do the promotions.
13571     if (isa<ConstantSDNode>(Inputs[i]))
13572       continue;
13573     else
13574       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
13575   }
13576 
13577   std::list<HandleSDNode> PromOpHandles;
13578   for (auto &PromOp : PromOps)
13579     PromOpHandles.emplace_back(PromOp);
13580 
13581   // Replace all operations (these are all the same, but have a different
13582   // (i1) return type). DAG.getNode will validate that the types of
13583   // a binary operator match, so go through the list in reverse so that
13584   // we've likely promoted both operands first. Any intermediate truncations or
13585   // extensions disappear.
13586   while (!PromOpHandles.empty()) {
13587     SDValue PromOp = PromOpHandles.back().getValue();
13588     PromOpHandles.pop_back();
13589 
13590     if (PromOp.getOpcode() == ISD::TRUNCATE ||
13591         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
13592         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
13593         PromOp.getOpcode() == ISD::ANY_EXTEND) {
13594       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
13595           PromOp.getOperand(0).getValueType() != MVT::i1) {
13596         // The operand is not yet ready (see comment below).
13597         PromOpHandles.emplace_front(PromOp);
13598         continue;
13599       }
13600 
13601       SDValue RepValue = PromOp.getOperand(0);
13602       if (isa<ConstantSDNode>(RepValue))
13603         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
13604 
13605       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
13606       continue;
13607     }
13608 
13609     unsigned C;
13610     switch (PromOp.getOpcode()) {
13611     default:             C = 0; break;
13612     case ISD::SELECT:    C = 1; break;
13613     case ISD::SELECT_CC: C = 2; break;
13614     }
13615 
13616     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13617          PromOp.getOperand(C).getValueType() != MVT::i1) ||
13618         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13619          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
13620       // The to-be-promoted operands of this node have not yet been
13621       // promoted (this should be rare because we're going through the
13622       // list backward, but if one of the operands has several users in
13623       // this cluster of to-be-promoted nodes, it is possible).
13624       PromOpHandles.emplace_front(PromOp);
13625       continue;
13626     }
13627 
13628     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13629                                 PromOp.getNode()->op_end());
13630 
13631     // If there are any constant inputs, make sure they're replaced now.
13632     for (unsigned i = 0; i < 2; ++i)
13633       if (isa<ConstantSDNode>(Ops[C+i]))
13634         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
13635 
13636     DAG.ReplaceAllUsesOfValueWith(PromOp,
13637       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
13638   }
13639 
13640   // Now we're left with the initial truncation itself.
13641   if (N->getOpcode() == ISD::TRUNCATE)
13642     return N->getOperand(0);
13643 
13644   // Otherwise, this is a comparison. The operands to be compared have just
13645   // changed type (to i1), but everything else is the same.
13646   return SDValue(N, 0);
13647 }
13648 
13649 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
13650                                                   DAGCombinerInfo &DCI) const {
13651   SelectionDAG &DAG = DCI.DAG;
13652   SDLoc dl(N);
13653 
13654   // If we're tracking CR bits, we need to be careful that we don't have:
13655   //   zext(binary-ops(trunc(x), trunc(y)))
13656   // or
13657   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
13658   // such that we're unnecessarily moving things into CR bits that can more
13659   // efficiently stay in GPRs. Note that if we're not certain that the high
13660   // bits are set as required by the final extension, we still may need to do
13661   // some masking to get the proper behavior.
13662 
13663   // This same functionality is important on PPC64 when dealing with
13664   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
13665   // the return values of functions. Because it is so similar, it is handled
13666   // here as well.
13667 
13668   if (N->getValueType(0) != MVT::i32 &&
13669       N->getValueType(0) != MVT::i64)
13670     return SDValue();
13671 
13672   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
13673         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
13674     return SDValue();
13675 
13676   if (N->getOperand(0).getOpcode() != ISD::AND &&
13677       N->getOperand(0).getOpcode() != ISD::OR  &&
13678       N->getOperand(0).getOpcode() != ISD::XOR &&
13679       N->getOperand(0).getOpcode() != ISD::SELECT &&
13680       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
13681     return SDValue();
13682 
13683   SmallVector<SDValue, 4> Inputs;
13684   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
13685   SmallPtrSet<SDNode *, 16> Visited;
13686 
13687   // Visit all inputs, collect all binary operations (and, or, xor and
13688   // select) that are all fed by truncations.
13689   while (!BinOps.empty()) {
13690     SDValue BinOp = BinOps.pop_back_val();
13691 
13692     if (!Visited.insert(BinOp.getNode()).second)
13693       continue;
13694 
13695     PromOps.push_back(BinOp);
13696 
13697     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
13698       // The condition of the select is not promoted.
13699       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
13700         continue;
13701       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
13702         continue;
13703 
13704       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
13705           isa<ConstantSDNode>(BinOp.getOperand(i))) {
13706         Inputs.push_back(BinOp.getOperand(i));
13707       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
13708                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
13709                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
13710                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
13711                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
13712         BinOps.push_back(BinOp.getOperand(i));
13713       } else {
13714         // We have an input that is not a truncation or another binary
13715         // operation; we'll abort this transformation.
13716         return SDValue();
13717       }
13718     }
13719   }
13720 
13721   // The operands of a select that must be truncated when the select is
13722   // promoted because the operand is actually part of the to-be-promoted set.
13723   DenseMap<SDNode *, EVT> SelectTruncOp[2];
13724 
13725   // Make sure that this is a self-contained cluster of operations (which
13726   // is not quite the same thing as saying that everything has only one
13727   // use).
13728   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13729     if (isa<ConstantSDNode>(Inputs[i]))
13730       continue;
13731 
13732     for (SDNode *User : Inputs[i].getNode()->uses()) {
13733       if (User != N && !Visited.count(User))
13734         return SDValue();
13735 
13736       // If we're going to promote the non-output-value operand(s) or SELECT or
13737       // SELECT_CC, record them for truncation.
13738       if (User->getOpcode() == ISD::SELECT) {
13739         if (User->getOperand(0) == Inputs[i])
13740           SelectTruncOp[0].insert(std::make_pair(User,
13741                                     User->getOperand(0).getValueType()));
13742       } else if (User->getOpcode() == ISD::SELECT_CC) {
13743         if (User->getOperand(0) == Inputs[i])
13744           SelectTruncOp[0].insert(std::make_pair(User,
13745                                     User->getOperand(0).getValueType()));
13746         if (User->getOperand(1) == Inputs[i])
13747           SelectTruncOp[1].insert(std::make_pair(User,
13748                                     User->getOperand(1).getValueType()));
13749       }
13750     }
13751   }
13752 
13753   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
13754     for (SDNode *User : PromOps[i].getNode()->uses()) {
13755       if (User != N && !Visited.count(User))
13756         return SDValue();
13757 
13758       // If we're going to promote the non-output-value operand(s) or SELECT or
13759       // SELECT_CC, record them for truncation.
13760       if (User->getOpcode() == ISD::SELECT) {
13761         if (User->getOperand(0) == PromOps[i])
13762           SelectTruncOp[0].insert(std::make_pair(User,
13763                                     User->getOperand(0).getValueType()));
13764       } else if (User->getOpcode() == ISD::SELECT_CC) {
13765         if (User->getOperand(0) == PromOps[i])
13766           SelectTruncOp[0].insert(std::make_pair(User,
13767                                     User->getOperand(0).getValueType()));
13768         if (User->getOperand(1) == PromOps[i])
13769           SelectTruncOp[1].insert(std::make_pair(User,
13770                                     User->getOperand(1).getValueType()));
13771       }
13772     }
13773   }
13774 
13775   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
13776   bool ReallyNeedsExt = false;
13777   if (N->getOpcode() != ISD::ANY_EXTEND) {
13778     // If all of the inputs are not already sign/zero extended, then
13779     // we'll still need to do that at the end.
13780     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13781       if (isa<ConstantSDNode>(Inputs[i]))
13782         continue;
13783 
13784       unsigned OpBits =
13785         Inputs[i].getOperand(0).getValueSizeInBits();
13786       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
13787 
13788       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
13789            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13790                                   APInt::getHighBitsSet(OpBits,
13791                                                         OpBits-PromBits))) ||
13792           (N->getOpcode() == ISD::SIGN_EXTEND &&
13793            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13794              (OpBits-(PromBits-1)))) {
13795         ReallyNeedsExt = true;
13796         break;
13797       }
13798     }
13799   }
13800 
13801   // Replace all inputs, either with the truncation operand, or a
13802   // truncation or extension to the final output type.
13803   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13804     // Constant inputs need to be replaced with the to-be-promoted nodes that
13805     // use them because they might have users outside of the cluster of
13806     // promoted nodes.
13807     if (isa<ConstantSDNode>(Inputs[i]))
13808       continue;
13809 
13810     SDValue InSrc = Inputs[i].getOperand(0);
13811     if (Inputs[i].getValueType() == N->getValueType(0))
13812       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13813     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13814       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13815         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13816     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13817       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13818         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13819     else
13820       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13821         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13822   }
13823 
13824   std::list<HandleSDNode> PromOpHandles;
13825   for (auto &PromOp : PromOps)
13826     PromOpHandles.emplace_back(PromOp);
13827 
13828   // Replace all operations (these are all the same, but have a different
13829   // (promoted) return type). DAG.getNode will validate that the types of
13830   // a binary operator match, so go through the list in reverse so that
13831   // we've likely promoted both operands first.
13832   while (!PromOpHandles.empty()) {
13833     SDValue PromOp = PromOpHandles.back().getValue();
13834     PromOpHandles.pop_back();
13835 
13836     unsigned C;
13837     switch (PromOp.getOpcode()) {
13838     default:             C = 0; break;
13839     case ISD::SELECT:    C = 1; break;
13840     case ISD::SELECT_CC: C = 2; break;
13841     }
13842 
13843     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13844          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13845         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13846          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13847       // The to-be-promoted operands of this node have not yet been
13848       // promoted (this should be rare because we're going through the
13849       // list backward, but if one of the operands has several users in
13850       // this cluster of to-be-promoted nodes, it is possible).
13851       PromOpHandles.emplace_front(PromOp);
13852       continue;
13853     }
13854 
13855     // For SELECT and SELECT_CC nodes, we do a similar check for any
13856     // to-be-promoted comparison inputs.
13857     if (PromOp.getOpcode() == ISD::SELECT ||
13858         PromOp.getOpcode() == ISD::SELECT_CC) {
13859       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13860            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13861           (SelectTruncOp[1].count(PromOp.getNode()) &&
13862            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13863         PromOpHandles.emplace_front(PromOp);
13864         continue;
13865       }
13866     }
13867 
13868     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13869                                 PromOp.getNode()->op_end());
13870 
13871     // If this node has constant inputs, then they'll need to be promoted here.
13872     for (unsigned i = 0; i < 2; ++i) {
13873       if (!isa<ConstantSDNode>(Ops[C+i]))
13874         continue;
13875       if (Ops[C+i].getValueType() == N->getValueType(0))
13876         continue;
13877 
13878       if (N->getOpcode() == ISD::SIGN_EXTEND)
13879         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13880       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13881         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13882       else
13883         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13884     }
13885 
13886     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13887     // truncate them again to the original value type.
13888     if (PromOp.getOpcode() == ISD::SELECT ||
13889         PromOp.getOpcode() == ISD::SELECT_CC) {
13890       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13891       if (SI0 != SelectTruncOp[0].end())
13892         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13893       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13894       if (SI1 != SelectTruncOp[1].end())
13895         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13896     }
13897 
13898     DAG.ReplaceAllUsesOfValueWith(PromOp,
13899       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13900   }
13901 
13902   // Now we're left with the initial extension itself.
13903   if (!ReallyNeedsExt)
13904     return N->getOperand(0);
13905 
13906   // To zero extend, just mask off everything except for the first bit (in the
13907   // i1 case).
13908   if (N->getOpcode() == ISD::ZERO_EXTEND)
13909     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13910                        DAG.getConstant(APInt::getLowBitsSet(
13911                                          N->getValueSizeInBits(0), PromBits),
13912                                        dl, N->getValueType(0)));
13913 
13914   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13915          "Invalid extension type");
13916   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13917   SDValue ShiftCst =
13918       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13919   return DAG.getNode(
13920       ISD::SRA, dl, N->getValueType(0),
13921       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13922       ShiftCst);
13923 }
13924 
13925 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13926                                         DAGCombinerInfo &DCI) const {
13927   assert(N->getOpcode() == ISD::SETCC &&
13928          "Should be called with a SETCC node");
13929 
13930   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13931   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13932     SDValue LHS = N->getOperand(0);
13933     SDValue RHS = N->getOperand(1);
13934 
13935     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13936     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13937         LHS.hasOneUse())
13938       std::swap(LHS, RHS);
13939 
13940     // x == 0-y --> x+y == 0
13941     // x != 0-y --> x+y != 0
13942     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13943         RHS.hasOneUse()) {
13944       SDLoc DL(N);
13945       SelectionDAG &DAG = DCI.DAG;
13946       EVT VT = N->getValueType(0);
13947       EVT OpVT = LHS.getValueType();
13948       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13949       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13950     }
13951   }
13952 
13953   return DAGCombineTruncBoolExt(N, DCI);
13954 }
13955 
13956 // Is this an extending load from an f32 to an f64?
13957 static bool isFPExtLoad(SDValue Op) {
13958   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13959     return LD->getExtensionType() == ISD::EXTLOAD &&
13960       Op.getValueType() == MVT::f64;
13961   return false;
13962 }
13963 
13964 /// Reduces the number of fp-to-int conversion when building a vector.
13965 ///
13966 /// If this vector is built out of floating to integer conversions,
13967 /// transform it to a vector built out of floating point values followed by a
13968 /// single floating to integer conversion of the vector.
13969 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13970 /// becomes (fptosi (build_vector ($A, $B, ...)))
13971 SDValue PPCTargetLowering::
13972 combineElementTruncationToVectorTruncation(SDNode *N,
13973                                            DAGCombinerInfo &DCI) const {
13974   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13975          "Should be called with a BUILD_VECTOR node");
13976 
13977   SelectionDAG &DAG = DCI.DAG;
13978   SDLoc dl(N);
13979 
13980   SDValue FirstInput = N->getOperand(0);
13981   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13982          "The input operand must be an fp-to-int conversion.");
13983 
13984   // This combine happens after legalization so the fp_to_[su]i nodes are
13985   // already converted to PPCSISD nodes.
13986   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13987   if (FirstConversion == PPCISD::FCTIDZ ||
13988       FirstConversion == PPCISD::FCTIDUZ ||
13989       FirstConversion == PPCISD::FCTIWZ ||
13990       FirstConversion == PPCISD::FCTIWUZ) {
13991     bool IsSplat = true;
13992     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13993       FirstConversion == PPCISD::FCTIWUZ;
13994     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13995     SmallVector<SDValue, 4> Ops;
13996     EVT TargetVT = N->getValueType(0);
13997     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13998       SDValue NextOp = N->getOperand(i);
13999       if (NextOp.getOpcode() != PPCISD::MFVSR)
14000         return SDValue();
14001       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
14002       if (NextConversion != FirstConversion)
14003         return SDValue();
14004       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
14005       // This is not valid if the input was originally double precision. It is
14006       // also not profitable to do unless this is an extending load in which
14007       // case doing this combine will allow us to combine consecutive loads.
14008       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
14009         return SDValue();
14010       if (N->getOperand(i) != FirstInput)
14011         IsSplat = false;
14012     }
14013 
14014     // If this is a splat, we leave it as-is since there will be only a single
14015     // fp-to-int conversion followed by a splat of the integer. This is better
14016     // for 32-bit and smaller ints and neutral for 64-bit ints.
14017     if (IsSplat)
14018       return SDValue();
14019 
14020     // Now that we know we have the right type of node, get its operands
14021     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
14022       SDValue In = N->getOperand(i).getOperand(0);
14023       if (Is32Bit) {
14024         // For 32-bit values, we need to add an FP_ROUND node (if we made it
14025         // here, we know that all inputs are extending loads so this is safe).
14026         if (In.isUndef())
14027           Ops.push_back(DAG.getUNDEF(SrcVT));
14028         else {
14029           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
14030                                       MVT::f32, In.getOperand(0),
14031                                       DAG.getIntPtrConstant(1, dl));
14032           Ops.push_back(Trunc);
14033         }
14034       } else
14035         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
14036     }
14037 
14038     unsigned Opcode;
14039     if (FirstConversion == PPCISD::FCTIDZ ||
14040         FirstConversion == PPCISD::FCTIWZ)
14041       Opcode = ISD::FP_TO_SINT;
14042     else
14043       Opcode = ISD::FP_TO_UINT;
14044 
14045     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
14046     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
14047     return DAG.getNode(Opcode, dl, TargetVT, BV);
14048   }
14049   return SDValue();
14050 }
14051 
14052 /// Reduce the number of loads when building a vector.
14053 ///
14054 /// Building a vector out of multiple loads can be converted to a load
14055 /// of the vector type if the loads are consecutive. If the loads are
14056 /// consecutive but in descending order, a shuffle is added at the end
14057 /// to reorder the vector.
14058 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
14059   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14060          "Should be called with a BUILD_VECTOR node");
14061 
14062   SDLoc dl(N);
14063 
14064   // Return early for non byte-sized type, as they can't be consecutive.
14065   if (!N->getValueType(0).getVectorElementType().isByteSized())
14066     return SDValue();
14067 
14068   bool InputsAreConsecutiveLoads = true;
14069   bool InputsAreReverseConsecutive = true;
14070   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
14071   SDValue FirstInput = N->getOperand(0);
14072   bool IsRoundOfExtLoad = false;
14073 
14074   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
14075       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
14076     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
14077     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
14078   }
14079   // Not a build vector of (possibly fp_rounded) loads.
14080   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
14081       N->getNumOperands() == 1)
14082     return SDValue();
14083 
14084   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
14085     // If any inputs are fp_round(extload), they all must be.
14086     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
14087       return SDValue();
14088 
14089     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
14090       N->getOperand(i);
14091     if (NextInput.getOpcode() != ISD::LOAD)
14092       return SDValue();
14093 
14094     SDValue PreviousInput =
14095       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
14096     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
14097     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
14098 
14099     // If any inputs are fp_round(extload), they all must be.
14100     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
14101       return SDValue();
14102 
14103     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
14104       InputsAreConsecutiveLoads = false;
14105     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
14106       InputsAreReverseConsecutive = false;
14107 
14108     // Exit early if the loads are neither consecutive nor reverse consecutive.
14109     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
14110       return SDValue();
14111   }
14112 
14113   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
14114          "The loads cannot be both consecutive and reverse consecutive.");
14115 
14116   SDValue FirstLoadOp =
14117     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
14118   SDValue LastLoadOp =
14119     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
14120                        N->getOperand(N->getNumOperands()-1);
14121 
14122   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
14123   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
14124   if (InputsAreConsecutiveLoads) {
14125     assert(LD1 && "Input needs to be a LoadSDNode.");
14126     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
14127                        LD1->getBasePtr(), LD1->getPointerInfo(),
14128                        LD1->getAlignment());
14129   }
14130   if (InputsAreReverseConsecutive) {
14131     assert(LDL && "Input needs to be a LoadSDNode.");
14132     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
14133                                LDL->getBasePtr(), LDL->getPointerInfo(),
14134                                LDL->getAlignment());
14135     SmallVector<int, 16> Ops;
14136     for (int i = N->getNumOperands() - 1; i >= 0; i--)
14137       Ops.push_back(i);
14138 
14139     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
14140                                 DAG.getUNDEF(N->getValueType(0)), Ops);
14141   }
14142   return SDValue();
14143 }
14144 
14145 // This function adds the required vector_shuffle needed to get
14146 // the elements of the vector extract in the correct position
14147 // as specified by the CorrectElems encoding.
14148 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
14149                                       SDValue Input, uint64_t Elems,
14150                                       uint64_t CorrectElems) {
14151   SDLoc dl(N);
14152 
14153   unsigned NumElems = Input.getValueType().getVectorNumElements();
14154   SmallVector<int, 16> ShuffleMask(NumElems, -1);
14155 
14156   // Knowing the element indices being extracted from the original
14157   // vector and the order in which they're being inserted, just put
14158   // them at element indices required for the instruction.
14159   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14160     if (DAG.getDataLayout().isLittleEndian())
14161       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
14162     else
14163       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
14164     CorrectElems = CorrectElems >> 8;
14165     Elems = Elems >> 8;
14166   }
14167 
14168   SDValue Shuffle =
14169       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
14170                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
14171 
14172   EVT VT = N->getValueType(0);
14173   SDValue Conv = DAG.getBitcast(VT, Shuffle);
14174 
14175   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
14176                                Input.getValueType().getVectorElementType(),
14177                                VT.getVectorNumElements());
14178   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
14179                      DAG.getValueType(ExtVT));
14180 }
14181 
14182 // Look for build vector patterns where input operands come from sign
14183 // extended vector_extract elements of specific indices. If the correct indices
14184 // aren't used, add a vector shuffle to fix up the indices and create
14185 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
14186 // during instruction selection.
14187 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
14188   // This array encodes the indices that the vector sign extend instructions
14189   // extract from when extending from one type to another for both BE and LE.
14190   // The right nibble of each byte corresponds to the LE incides.
14191   // and the left nibble of each byte corresponds to the BE incides.
14192   // For example: 0x3074B8FC  byte->word
14193   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
14194   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
14195   // For example: 0x000070F8  byte->double word
14196   // For LE: the allowed indices are: 0x0,0x8
14197   // For BE: the allowed indices are: 0x7,0xF
14198   uint64_t TargetElems[] = {
14199       0x3074B8FC, // b->w
14200       0x000070F8, // b->d
14201       0x10325476, // h->w
14202       0x00003074, // h->d
14203       0x00001032, // w->d
14204   };
14205 
14206   uint64_t Elems = 0;
14207   int Index;
14208   SDValue Input;
14209 
14210   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
14211     if (!Op)
14212       return false;
14213     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
14214         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
14215       return false;
14216 
14217     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
14218     // of the right width.
14219     SDValue Extract = Op.getOperand(0);
14220     if (Extract.getOpcode() == ISD::ANY_EXTEND)
14221       Extract = Extract.getOperand(0);
14222     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14223       return false;
14224 
14225     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
14226     if (!ExtOp)
14227       return false;
14228 
14229     Index = ExtOp->getZExtValue();
14230     if (Input && Input != Extract.getOperand(0))
14231       return false;
14232 
14233     if (!Input)
14234       Input = Extract.getOperand(0);
14235 
14236     Elems = Elems << 8;
14237     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
14238     Elems |= Index;
14239 
14240     return true;
14241   };
14242 
14243   // If the build vector operands aren't sign extended vector extracts,
14244   // of the same input vector, then return.
14245   for (unsigned i = 0; i < N->getNumOperands(); i++) {
14246     if (!isSExtOfVecExtract(N->getOperand(i))) {
14247       return SDValue();
14248     }
14249   }
14250 
14251   // If the vector extract indicies are not correct, add the appropriate
14252   // vector_shuffle.
14253   int TgtElemArrayIdx;
14254   int InputSize = Input.getValueType().getScalarSizeInBits();
14255   int OutputSize = N->getValueType(0).getScalarSizeInBits();
14256   if (InputSize + OutputSize == 40)
14257     TgtElemArrayIdx = 0;
14258   else if (InputSize + OutputSize == 72)
14259     TgtElemArrayIdx = 1;
14260   else if (InputSize + OutputSize == 48)
14261     TgtElemArrayIdx = 2;
14262   else if (InputSize + OutputSize == 80)
14263     TgtElemArrayIdx = 3;
14264   else if (InputSize + OutputSize == 96)
14265     TgtElemArrayIdx = 4;
14266   else
14267     return SDValue();
14268 
14269   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
14270   CorrectElems = DAG.getDataLayout().isLittleEndian()
14271                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
14272                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
14273   if (Elems != CorrectElems) {
14274     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
14275   }
14276 
14277   // Regular lowering will catch cases where a shuffle is not needed.
14278   return SDValue();
14279 }
14280 
14281 // Look for the pattern of a load from a narrow width to i128, feeding
14282 // into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
14283 // (LXVRZX). This node represents a zero extending load that will be matched
14284 // to the Load VSX Vector Rightmost instructions.
14285 static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG) {
14286   SDLoc DL(N);
14287 
14288   // This combine is only eligible for a BUILD_VECTOR of v1i128.
14289   if (N->getValueType(0) != MVT::v1i128)
14290     return SDValue();
14291 
14292   SDValue Operand = N->getOperand(0);
14293   // Proceed with the transformation if the operand to the BUILD_VECTOR
14294   // is a load instruction.
14295   if (Operand.getOpcode() != ISD::LOAD)
14296     return SDValue();
14297 
14298   auto *LD = cast<LoadSDNode>(Operand);
14299   EVT MemoryType = LD->getMemoryVT();
14300 
14301   // This transformation is only valid if the we are loading either a byte,
14302   // halfword, word, or doubleword.
14303   bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
14304                      MemoryType == MVT::i32 || MemoryType == MVT::i64;
14305 
14306   // Ensure that the load from the narrow width is being zero extended to i128.
14307   if (!ValidLDType ||
14308       (LD->getExtensionType() != ISD::ZEXTLOAD &&
14309        LD->getExtensionType() != ISD::EXTLOAD))
14310     return SDValue();
14311 
14312   SDValue LoadOps[] = {
14313       LD->getChain(), LD->getBasePtr(),
14314       DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
14315 
14316   return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
14317                                  DAG.getVTList(MVT::v1i128, MVT::Other),
14318                                  LoadOps, MemoryType, LD->getMemOperand());
14319 }
14320 
14321 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
14322                                                  DAGCombinerInfo &DCI) const {
14323   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
14324          "Should be called with a BUILD_VECTOR node");
14325 
14326   SelectionDAG &DAG = DCI.DAG;
14327   SDLoc dl(N);
14328 
14329   if (!Subtarget.hasVSX())
14330     return SDValue();
14331 
14332   // The target independent DAG combiner will leave a build_vector of
14333   // float-to-int conversions intact. We can generate MUCH better code for
14334   // a float-to-int conversion of a vector of floats.
14335   SDValue FirstInput = N->getOperand(0);
14336   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
14337     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
14338     if (Reduced)
14339       return Reduced;
14340   }
14341 
14342   // If we're building a vector out of consecutive loads, just load that
14343   // vector type.
14344   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
14345   if (Reduced)
14346     return Reduced;
14347 
14348   // If we're building a vector out of extended elements from another vector
14349   // we have P9 vector integer extend instructions. The code assumes legal
14350   // input types (i.e. it can't handle things like v4i16) so do not run before
14351   // legalization.
14352   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
14353     Reduced = combineBVOfVecSExt(N, DAG);
14354     if (Reduced)
14355       return Reduced;
14356   }
14357 
14358   // On Power10, the Load VSX Vector Rightmost instructions can be utilized
14359   // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
14360   // is a load from <valid narrow width> to i128.
14361   if (Subtarget.isISA3_1()) {
14362     SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
14363     if (BVOfZLoad)
14364       return BVOfZLoad;
14365   }
14366 
14367   if (N->getValueType(0) != MVT::v2f64)
14368     return SDValue();
14369 
14370   // Looking for:
14371   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
14372   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
14373       FirstInput.getOpcode() != ISD::UINT_TO_FP)
14374     return SDValue();
14375   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
14376       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
14377     return SDValue();
14378   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
14379     return SDValue();
14380 
14381   SDValue Ext1 = FirstInput.getOperand(0);
14382   SDValue Ext2 = N->getOperand(1).getOperand(0);
14383   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
14384      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14385     return SDValue();
14386 
14387   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
14388   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
14389   if (!Ext1Op || !Ext2Op)
14390     return SDValue();
14391   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
14392       Ext1.getOperand(0) != Ext2.getOperand(0))
14393     return SDValue();
14394 
14395   int FirstElem = Ext1Op->getZExtValue();
14396   int SecondElem = Ext2Op->getZExtValue();
14397   int SubvecIdx;
14398   if (FirstElem == 0 && SecondElem == 1)
14399     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
14400   else if (FirstElem == 2 && SecondElem == 3)
14401     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
14402   else
14403     return SDValue();
14404 
14405   SDValue SrcVec = Ext1.getOperand(0);
14406   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
14407     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
14408   return DAG.getNode(NodeType, dl, MVT::v2f64,
14409                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
14410 }
14411 
14412 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
14413                                               DAGCombinerInfo &DCI) const {
14414   assert((N->getOpcode() == ISD::SINT_TO_FP ||
14415           N->getOpcode() == ISD::UINT_TO_FP) &&
14416          "Need an int -> FP conversion node here");
14417 
14418   if (useSoftFloat() || !Subtarget.has64BitSupport())
14419     return SDValue();
14420 
14421   SelectionDAG &DAG = DCI.DAG;
14422   SDLoc dl(N);
14423   SDValue Op(N, 0);
14424 
14425   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
14426   // from the hardware.
14427   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
14428     return SDValue();
14429   if (!Op.getOperand(0).getValueType().isSimple())
14430     return SDValue();
14431   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
14432       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
14433     return SDValue();
14434 
14435   SDValue FirstOperand(Op.getOperand(0));
14436   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
14437     (FirstOperand.getValueType() == MVT::i8 ||
14438      FirstOperand.getValueType() == MVT::i16);
14439   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
14440     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
14441     bool DstDouble = Op.getValueType() == MVT::f64;
14442     unsigned ConvOp = Signed ?
14443       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
14444       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
14445     SDValue WidthConst =
14446       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
14447                             dl, false);
14448     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
14449     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
14450     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
14451                                          DAG.getVTList(MVT::f64, MVT::Other),
14452                                          Ops, MVT::i8, LDN->getMemOperand());
14453 
14454     // For signed conversion, we need to sign-extend the value in the VSR
14455     if (Signed) {
14456       SDValue ExtOps[] = { Ld, WidthConst };
14457       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
14458       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
14459     } else
14460       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
14461   }
14462 
14463 
14464   // For i32 intermediate values, unfortunately, the conversion functions
14465   // leave the upper 32 bits of the value are undefined. Within the set of
14466   // scalar instructions, we have no method for zero- or sign-extending the
14467   // value. Thus, we cannot handle i32 intermediate values here.
14468   if (Op.getOperand(0).getValueType() == MVT::i32)
14469     return SDValue();
14470 
14471   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
14472          "UINT_TO_FP is supported only with FPCVT");
14473 
14474   // If we have FCFIDS, then use it when converting to single-precision.
14475   // Otherwise, convert to double-precision and then round.
14476   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14477                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
14478                                                             : PPCISD::FCFIDS)
14479                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
14480                                                             : PPCISD::FCFID);
14481   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
14482                   ? MVT::f32
14483                   : MVT::f64;
14484 
14485   // If we're converting from a float, to an int, and back to a float again,
14486   // then we don't need the store/load pair at all.
14487   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
14488        Subtarget.hasFPCVT()) ||
14489       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
14490     SDValue Src = Op.getOperand(0).getOperand(0);
14491     if (Src.getValueType() == MVT::f32) {
14492       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
14493       DCI.AddToWorklist(Src.getNode());
14494     } else if (Src.getValueType() != MVT::f64) {
14495       // Make sure that we don't pick up a ppc_fp128 source value.
14496       return SDValue();
14497     }
14498 
14499     unsigned FCTOp =
14500       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
14501                                                         PPCISD::FCTIDUZ;
14502 
14503     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
14504     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
14505 
14506     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
14507       FP = DAG.getNode(ISD::FP_ROUND, dl,
14508                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
14509       DCI.AddToWorklist(FP.getNode());
14510     }
14511 
14512     return FP;
14513   }
14514 
14515   return SDValue();
14516 }
14517 
14518 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
14519 // builtins) into loads with swaps.
14520 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
14521                                               DAGCombinerInfo &DCI) const {
14522   SelectionDAG &DAG = DCI.DAG;
14523   SDLoc dl(N);
14524   SDValue Chain;
14525   SDValue Base;
14526   MachineMemOperand *MMO;
14527 
14528   switch (N->getOpcode()) {
14529   default:
14530     llvm_unreachable("Unexpected opcode for little endian VSX load");
14531   case ISD::LOAD: {
14532     LoadSDNode *LD = cast<LoadSDNode>(N);
14533     Chain = LD->getChain();
14534     Base = LD->getBasePtr();
14535     MMO = LD->getMemOperand();
14536     // If the MMO suggests this isn't a load of a full vector, leave
14537     // things alone.  For a built-in, we have to make the change for
14538     // correctness, so if there is a size problem that will be a bug.
14539     if (MMO->getSize() < 16)
14540       return SDValue();
14541     break;
14542   }
14543   case ISD::INTRINSIC_W_CHAIN: {
14544     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14545     Chain = Intrin->getChain();
14546     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
14547     // us what we want. Get operand 2 instead.
14548     Base = Intrin->getOperand(2);
14549     MMO = Intrin->getMemOperand();
14550     break;
14551   }
14552   }
14553 
14554   MVT VecTy = N->getValueType(0).getSimpleVT();
14555 
14556   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
14557   // aligned and the type is a vector with elements up to 4 bytes
14558   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14559       VecTy.getScalarSizeInBits() <= 32) {
14560     return SDValue();
14561   }
14562 
14563   SDValue LoadOps[] = { Chain, Base };
14564   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
14565                                          DAG.getVTList(MVT::v2f64, MVT::Other),
14566                                          LoadOps, MVT::v2f64, MMO);
14567 
14568   DCI.AddToWorklist(Load.getNode());
14569   Chain = Load.getValue(1);
14570   SDValue Swap = DAG.getNode(
14571       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
14572   DCI.AddToWorklist(Swap.getNode());
14573 
14574   // Add a bitcast if the resulting load type doesn't match v2f64.
14575   if (VecTy != MVT::v2f64) {
14576     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
14577     DCI.AddToWorklist(N.getNode());
14578     // Package {bitcast value, swap's chain} to match Load's shape.
14579     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
14580                        N, Swap.getValue(1));
14581   }
14582 
14583   return Swap;
14584 }
14585 
14586 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
14587 // builtins) into stores with swaps.
14588 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
14589                                                DAGCombinerInfo &DCI) const {
14590   SelectionDAG &DAG = DCI.DAG;
14591   SDLoc dl(N);
14592   SDValue Chain;
14593   SDValue Base;
14594   unsigned SrcOpnd;
14595   MachineMemOperand *MMO;
14596 
14597   switch (N->getOpcode()) {
14598   default:
14599     llvm_unreachable("Unexpected opcode for little endian VSX store");
14600   case ISD::STORE: {
14601     StoreSDNode *ST = cast<StoreSDNode>(N);
14602     Chain = ST->getChain();
14603     Base = ST->getBasePtr();
14604     MMO = ST->getMemOperand();
14605     SrcOpnd = 1;
14606     // If the MMO suggests this isn't a store of a full vector, leave
14607     // things alone.  For a built-in, we have to make the change for
14608     // correctness, so if there is a size problem that will be a bug.
14609     if (MMO->getSize() < 16)
14610       return SDValue();
14611     break;
14612   }
14613   case ISD::INTRINSIC_VOID: {
14614     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
14615     Chain = Intrin->getChain();
14616     // Intrin->getBasePtr() oddly does not get what we want.
14617     Base = Intrin->getOperand(3);
14618     MMO = Intrin->getMemOperand();
14619     SrcOpnd = 2;
14620     break;
14621   }
14622   }
14623 
14624   SDValue Src = N->getOperand(SrcOpnd);
14625   MVT VecTy = Src.getValueType().getSimpleVT();
14626 
14627   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
14628   // aligned and the type is a vector with elements up to 4 bytes
14629   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
14630       VecTy.getScalarSizeInBits() <= 32) {
14631     return SDValue();
14632   }
14633 
14634   // All stores are done as v2f64 and possible bit cast.
14635   if (VecTy != MVT::v2f64) {
14636     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
14637     DCI.AddToWorklist(Src.getNode());
14638   }
14639 
14640   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
14641                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
14642   DCI.AddToWorklist(Swap.getNode());
14643   Chain = Swap.getValue(1);
14644   SDValue StoreOps[] = { Chain, Swap, Base };
14645   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
14646                                           DAG.getVTList(MVT::Other),
14647                                           StoreOps, VecTy, MMO);
14648   DCI.AddToWorklist(Store.getNode());
14649   return Store;
14650 }
14651 
14652 // Handle DAG combine for STORE (FP_TO_INT F).
14653 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
14654                                                DAGCombinerInfo &DCI) const {
14655 
14656   SelectionDAG &DAG = DCI.DAG;
14657   SDLoc dl(N);
14658   unsigned Opcode = N->getOperand(1).getOpcode();
14659 
14660   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
14661          && "Not a FP_TO_INT Instruction!");
14662 
14663   SDValue Val = N->getOperand(1).getOperand(0);
14664   EVT Op1VT = N->getOperand(1).getValueType();
14665   EVT ResVT = Val.getValueType();
14666 
14667   if (!isTypeLegal(ResVT))
14668     return SDValue();
14669 
14670   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
14671   bool ValidTypeForStoreFltAsInt =
14672         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
14673          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
14674 
14675   if (ResVT == MVT::f128 && !Subtarget.hasP9Vector())
14676     return SDValue();
14677 
14678   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
14679       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
14680     return SDValue();
14681 
14682   // Extend f32 values to f64
14683   if (ResVT.getScalarSizeInBits() == 32) {
14684     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
14685     DCI.AddToWorklist(Val.getNode());
14686   }
14687 
14688   // Set signed or unsigned conversion opcode.
14689   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
14690                           PPCISD::FP_TO_SINT_IN_VSR :
14691                           PPCISD::FP_TO_UINT_IN_VSR;
14692 
14693   Val = DAG.getNode(ConvOpcode,
14694                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
14695   DCI.AddToWorklist(Val.getNode());
14696 
14697   // Set number of bytes being converted.
14698   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
14699   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
14700                     DAG.getIntPtrConstant(ByteSize, dl, false),
14701                     DAG.getValueType(Op1VT) };
14702 
14703   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
14704           DAG.getVTList(MVT::Other), Ops,
14705           cast<StoreSDNode>(N)->getMemoryVT(),
14706           cast<StoreSDNode>(N)->getMemOperand());
14707 
14708   DCI.AddToWorklist(Val.getNode());
14709   return Val;
14710 }
14711 
14712 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
14713   // Check that the source of the element keeps flipping
14714   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
14715   bool PrevElemFromFirstVec = Mask[0] < NumElts;
14716   for (int i = 1, e = Mask.size(); i < e; i++) {
14717     if (PrevElemFromFirstVec && Mask[i] < NumElts)
14718       return false;
14719     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
14720       return false;
14721     PrevElemFromFirstVec = !PrevElemFromFirstVec;
14722   }
14723   return true;
14724 }
14725 
14726 static bool isSplatBV(SDValue Op) {
14727   if (Op.getOpcode() != ISD::BUILD_VECTOR)
14728     return false;
14729   SDValue FirstOp;
14730 
14731   // Find first non-undef input.
14732   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
14733     FirstOp = Op.getOperand(i);
14734     if (!FirstOp.isUndef())
14735       break;
14736   }
14737 
14738   // All inputs are undef or the same as the first non-undef input.
14739   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
14740     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
14741       return false;
14742   return true;
14743 }
14744 
14745 static SDValue isScalarToVec(SDValue Op) {
14746   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14747     return Op;
14748   if (Op.getOpcode() != ISD::BITCAST)
14749     return SDValue();
14750   Op = Op.getOperand(0);
14751   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
14752     return Op;
14753   return SDValue();
14754 }
14755 
14756 // Fix up the shuffle mask to account for the fact that the result of
14757 // scalar_to_vector is not in lane zero. This just takes all values in
14758 // the ranges specified by the min/max indices and adds the number of
14759 // elements required to ensure each element comes from the respective
14760 // position in the valid lane.
14761 // On little endian, that's just the corresponding element in the other
14762 // half of the vector. On big endian, it is in the same half but right
14763 // justified rather than left justified in that half.
14764 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
14765                                             int LHSMaxIdx, int RHSMinIdx,
14766                                             int RHSMaxIdx, int HalfVec,
14767                                             unsigned ValidLaneWidth,
14768                                             const PPCSubtarget &Subtarget) {
14769   for (int i = 0, e = ShuffV.size(); i < e; i++) {
14770     int Idx = ShuffV[i];
14771     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
14772       ShuffV[i] +=
14773           Subtarget.isLittleEndian() ? HalfVec : HalfVec - ValidLaneWidth;
14774   }
14775 }
14776 
14777 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
14778 // the original is:
14779 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
14780 // In such a case, just change the shuffle mask to extract the element
14781 // from the permuted index.
14782 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG,
14783                                const PPCSubtarget &Subtarget) {
14784   SDLoc dl(OrigSToV);
14785   EVT VT = OrigSToV.getValueType();
14786   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
14787          "Expecting a SCALAR_TO_VECTOR here");
14788   SDValue Input = OrigSToV.getOperand(0);
14789 
14790   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14791     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
14792     SDValue OrigVector = Input.getOperand(0);
14793 
14794     // Can't handle non-const element indices or different vector types
14795     // for the input to the extract and the output of the scalar_to_vector.
14796     if (Idx && VT == OrigVector.getValueType()) {
14797       unsigned NumElts = VT.getVectorNumElements();
14798       assert(
14799           NumElts > 1 &&
14800           "Cannot produce a permuted scalar_to_vector for one element vector");
14801       SmallVector<int, 16> NewMask(NumElts, -1);
14802       unsigned ResultInElt = NumElts / 2;
14803       ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
14804       NewMask[ResultInElt] = Idx->getZExtValue();
14805       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
14806     }
14807   }
14808   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
14809                      OrigSToV.getOperand(0));
14810 }
14811 
14812 // On little endian subtargets, combine shuffles such as:
14813 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
14814 // into:
14815 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
14816 // because the latter can be matched to a single instruction merge.
14817 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
14818 // to put the value into element zero. Adjust the shuffle mask so that the
14819 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
14820 // On big endian targets, this is still useful for SCALAR_TO_VECTOR
14821 // nodes with elements smaller than doubleword because all the ways
14822 // of getting scalar data into a vector register put the value in the
14823 // rightmost element of the left half of the vector.
14824 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
14825                                                 SelectionDAG &DAG) const {
14826   SDValue LHS = SVN->getOperand(0);
14827   SDValue RHS = SVN->getOperand(1);
14828   auto Mask = SVN->getMask();
14829   int NumElts = LHS.getValueType().getVectorNumElements();
14830   SDValue Res(SVN, 0);
14831   SDLoc dl(SVN);
14832   bool IsLittleEndian = Subtarget.isLittleEndian();
14833 
14834   // On big endian targets this is only useful for subtargets with direct moves.
14835   // On little endian targets it would be useful for all subtargets with VSX.
14836   // However adding special handling for LE subtargets without direct moves
14837   // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
14838   // which includes direct moves.
14839   if (!Subtarget.hasDirectMove())
14840     return Res;
14841 
14842   // If this is not a shuffle of a shuffle and the first element comes from
14843   // the second vector, canonicalize to the commuted form. This will make it
14844   // more likely to match one of the single instruction patterns.
14845   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14846       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
14847     std::swap(LHS, RHS);
14848     Res = DAG.getCommutedVectorShuffle(*SVN);
14849     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14850   }
14851 
14852   // Adjust the shuffle mask if either input vector comes from a
14853   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
14854   // form (to prevent the need for a swap).
14855   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
14856   SDValue SToVLHS = isScalarToVec(LHS);
14857   SDValue SToVRHS = isScalarToVec(RHS);
14858   if (SToVLHS || SToVRHS) {
14859     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
14860                             : SToVRHS.getValueType().getVectorNumElements();
14861     int NumEltsOut = ShuffV.size();
14862     // The width of the "valid lane" (i.e. the lane that contains the value that
14863     // is vectorized) needs to be expressed in terms of the number of elements
14864     // of the shuffle. It is thereby the ratio of the values before and after
14865     // any bitcast.
14866     unsigned ValidLaneWidth =
14867         SToVLHS ? SToVLHS.getValueType().getScalarSizeInBits() /
14868                       LHS.getValueType().getScalarSizeInBits()
14869                 : SToVRHS.getValueType().getScalarSizeInBits() /
14870                       RHS.getValueType().getScalarSizeInBits();
14871 
14872     // Initially assume that neither input is permuted. These will be adjusted
14873     // accordingly if either input is.
14874     int LHSMaxIdx = -1;
14875     int RHSMinIdx = -1;
14876     int RHSMaxIdx = -1;
14877     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14878 
14879     // Get the permuted scalar to vector nodes for the source(s) that come from
14880     // ISD::SCALAR_TO_VECTOR.
14881     // On big endian systems, this only makes sense for element sizes smaller
14882     // than 64 bits since for 64-bit elements, all instructions already put
14883     // the value into element zero. Since scalar size of LHS and RHS may differ
14884     // after isScalarToVec, this should be checked using their own sizes.
14885     if (SToVLHS) {
14886       if (!IsLittleEndian && SToVLHS.getValueType().getScalarSizeInBits() >= 64)
14887         return Res;
14888       // Set up the values for the shuffle vector fixup.
14889       LHSMaxIdx = NumEltsOut / NumEltsIn;
14890       SToVLHS = getSToVPermuted(SToVLHS, DAG, Subtarget);
14891       if (SToVLHS.getValueType() != LHS.getValueType())
14892         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14893       LHS = SToVLHS;
14894     }
14895     if (SToVRHS) {
14896       if (!IsLittleEndian && SToVRHS.getValueType().getScalarSizeInBits() >= 64)
14897         return Res;
14898       RHSMinIdx = NumEltsOut;
14899       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14900       SToVRHS = getSToVPermuted(SToVRHS, DAG, Subtarget);
14901       if (SToVRHS.getValueType() != RHS.getValueType())
14902         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14903       RHS = SToVRHS;
14904     }
14905 
14906     // Fix up the shuffle mask to reflect where the desired element actually is.
14907     // The minimum and maximum indices that correspond to element zero for both
14908     // the LHS and RHS are computed and will control which shuffle mask entries
14909     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14910     // entries in the range [RHSMinIdx,RHSMaxIdx) will be adjusted.
14911     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14912                                     HalfVec, ValidLaneWidth, Subtarget);
14913     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14914 
14915     // We may have simplified away the shuffle. We won't be able to do anything
14916     // further with it here.
14917     if (!isa<ShuffleVectorSDNode>(Res))
14918       return Res;
14919     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14920   }
14921 
14922   SDValue TheSplat = IsLittleEndian ? RHS : LHS;
14923   // The common case after we commuted the shuffle is that the RHS is a splat
14924   // and we have elements coming in from the splat at indices that are not
14925   // conducive to using a merge.
14926   // Example:
14927   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14928   if (!isSplatBV(TheSplat))
14929     return Res;
14930 
14931   // We are looking for a mask such that all even elements are from
14932   // one vector and all odd elements from the other.
14933   if (!isAlternatingShuffMask(Mask, NumElts))
14934     return Res;
14935 
14936   // Adjust the mask so we are pulling in the same index from the splat
14937   // as the index from the interesting vector in consecutive elements.
14938   if (IsLittleEndian) {
14939     // Example (even elements from first vector):
14940     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14941     if (Mask[0] < NumElts)
14942       for (int i = 1, e = Mask.size(); i < e; i += 2)
14943         ShuffV[i] = (ShuffV[i - 1] + NumElts);
14944     // Example (odd elements from first vector):
14945     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14946     else
14947       for (int i = 0, e = Mask.size(); i < e; i += 2)
14948         ShuffV[i] = (ShuffV[i + 1] + NumElts);
14949   } else {
14950     // Example (even elements from first vector):
14951     // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
14952     if (Mask[0] < NumElts)
14953       for (int i = 0, e = Mask.size(); i < e; i += 2)
14954         ShuffV[i] = ShuffV[i + 1] - NumElts;
14955     // Example (odd elements from first vector):
14956     // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
14957     else
14958       for (int i = 1, e = Mask.size(); i < e; i += 2)
14959         ShuffV[i] = ShuffV[i - 1] - NumElts;
14960   }
14961 
14962   // If the RHS has undefs, we need to remove them since we may have created
14963   // a shuffle that adds those instead of the splat value.
14964   SDValue SplatVal =
14965       cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
14966   TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
14967 
14968   if (IsLittleEndian)
14969     RHS = TheSplat;
14970   else
14971     LHS = TheSplat;
14972   return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14973 }
14974 
14975 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14976                                                 LSBaseSDNode *LSBase,
14977                                                 DAGCombinerInfo &DCI) const {
14978   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14979         "Not a reverse memop pattern!");
14980 
14981   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14982     auto Mask = SVN->getMask();
14983     int i = 0;
14984     auto I = Mask.rbegin();
14985     auto E = Mask.rend();
14986 
14987     for (; I != E; ++I) {
14988       if (*I != i)
14989         return false;
14990       i++;
14991     }
14992     return true;
14993   };
14994 
14995   SelectionDAG &DAG = DCI.DAG;
14996   EVT VT = SVN->getValueType(0);
14997 
14998   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14999     return SDValue();
15000 
15001   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
15002   // See comment in PPCVSXSwapRemoval.cpp.
15003   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
15004   if (!Subtarget.hasP9Vector())
15005     return SDValue();
15006 
15007   if(!IsElementReverse(SVN))
15008     return SDValue();
15009 
15010   if (LSBase->getOpcode() == ISD::LOAD) {
15011     // If the load return value 0 has more than one user except the
15012     // shufflevector instruction, it is not profitable to replace the
15013     // shufflevector with a reverse load.
15014     for (SDNode::use_iterator UI = LSBase->use_begin(), UE = LSBase->use_end();
15015          UI != UE; ++UI)
15016       if (UI.getUse().getResNo() == 0 && UI->getOpcode() != ISD::VECTOR_SHUFFLE)
15017         return SDValue();
15018 
15019     SDLoc dl(LSBase);
15020     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
15021     return DAG.getMemIntrinsicNode(
15022         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
15023         LSBase->getMemoryVT(), LSBase->getMemOperand());
15024   }
15025 
15026   if (LSBase->getOpcode() == ISD::STORE) {
15027     // If there are other uses of the shuffle, the swap cannot be avoided.
15028     // Forcing the use of an X-Form (since swapped stores only have
15029     // X-Forms) without removing the swap is unprofitable.
15030     if (!SVN->hasOneUse())
15031       return SDValue();
15032 
15033     SDLoc dl(LSBase);
15034     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
15035                           LSBase->getBasePtr()};
15036     return DAG.getMemIntrinsicNode(
15037         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
15038         LSBase->getMemoryVT(), LSBase->getMemOperand());
15039   }
15040 
15041   llvm_unreachable("Expected a load or store node here");
15042 }
15043 
15044 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
15045                                              DAGCombinerInfo &DCI) const {
15046   SelectionDAG &DAG = DCI.DAG;
15047   SDLoc dl(N);
15048   switch (N->getOpcode()) {
15049   default: break;
15050   case ISD::ADD:
15051     return combineADD(N, DCI);
15052   case ISD::SHL:
15053     return combineSHL(N, DCI);
15054   case ISD::SRA:
15055     return combineSRA(N, DCI);
15056   case ISD::SRL:
15057     return combineSRL(N, DCI);
15058   case ISD::MUL:
15059     return combineMUL(N, DCI);
15060   case ISD::FMA:
15061   case PPCISD::FNMSUB:
15062     return combineFMALike(N, DCI);
15063   case PPCISD::SHL:
15064     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
15065         return N->getOperand(0);
15066     break;
15067   case PPCISD::SRL:
15068     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
15069         return N->getOperand(0);
15070     break;
15071   case PPCISD::SRA:
15072     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
15073       if (C->isZero() ||  //  0 >>s V -> 0.
15074           C->isAllOnes()) // -1 >>s V -> -1.
15075         return N->getOperand(0);
15076     }
15077     break;
15078   case ISD::SIGN_EXTEND:
15079   case ISD::ZERO_EXTEND:
15080   case ISD::ANY_EXTEND:
15081     return DAGCombineExtBoolTrunc(N, DCI);
15082   case ISD::TRUNCATE:
15083     return combineTRUNCATE(N, DCI);
15084   case ISD::SETCC:
15085     if (SDValue CSCC = combineSetCC(N, DCI))
15086       return CSCC;
15087     LLVM_FALLTHROUGH;
15088   case ISD::SELECT_CC:
15089     return DAGCombineTruncBoolExt(N, DCI);
15090   case ISD::SINT_TO_FP:
15091   case ISD::UINT_TO_FP:
15092     return combineFPToIntToFP(N, DCI);
15093   case ISD::VECTOR_SHUFFLE:
15094     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
15095       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
15096       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
15097     }
15098     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
15099   case ISD::STORE: {
15100 
15101     EVT Op1VT = N->getOperand(1).getValueType();
15102     unsigned Opcode = N->getOperand(1).getOpcode();
15103 
15104     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
15105       SDValue Val= combineStoreFPToInt(N, DCI);
15106       if (Val)
15107         return Val;
15108     }
15109 
15110     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
15111       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
15112       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
15113       if (Val)
15114         return Val;
15115     }
15116 
15117     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
15118     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
15119         N->getOperand(1).getNode()->hasOneUse() &&
15120         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
15121          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
15122 
15123       // STBRX can only handle simple types and it makes no sense to store less
15124       // two bytes in byte-reversed order.
15125       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
15126       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
15127         break;
15128 
15129       SDValue BSwapOp = N->getOperand(1).getOperand(0);
15130       // Do an any-extend to 32-bits if this is a half-word input.
15131       if (BSwapOp.getValueType() == MVT::i16)
15132         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
15133 
15134       // If the type of BSWAP operand is wider than stored memory width
15135       // it need to be shifted to the right side before STBRX.
15136       if (Op1VT.bitsGT(mVT)) {
15137         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
15138         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
15139                               DAG.getConstant(Shift, dl, MVT::i32));
15140         // Need to truncate if this is a bswap of i64 stored as i32/i16.
15141         if (Op1VT == MVT::i64)
15142           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
15143       }
15144 
15145       SDValue Ops[] = {
15146         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
15147       };
15148       return
15149         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
15150                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
15151                                 cast<StoreSDNode>(N)->getMemOperand());
15152     }
15153 
15154     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
15155     // So it can increase the chance of CSE constant construction.
15156     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
15157         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
15158       // Need to sign-extended to 64-bits to handle negative values.
15159       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
15160       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
15161                                     MemVT.getSizeInBits());
15162       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
15163 
15164       // DAG.getTruncStore() can't be used here because it doesn't accept
15165       // the general (base + offset) addressing mode.
15166       // So we use UpdateNodeOperands and setTruncatingStore instead.
15167       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
15168                              N->getOperand(3));
15169       cast<StoreSDNode>(N)->setTruncatingStore(true);
15170       return SDValue(N, 0);
15171     }
15172 
15173     // For little endian, VSX stores require generating xxswapd/lxvd2x.
15174     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15175     if (Op1VT.isSimple()) {
15176       MVT StoreVT = Op1VT.getSimpleVT();
15177       if (Subtarget.needsSwapsForVSXMemOps() &&
15178           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
15179            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
15180         return expandVSXStoreForLE(N, DCI);
15181     }
15182     break;
15183   }
15184   case ISD::LOAD: {
15185     LoadSDNode *LD = cast<LoadSDNode>(N);
15186     EVT VT = LD->getValueType(0);
15187 
15188     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15189     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15190     if (VT.isSimple()) {
15191       MVT LoadVT = VT.getSimpleVT();
15192       if (Subtarget.needsSwapsForVSXMemOps() &&
15193           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
15194            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
15195         return expandVSXLoadForLE(N, DCI);
15196     }
15197 
15198     // We sometimes end up with a 64-bit integer load, from which we extract
15199     // two single-precision floating-point numbers. This happens with
15200     // std::complex<float>, and other similar structures, because of the way we
15201     // canonicalize structure copies. However, if we lack direct moves,
15202     // then the final bitcasts from the extracted integer values to the
15203     // floating-point numbers turn into store/load pairs. Even with direct moves,
15204     // just loading the two floating-point numbers is likely better.
15205     auto ReplaceTwoFloatLoad = [&]() {
15206       if (VT != MVT::i64)
15207         return false;
15208 
15209       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
15210           LD->isVolatile())
15211         return false;
15212 
15213       //  We're looking for a sequence like this:
15214       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
15215       //      t16: i64 = srl t13, Constant:i32<32>
15216       //    t17: i32 = truncate t16
15217       //  t18: f32 = bitcast t17
15218       //    t19: i32 = truncate t13
15219       //  t20: f32 = bitcast t19
15220 
15221       if (!LD->hasNUsesOfValue(2, 0))
15222         return false;
15223 
15224       auto UI = LD->use_begin();
15225       while (UI.getUse().getResNo() != 0) ++UI;
15226       SDNode *Trunc = *UI++;
15227       while (UI.getUse().getResNo() != 0) ++UI;
15228       SDNode *RightShift = *UI;
15229       if (Trunc->getOpcode() != ISD::TRUNCATE)
15230         std::swap(Trunc, RightShift);
15231 
15232       if (Trunc->getOpcode() != ISD::TRUNCATE ||
15233           Trunc->getValueType(0) != MVT::i32 ||
15234           !Trunc->hasOneUse())
15235         return false;
15236       if (RightShift->getOpcode() != ISD::SRL ||
15237           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
15238           RightShift->getConstantOperandVal(1) != 32 ||
15239           !RightShift->hasOneUse())
15240         return false;
15241 
15242       SDNode *Trunc2 = *RightShift->use_begin();
15243       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
15244           Trunc2->getValueType(0) != MVT::i32 ||
15245           !Trunc2->hasOneUse())
15246         return false;
15247 
15248       SDNode *Bitcast = *Trunc->use_begin();
15249       SDNode *Bitcast2 = *Trunc2->use_begin();
15250 
15251       if (Bitcast->getOpcode() != ISD::BITCAST ||
15252           Bitcast->getValueType(0) != MVT::f32)
15253         return false;
15254       if (Bitcast2->getOpcode() != ISD::BITCAST ||
15255           Bitcast2->getValueType(0) != MVT::f32)
15256         return false;
15257 
15258       if (Subtarget.isLittleEndian())
15259         std::swap(Bitcast, Bitcast2);
15260 
15261       // Bitcast has the second float (in memory-layout order) and Bitcast2
15262       // has the first one.
15263 
15264       SDValue BasePtr = LD->getBasePtr();
15265       if (LD->isIndexed()) {
15266         assert(LD->getAddressingMode() == ISD::PRE_INC &&
15267                "Non-pre-inc AM on PPC?");
15268         BasePtr =
15269           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15270                       LD->getOffset());
15271       }
15272 
15273       auto MMOFlags =
15274           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
15275       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
15276                                       LD->getPointerInfo(), LD->getAlignment(),
15277                                       MMOFlags, LD->getAAInfo());
15278       SDValue AddPtr =
15279         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
15280                     BasePtr, DAG.getIntPtrConstant(4, dl));
15281       SDValue FloatLoad2 = DAG.getLoad(
15282           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
15283           LD->getPointerInfo().getWithOffset(4),
15284           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
15285 
15286       if (LD->isIndexed()) {
15287         // Note that DAGCombine should re-form any pre-increment load(s) from
15288         // what is produced here if that makes sense.
15289         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
15290       }
15291 
15292       DCI.CombineTo(Bitcast2, FloatLoad);
15293       DCI.CombineTo(Bitcast, FloatLoad2);
15294 
15295       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
15296                                     SDValue(FloatLoad2.getNode(), 1));
15297       return true;
15298     };
15299 
15300     if (ReplaceTwoFloatLoad())
15301       return SDValue(N, 0);
15302 
15303     EVT MemVT = LD->getMemoryVT();
15304     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
15305     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
15306     if (LD->isUnindexed() && VT.isVector() &&
15307         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
15308           // P8 and later hardware should just use LOAD.
15309           !Subtarget.hasP8Vector() &&
15310           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
15311            VT == MVT::v4f32))) &&
15312         LD->getAlign() < ABIAlignment) {
15313       // This is a type-legal unaligned Altivec load.
15314       SDValue Chain = LD->getChain();
15315       SDValue Ptr = LD->getBasePtr();
15316       bool isLittleEndian = Subtarget.isLittleEndian();
15317 
15318       // This implements the loading of unaligned vectors as described in
15319       // the venerable Apple Velocity Engine overview. Specifically:
15320       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
15321       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
15322       //
15323       // The general idea is to expand a sequence of one or more unaligned
15324       // loads into an alignment-based permutation-control instruction (lvsl
15325       // or lvsr), a series of regular vector loads (which always truncate
15326       // their input address to an aligned address), and a series of
15327       // permutations.  The results of these permutations are the requested
15328       // loaded values.  The trick is that the last "extra" load is not taken
15329       // from the address you might suspect (sizeof(vector) bytes after the
15330       // last requested load), but rather sizeof(vector) - 1 bytes after the
15331       // last requested vector. The point of this is to avoid a page fault if
15332       // the base address happened to be aligned. This works because if the
15333       // base address is aligned, then adding less than a full vector length
15334       // will cause the last vector in the sequence to be (re)loaded.
15335       // Otherwise, the next vector will be fetched as you might suspect was
15336       // necessary.
15337 
15338       // We might be able to reuse the permutation generation from
15339       // a different base address offset from this one by an aligned amount.
15340       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
15341       // optimization later.
15342       Intrinsic::ID Intr, IntrLD, IntrPerm;
15343       MVT PermCntlTy, PermTy, LDTy;
15344       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15345                             : Intrinsic::ppc_altivec_lvsl;
15346       IntrLD = Intrinsic::ppc_altivec_lvx;
15347       IntrPerm = Intrinsic::ppc_altivec_vperm;
15348       PermCntlTy = MVT::v16i8;
15349       PermTy = MVT::v4i32;
15350       LDTy = MVT::v4i32;
15351 
15352       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
15353 
15354       // Create the new MMO for the new base load. It is like the original MMO,
15355       // but represents an area in memory almost twice the vector size centered
15356       // on the original address. If the address is unaligned, we might start
15357       // reading up to (sizeof(vector)-1) bytes below the address of the
15358       // original unaligned load.
15359       MachineFunction &MF = DAG.getMachineFunction();
15360       MachineMemOperand *BaseMMO =
15361         MF.getMachineMemOperand(LD->getMemOperand(),
15362                                 -(long)MemVT.getStoreSize()+1,
15363                                 2*MemVT.getStoreSize()-1);
15364 
15365       // Create the new base load.
15366       SDValue LDXIntID =
15367           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
15368       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
15369       SDValue BaseLoad =
15370         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15371                                 DAG.getVTList(PermTy, MVT::Other),
15372                                 BaseLoadOps, LDTy, BaseMMO);
15373 
15374       // Note that the value of IncOffset (which is provided to the next
15375       // load's pointer info offset value, and thus used to calculate the
15376       // alignment), and the value of IncValue (which is actually used to
15377       // increment the pointer value) are different! This is because we
15378       // require the next load to appear to be aligned, even though it
15379       // is actually offset from the base pointer by a lesser amount.
15380       int IncOffset = VT.getSizeInBits() / 8;
15381       int IncValue = IncOffset;
15382 
15383       // Walk (both up and down) the chain looking for another load at the real
15384       // (aligned) offset (the alignment of the other load does not matter in
15385       // this case). If found, then do not use the offset reduction trick, as
15386       // that will prevent the loads from being later combined (as they would
15387       // otherwise be duplicates).
15388       if (!findConsecutiveLoad(LD, DAG))
15389         --IncValue;
15390 
15391       SDValue Increment =
15392           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
15393       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15394 
15395       MachineMemOperand *ExtraMMO =
15396         MF.getMachineMemOperand(LD->getMemOperand(),
15397                                 1, 2*MemVT.getStoreSize()-1);
15398       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
15399       SDValue ExtraLoad =
15400         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
15401                                 DAG.getVTList(PermTy, MVT::Other),
15402                                 ExtraLoadOps, LDTy, ExtraMMO);
15403 
15404       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15405         BaseLoad.getValue(1), ExtraLoad.getValue(1));
15406 
15407       // Because vperm has a big-endian bias, we must reverse the order
15408       // of the input vectors and complement the permute control vector
15409       // when generating little endian code.  We have already handled the
15410       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
15411       // and ExtraLoad here.
15412       SDValue Perm;
15413       if (isLittleEndian)
15414         Perm = BuildIntrinsicOp(IntrPerm,
15415                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
15416       else
15417         Perm = BuildIntrinsicOp(IntrPerm,
15418                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
15419 
15420       if (VT != PermTy)
15421         Perm = Subtarget.hasAltivec()
15422                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
15423                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
15424                                  DAG.getTargetConstant(1, dl, MVT::i64));
15425                                // second argument is 1 because this rounding
15426                                // is always exact.
15427 
15428       // The output of the permutation is our loaded result, the TokenFactor is
15429       // our new chain.
15430       DCI.CombineTo(N, Perm, TF);
15431       return SDValue(N, 0);
15432     }
15433     }
15434     break;
15435     case ISD::INTRINSIC_WO_CHAIN: {
15436       bool isLittleEndian = Subtarget.isLittleEndian();
15437       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
15438       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
15439                                            : Intrinsic::ppc_altivec_lvsl);
15440       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
15441         SDValue Add = N->getOperand(1);
15442 
15443         int Bits = 4 /* 16 byte alignment */;
15444 
15445         if (DAG.MaskedValueIsZero(Add->getOperand(1),
15446                                   APInt::getAllOnes(Bits /* alignment */)
15447                                       .zext(Add.getScalarValueSizeInBits()))) {
15448           SDNode *BasePtr = Add->getOperand(0).getNode();
15449           for (SDNode *U : BasePtr->uses()) {
15450             if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15451                 cast<ConstantSDNode>(U->getOperand(0))->getZExtValue() == IID) {
15452               // We've found another LVSL/LVSR, and this address is an aligned
15453               // multiple of that one. The results will be the same, so use the
15454               // one we've just found instead.
15455 
15456               return SDValue(U, 0);
15457             }
15458           }
15459         }
15460 
15461         if (isa<ConstantSDNode>(Add->getOperand(1))) {
15462           SDNode *BasePtr = Add->getOperand(0).getNode();
15463           for (SDNode *U : BasePtr->uses()) {
15464             if (U->getOpcode() == ISD::ADD &&
15465                 isa<ConstantSDNode>(U->getOperand(1)) &&
15466                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
15467                  cast<ConstantSDNode>(U->getOperand(1))->getZExtValue()) %
15468                         (1ULL << Bits) ==
15469                     0) {
15470               SDNode *OtherAdd = U;
15471               for (SDNode *V : OtherAdd->uses()) {
15472                 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15473                     cast<ConstantSDNode>(V->getOperand(0))->getZExtValue() ==
15474                         IID) {
15475                   return SDValue(V, 0);
15476                 }
15477               }
15478             }
15479           }
15480         }
15481       }
15482 
15483       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
15484       // Expose the vabsduw/h/b opportunity for down stream
15485       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
15486           (IID == Intrinsic::ppc_altivec_vmaxsw ||
15487            IID == Intrinsic::ppc_altivec_vmaxsh ||
15488            IID == Intrinsic::ppc_altivec_vmaxsb)) {
15489         SDValue V1 = N->getOperand(1);
15490         SDValue V2 = N->getOperand(2);
15491         if ((V1.getSimpleValueType() == MVT::v4i32 ||
15492              V1.getSimpleValueType() == MVT::v8i16 ||
15493              V1.getSimpleValueType() == MVT::v16i8) &&
15494             V1.getSimpleValueType() == V2.getSimpleValueType()) {
15495           // (0-a, a)
15496           if (V1.getOpcode() == ISD::SUB &&
15497               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
15498               V1.getOperand(1) == V2) {
15499             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
15500           }
15501           // (a, 0-a)
15502           if (V2.getOpcode() == ISD::SUB &&
15503               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
15504               V2.getOperand(1) == V1) {
15505             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15506           }
15507           // (x-y, y-x)
15508           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
15509               V1.getOperand(0) == V2.getOperand(1) &&
15510               V1.getOperand(1) == V2.getOperand(0)) {
15511             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
15512           }
15513         }
15514       }
15515     }
15516 
15517     break;
15518   case ISD::INTRINSIC_W_CHAIN:
15519     // For little endian, VSX loads require generating lxvd2x/xxswapd.
15520     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
15521     if (Subtarget.needsSwapsForVSXMemOps()) {
15522       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15523       default:
15524         break;
15525       case Intrinsic::ppc_vsx_lxvw4x:
15526       case Intrinsic::ppc_vsx_lxvd2x:
15527         return expandVSXLoadForLE(N, DCI);
15528       }
15529     }
15530     break;
15531   case ISD::INTRINSIC_VOID:
15532     // For little endian, VSX stores require generating xxswapd/stxvd2x.
15533     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
15534     if (Subtarget.needsSwapsForVSXMemOps()) {
15535       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15536       default:
15537         break;
15538       case Intrinsic::ppc_vsx_stxvw4x:
15539       case Intrinsic::ppc_vsx_stxvd2x:
15540         return expandVSXStoreForLE(N, DCI);
15541       }
15542     }
15543     break;
15544   case ISD::BSWAP: {
15545     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
15546     // For subtargets without LDBRX, we can still do better than the default
15547     // expansion even for 64-bit BSWAP (LOAD).
15548     bool Is64BitBswapOn64BitTgt =
15549         Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
15550     bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
15551                                N->getOperand(0).hasOneUse();
15552     if (IsSingleUseNormalLd &&
15553         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
15554          (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
15555       SDValue Load = N->getOperand(0);
15556       LoadSDNode *LD = cast<LoadSDNode>(Load);
15557       // Create the byte-swapping load.
15558       SDValue Ops[] = {
15559         LD->getChain(),    // Chain
15560         LD->getBasePtr(),  // Ptr
15561         DAG.getValueType(N->getValueType(0)) // VT
15562       };
15563       SDValue BSLoad =
15564         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
15565                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
15566                                               MVT::i64 : MVT::i32, MVT::Other),
15567                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
15568 
15569       // If this is an i16 load, insert the truncate.
15570       SDValue ResVal = BSLoad;
15571       if (N->getValueType(0) == MVT::i16)
15572         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
15573 
15574       // First, combine the bswap away.  This makes the value produced by the
15575       // load dead.
15576       DCI.CombineTo(N, ResVal);
15577 
15578       // Next, combine the load away, we give it a bogus result value but a real
15579       // chain result.  The result value is dead because the bswap is dead.
15580       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
15581 
15582       // Return N so it doesn't get rechecked!
15583       return SDValue(N, 0);
15584     }
15585     // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
15586     // before legalization so that the BUILD_PAIR is handled correctly.
15587     if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
15588         !IsSingleUseNormalLd)
15589       return SDValue();
15590     LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
15591 
15592     // Can't split volatile or atomic loads.
15593     if (!LD->isSimple())
15594       return SDValue();
15595     SDValue BasePtr = LD->getBasePtr();
15596     SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
15597                              LD->getPointerInfo(), LD->getAlignment());
15598     Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
15599     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
15600                           DAG.getIntPtrConstant(4, dl));
15601     MachineMemOperand *NewMMO = DAG.getMachineFunction().getMachineMemOperand(
15602         LD->getMemOperand(), 4, 4);
15603     SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
15604     Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
15605     SDValue Res;
15606     if (Subtarget.isLittleEndian())
15607       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
15608     else
15609       Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
15610     SDValue TF =
15611         DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15612                     Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
15613     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
15614     return Res;
15615   }
15616   case PPCISD::VCMP:
15617     // If a VCMP_rec node already exists with exactly the same operands as this
15618     // node, use its result instead of this node (VCMP_rec computes both a CR6
15619     // and a normal output).
15620     //
15621     if (!N->getOperand(0).hasOneUse() &&
15622         !N->getOperand(1).hasOneUse() &&
15623         !N->getOperand(2).hasOneUse()) {
15624 
15625       // Scan all of the users of the LHS, looking for VCMP_rec's that match.
15626       SDNode *VCMPrecNode = nullptr;
15627 
15628       SDNode *LHSN = N->getOperand(0).getNode();
15629       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
15630            UI != E; ++UI)
15631         if (UI->getOpcode() == PPCISD::VCMP_rec &&
15632             UI->getOperand(1) == N->getOperand(1) &&
15633             UI->getOperand(2) == N->getOperand(2) &&
15634             UI->getOperand(0) == N->getOperand(0)) {
15635           VCMPrecNode = *UI;
15636           break;
15637         }
15638 
15639       // If there is no VCMP_rec node, or if the flag value has a single use,
15640       // don't transform this.
15641       if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
15642         break;
15643 
15644       // Look at the (necessarily single) use of the flag value.  If it has a
15645       // chain, this transformation is more complex.  Note that multiple things
15646       // could use the value result, which we should ignore.
15647       SDNode *FlagUser = nullptr;
15648       for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
15649            FlagUser == nullptr; ++UI) {
15650         assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
15651         SDNode *User = *UI;
15652         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
15653           if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
15654             FlagUser = User;
15655             break;
15656           }
15657         }
15658       }
15659 
15660       // If the user is a MFOCRF instruction, we know this is safe.
15661       // Otherwise we give up for right now.
15662       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
15663         return SDValue(VCMPrecNode, 0);
15664     }
15665     break;
15666   case ISD::BRCOND: {
15667     SDValue Cond = N->getOperand(1);
15668     SDValue Target = N->getOperand(2);
15669 
15670     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15671         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
15672           Intrinsic::loop_decrement) {
15673 
15674       // We now need to make the intrinsic dead (it cannot be instruction
15675       // selected).
15676       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
15677       assert(Cond.getNode()->hasOneUse() &&
15678              "Counter decrement has more than one use");
15679 
15680       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
15681                          N->getOperand(0), Target);
15682     }
15683   }
15684   break;
15685   case ISD::BR_CC: {
15686     // If this is a branch on an altivec predicate comparison, lower this so
15687     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
15688     // lowering is done pre-legalize, because the legalizer lowers the predicate
15689     // compare down to code that is difficult to reassemble.
15690     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15691     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
15692 
15693     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
15694     // value. If so, pass-through the AND to get to the intrinsic.
15695     if (LHS.getOpcode() == ISD::AND &&
15696         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15697         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
15698           Intrinsic::loop_decrement &&
15699         isa<ConstantSDNode>(LHS.getOperand(1)) &&
15700         !isNullConstant(LHS.getOperand(1)))
15701       LHS = LHS.getOperand(0);
15702 
15703     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
15704         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
15705           Intrinsic::loop_decrement &&
15706         isa<ConstantSDNode>(RHS)) {
15707       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
15708              "Counter decrement comparison is not EQ or NE");
15709 
15710       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15711       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
15712                     (CC == ISD::SETNE && !Val);
15713 
15714       // We now need to make the intrinsic dead (it cannot be instruction
15715       // selected).
15716       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
15717       assert(LHS.getNode()->hasOneUse() &&
15718              "Counter decrement has more than one use");
15719 
15720       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
15721                          N->getOperand(0), N->getOperand(4));
15722     }
15723 
15724     int CompareOpc;
15725     bool isDot;
15726 
15727     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
15728         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
15729         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
15730       assert(isDot && "Can't compare against a vector result!");
15731 
15732       // If this is a comparison against something other than 0/1, then we know
15733       // that the condition is never/always true.
15734       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
15735       if (Val != 0 && Val != 1) {
15736         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
15737           return N->getOperand(0);
15738         // Always !=, turn it into an unconditional branch.
15739         return DAG.getNode(ISD::BR, dl, MVT::Other,
15740                            N->getOperand(0), N->getOperand(4));
15741       }
15742 
15743       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
15744 
15745       // Create the PPCISD altivec 'dot' comparison node.
15746       SDValue Ops[] = {
15747         LHS.getOperand(2),  // LHS of compare
15748         LHS.getOperand(3),  // RHS of compare
15749         DAG.getConstant(CompareOpc, dl, MVT::i32)
15750       };
15751       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
15752       SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
15753 
15754       // Unpack the result based on how the target uses it.
15755       PPC::Predicate CompOpc;
15756       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
15757       default:  // Can't happen, don't crash on invalid number though.
15758       case 0:   // Branch on the value of the EQ bit of CR6.
15759         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
15760         break;
15761       case 1:   // Branch on the inverted value of the EQ bit of CR6.
15762         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
15763         break;
15764       case 2:   // Branch on the value of the LT bit of CR6.
15765         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
15766         break;
15767       case 3:   // Branch on the inverted value of the LT bit of CR6.
15768         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
15769         break;
15770       }
15771 
15772       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
15773                          DAG.getConstant(CompOpc, dl, MVT::i32),
15774                          DAG.getRegister(PPC::CR6, MVT::i32),
15775                          N->getOperand(4), CompNode.getValue(1));
15776     }
15777     break;
15778   }
15779   case ISD::BUILD_VECTOR:
15780     return DAGCombineBuildVector(N, DCI);
15781   case ISD::ABS:
15782     return combineABS(N, DCI);
15783   case ISD::VSELECT:
15784     return combineVSelect(N, DCI);
15785   }
15786 
15787   return SDValue();
15788 }
15789 
15790 SDValue
15791 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
15792                                  SelectionDAG &DAG,
15793                                  SmallVectorImpl<SDNode *> &Created) const {
15794   // fold (sdiv X, pow2)
15795   EVT VT = N->getValueType(0);
15796   if (VT == MVT::i64 && !Subtarget.isPPC64())
15797     return SDValue();
15798   if ((VT != MVT::i32 && VT != MVT::i64) ||
15799       !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
15800     return SDValue();
15801 
15802   SDLoc DL(N);
15803   SDValue N0 = N->getOperand(0);
15804 
15805   bool IsNegPow2 = Divisor.isNegatedPowerOf2();
15806   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
15807   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
15808 
15809   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
15810   Created.push_back(Op.getNode());
15811 
15812   if (IsNegPow2) {
15813     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
15814     Created.push_back(Op.getNode());
15815   }
15816 
15817   return Op;
15818 }
15819 
15820 //===----------------------------------------------------------------------===//
15821 // Inline Assembly Support
15822 //===----------------------------------------------------------------------===//
15823 
15824 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15825                                                       KnownBits &Known,
15826                                                       const APInt &DemandedElts,
15827                                                       const SelectionDAG &DAG,
15828                                                       unsigned Depth) const {
15829   Known.resetAll();
15830   switch (Op.getOpcode()) {
15831   default: break;
15832   case PPCISD::LBRX: {
15833     // lhbrx is known to have the top bits cleared out.
15834     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
15835       Known.Zero = 0xFFFF0000;
15836     break;
15837   }
15838   case ISD::INTRINSIC_WO_CHAIN: {
15839     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
15840     default: break;
15841     case Intrinsic::ppc_altivec_vcmpbfp_p:
15842     case Intrinsic::ppc_altivec_vcmpeqfp_p:
15843     case Intrinsic::ppc_altivec_vcmpequb_p:
15844     case Intrinsic::ppc_altivec_vcmpequh_p:
15845     case Intrinsic::ppc_altivec_vcmpequw_p:
15846     case Intrinsic::ppc_altivec_vcmpequd_p:
15847     case Intrinsic::ppc_altivec_vcmpequq_p:
15848     case Intrinsic::ppc_altivec_vcmpgefp_p:
15849     case Intrinsic::ppc_altivec_vcmpgtfp_p:
15850     case Intrinsic::ppc_altivec_vcmpgtsb_p:
15851     case Intrinsic::ppc_altivec_vcmpgtsh_p:
15852     case Intrinsic::ppc_altivec_vcmpgtsw_p:
15853     case Intrinsic::ppc_altivec_vcmpgtsd_p:
15854     case Intrinsic::ppc_altivec_vcmpgtsq_p:
15855     case Intrinsic::ppc_altivec_vcmpgtub_p:
15856     case Intrinsic::ppc_altivec_vcmpgtuh_p:
15857     case Intrinsic::ppc_altivec_vcmpgtuw_p:
15858     case Intrinsic::ppc_altivec_vcmpgtud_p:
15859     case Intrinsic::ppc_altivec_vcmpgtuq_p:
15860       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
15861       break;
15862     }
15863     break;
15864   }
15865   case ISD::INTRINSIC_W_CHAIN: {
15866     switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
15867     default:
15868       break;
15869     case Intrinsic::ppc_load2r:
15870       // Top bits are cleared for load2r (which is the same as lhbrx).
15871       Known.Zero = 0xFFFF0000;
15872       break;
15873     }
15874     break;
15875   }
15876   }
15877 }
15878 
15879 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
15880   switch (Subtarget.getCPUDirective()) {
15881   default: break;
15882   case PPC::DIR_970:
15883   case PPC::DIR_PWR4:
15884   case PPC::DIR_PWR5:
15885   case PPC::DIR_PWR5X:
15886   case PPC::DIR_PWR6:
15887   case PPC::DIR_PWR6X:
15888   case PPC::DIR_PWR7:
15889   case PPC::DIR_PWR8:
15890   case PPC::DIR_PWR9:
15891   case PPC::DIR_PWR10:
15892   case PPC::DIR_PWR_FUTURE: {
15893     if (!ML)
15894       break;
15895 
15896     if (!DisableInnermostLoopAlign32) {
15897       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
15898       // so that we can decrease cache misses and branch-prediction misses.
15899       // Actual alignment of the loop will depend on the hotness check and other
15900       // logic in alignBlocks.
15901       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
15902         return Align(32);
15903     }
15904 
15905     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
15906 
15907     // For small loops (between 5 and 8 instructions), align to a 32-byte
15908     // boundary so that the entire loop fits in one instruction-cache line.
15909     uint64_t LoopSize = 0;
15910     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
15911       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
15912         LoopSize += TII->getInstSizeInBytes(*J);
15913         if (LoopSize > 32)
15914           break;
15915       }
15916 
15917     if (LoopSize > 16 && LoopSize <= 32)
15918       return Align(32);
15919 
15920     break;
15921   }
15922   }
15923 
15924   return TargetLowering::getPrefLoopAlignment(ML);
15925 }
15926 
15927 /// getConstraintType - Given a constraint, return the type of
15928 /// constraint it is for this target.
15929 PPCTargetLowering::ConstraintType
15930 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
15931   if (Constraint.size() == 1) {
15932     switch (Constraint[0]) {
15933     default: break;
15934     case 'b':
15935     case 'r':
15936     case 'f':
15937     case 'd':
15938     case 'v':
15939     case 'y':
15940       return C_RegisterClass;
15941     case 'Z':
15942       // FIXME: While Z does indicate a memory constraint, it specifically
15943       // indicates an r+r address (used in conjunction with the 'y' modifier
15944       // in the replacement string). Currently, we're forcing the base
15945       // register to be r0 in the asm printer (which is interpreted as zero)
15946       // and forming the complete address in the second register. This is
15947       // suboptimal.
15948       return C_Memory;
15949     }
15950   } else if (Constraint == "wc") { // individual CR bits.
15951     return C_RegisterClass;
15952   } else if (Constraint == "wa" || Constraint == "wd" ||
15953              Constraint == "wf" || Constraint == "ws" ||
15954              Constraint == "wi" || Constraint == "ww") {
15955     return C_RegisterClass; // VSX registers.
15956   }
15957   return TargetLowering::getConstraintType(Constraint);
15958 }
15959 
15960 /// Examine constraint type and operand type and determine a weight value.
15961 /// This object must already have been set up with the operand type
15962 /// and the current alternative constraint selected.
15963 TargetLowering::ConstraintWeight
15964 PPCTargetLowering::getSingleConstraintMatchWeight(
15965     AsmOperandInfo &info, const char *constraint) const {
15966   ConstraintWeight weight = CW_Invalid;
15967   Value *CallOperandVal = info.CallOperandVal;
15968     // If we don't have a value, we can't do a match,
15969     // but allow it at the lowest weight.
15970   if (!CallOperandVal)
15971     return CW_Default;
15972   Type *type = CallOperandVal->getType();
15973 
15974   // Look at the constraint type.
15975   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15976     return CW_Register; // an individual CR bit.
15977   else if ((StringRef(constraint) == "wa" ||
15978             StringRef(constraint) == "wd" ||
15979             StringRef(constraint) == "wf") &&
15980            type->isVectorTy())
15981     return CW_Register;
15982   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15983     return CW_Register; // just hold 64-bit integers data.
15984   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15985     return CW_Register;
15986   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15987     return CW_Register;
15988 
15989   switch (*constraint) {
15990   default:
15991     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15992     break;
15993   case 'b':
15994     if (type->isIntegerTy())
15995       weight = CW_Register;
15996     break;
15997   case 'f':
15998     if (type->isFloatTy())
15999       weight = CW_Register;
16000     break;
16001   case 'd':
16002     if (type->isDoubleTy())
16003       weight = CW_Register;
16004     break;
16005   case 'v':
16006     if (type->isVectorTy())
16007       weight = CW_Register;
16008     break;
16009   case 'y':
16010     weight = CW_Register;
16011     break;
16012   case 'Z':
16013     weight = CW_Memory;
16014     break;
16015   }
16016   return weight;
16017 }
16018 
16019 std::pair<unsigned, const TargetRegisterClass *>
16020 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
16021                                                 StringRef Constraint,
16022                                                 MVT VT) const {
16023   if (Constraint.size() == 1) {
16024     // GCC RS6000 Constraint Letters
16025     switch (Constraint[0]) {
16026     case 'b':   // R1-R31
16027       if (VT == MVT::i64 && Subtarget.isPPC64())
16028         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
16029       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
16030     case 'r':   // R0-R31
16031       if (VT == MVT::i64 && Subtarget.isPPC64())
16032         return std::make_pair(0U, &PPC::G8RCRegClass);
16033       return std::make_pair(0U, &PPC::GPRCRegClass);
16034     // 'd' and 'f' constraints are both defined to be "the floating point
16035     // registers", where one is for 32-bit and the other for 64-bit. We don't
16036     // really care overly much here so just give them all the same reg classes.
16037     case 'd':
16038     case 'f':
16039       if (Subtarget.hasSPE()) {
16040         if (VT == MVT::f32 || VT == MVT::i32)
16041           return std::make_pair(0U, &PPC::GPRCRegClass);
16042         if (VT == MVT::f64 || VT == MVT::i64)
16043           return std::make_pair(0U, &PPC::SPERCRegClass);
16044       } else {
16045         if (VT == MVT::f32 || VT == MVT::i32)
16046           return std::make_pair(0U, &PPC::F4RCRegClass);
16047         if (VT == MVT::f64 || VT == MVT::i64)
16048           return std::make_pair(0U, &PPC::F8RCRegClass);
16049       }
16050       break;
16051     case 'v':
16052       if (Subtarget.hasAltivec() && VT.isVector())
16053         return std::make_pair(0U, &PPC::VRRCRegClass);
16054       else if (Subtarget.hasVSX())
16055         // Scalars in Altivec registers only make sense with VSX.
16056         return std::make_pair(0U, &PPC::VFRCRegClass);
16057       break;
16058     case 'y':   // crrc
16059       return std::make_pair(0U, &PPC::CRRCRegClass);
16060     }
16061   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
16062     // An individual CR bit.
16063     return std::make_pair(0U, &PPC::CRBITRCRegClass);
16064   } else if ((Constraint == "wa" || Constraint == "wd" ||
16065              Constraint == "wf" || Constraint == "wi") &&
16066              Subtarget.hasVSX()) {
16067     // A VSX register for either a scalar (FP) or vector. There is no
16068     // support for single precision scalars on subtargets prior to Power8.
16069     if (VT.isVector())
16070       return std::make_pair(0U, &PPC::VSRCRegClass);
16071     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16072       return std::make_pair(0U, &PPC::VSSRCRegClass);
16073     return std::make_pair(0U, &PPC::VSFRCRegClass);
16074   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
16075     if (VT == MVT::f32 && Subtarget.hasP8Vector())
16076       return std::make_pair(0U, &PPC::VSSRCRegClass);
16077     else
16078       return std::make_pair(0U, &PPC::VSFRCRegClass);
16079   } else if (Constraint == "lr") {
16080     if (VT == MVT::i64)
16081       return std::make_pair(0U, &PPC::LR8RCRegClass);
16082     else
16083       return std::make_pair(0U, &PPC::LRRCRegClass);
16084   }
16085 
16086   // Handle special cases of physical registers that are not properly handled
16087   // by the base class.
16088   if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
16089     // If we name a VSX register, we can't defer to the base class because it
16090     // will not recognize the correct register (their names will be VSL{0-31}
16091     // and V{0-31} so they won't match). So we match them here.
16092     if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
16093       int VSNum = atoi(Constraint.data() + 3);
16094       assert(VSNum >= 0 && VSNum <= 63 &&
16095              "Attempted to access a vsr out of range");
16096       if (VSNum < 32)
16097         return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
16098       return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
16099     }
16100 
16101     // For float registers, we can't defer to the base class as it will match
16102     // the SPILLTOVSRRC class.
16103     if (Constraint.size() > 3 && Constraint[1] == 'f') {
16104       int RegNum = atoi(Constraint.data() + 2);
16105       if (RegNum > 31 || RegNum < 0)
16106         report_fatal_error("Invalid floating point register number");
16107       if (VT == MVT::f32 || VT == MVT::i32)
16108         return Subtarget.hasSPE()
16109                    ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
16110                    : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
16111       if (VT == MVT::f64 || VT == MVT::i64)
16112         return Subtarget.hasSPE()
16113                    ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
16114                    : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
16115     }
16116   }
16117 
16118   std::pair<unsigned, const TargetRegisterClass *> R =
16119       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16120 
16121   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
16122   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
16123   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
16124   // register.
16125   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
16126   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
16127   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
16128       PPC::GPRCRegClass.contains(R.first))
16129     return std::make_pair(TRI->getMatchingSuperReg(R.first,
16130                             PPC::sub_32, &PPC::G8RCRegClass),
16131                           &PPC::G8RCRegClass);
16132 
16133   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
16134   if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
16135     R.first = PPC::CR0;
16136     R.second = &PPC::CRRCRegClass;
16137   }
16138   // FIXME: This warning should ideally be emitted in the front end.
16139   const auto &TM = getTargetMachine();
16140   if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI()) {
16141     if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
16142          (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
16143         (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
16144       errs() << "warning: vector registers 20 to 32 are reserved in the "
16145                 "default AIX AltiVec ABI and cannot be used\n";
16146   }
16147 
16148   return R;
16149 }
16150 
16151 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16152 /// vector.  If it is invalid, don't add anything to Ops.
16153 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16154                                                      std::string &Constraint,
16155                                                      std::vector<SDValue>&Ops,
16156                                                      SelectionDAG &DAG) const {
16157   SDValue Result;
16158 
16159   // Only support length 1 constraints.
16160   if (Constraint.length() > 1) return;
16161 
16162   char Letter = Constraint[0];
16163   switch (Letter) {
16164   default: break;
16165   case 'I':
16166   case 'J':
16167   case 'K':
16168   case 'L':
16169   case 'M':
16170   case 'N':
16171   case 'O':
16172   case 'P': {
16173     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
16174     if (!CST) return; // Must be an immediate to match.
16175     SDLoc dl(Op);
16176     int64_t Value = CST->getSExtValue();
16177     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
16178                          // numbers are printed as such.
16179     switch (Letter) {
16180     default: llvm_unreachable("Unknown constraint letter!");
16181     case 'I':  // "I" is a signed 16-bit constant.
16182       if (isInt<16>(Value))
16183         Result = DAG.getTargetConstant(Value, dl, TCVT);
16184       break;
16185     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
16186       if (isShiftedUInt<16, 16>(Value))
16187         Result = DAG.getTargetConstant(Value, dl, TCVT);
16188       break;
16189     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
16190       if (isShiftedInt<16, 16>(Value))
16191         Result = DAG.getTargetConstant(Value, dl, TCVT);
16192       break;
16193     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
16194       if (isUInt<16>(Value))
16195         Result = DAG.getTargetConstant(Value, dl, TCVT);
16196       break;
16197     case 'M':  // "M" is a constant that is greater than 31.
16198       if (Value > 31)
16199         Result = DAG.getTargetConstant(Value, dl, TCVT);
16200       break;
16201     case 'N':  // "N" is a positive constant that is an exact power of two.
16202       if (Value > 0 && isPowerOf2_64(Value))
16203         Result = DAG.getTargetConstant(Value, dl, TCVT);
16204       break;
16205     case 'O':  // "O" is the constant zero.
16206       if (Value == 0)
16207         Result = DAG.getTargetConstant(Value, dl, TCVT);
16208       break;
16209     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
16210       if (isInt<16>(-Value))
16211         Result = DAG.getTargetConstant(Value, dl, TCVT);
16212       break;
16213     }
16214     break;
16215   }
16216   }
16217 
16218   if (Result.getNode()) {
16219     Ops.push_back(Result);
16220     return;
16221   }
16222 
16223   // Handle standard constraint letters.
16224   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16225 }
16226 
16227 // isLegalAddressingMode - Return true if the addressing mode represented
16228 // by AM is legal for this target, for a load/store of the specified type.
16229 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16230                                               const AddrMode &AM, Type *Ty,
16231                                               unsigned AS,
16232                                               Instruction *I) const {
16233   // Vector type r+i form is supported since power9 as DQ form. We don't check
16234   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
16235   // imm form is preferred and the offset can be adjusted to use imm form later
16236   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
16237   // max offset to check legal addressing mode, we should be a little aggressive
16238   // to contain other offsets for that LSRUse.
16239   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
16240     return false;
16241 
16242   // PPC allows a sign-extended 16-bit immediate field.
16243   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
16244     return false;
16245 
16246   // No global is ever allowed as a base.
16247   if (AM.BaseGV)
16248     return false;
16249 
16250   // PPC only support r+r,
16251   switch (AM.Scale) {
16252   case 0:  // "r+i" or just "i", depending on HasBaseReg.
16253     break;
16254   case 1:
16255     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
16256       return false;
16257     // Otherwise we have r+r or r+i.
16258     break;
16259   case 2:
16260     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
16261       return false;
16262     // Allow 2*r as r+r.
16263     break;
16264   default:
16265     // No other scales are supported.
16266     return false;
16267   }
16268 
16269   return true;
16270 }
16271 
16272 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
16273                                            SelectionDAG &DAG) const {
16274   MachineFunction &MF = DAG.getMachineFunction();
16275   MachineFrameInfo &MFI = MF.getFrameInfo();
16276   MFI.setReturnAddressIsTaken(true);
16277 
16278   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16279     return SDValue();
16280 
16281   SDLoc dl(Op);
16282   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16283 
16284   // Make sure the function does not optimize away the store of the RA to
16285   // the stack.
16286   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
16287   FuncInfo->setLRStoreRequired();
16288   bool isPPC64 = Subtarget.isPPC64();
16289   auto PtrVT = getPointerTy(MF.getDataLayout());
16290 
16291   if (Depth > 0) {
16292     // The link register (return address) is saved in the caller's frame
16293     // not the callee's stack frame. So we must get the caller's frame
16294     // address and load the return address at the LR offset from there.
16295     SDValue FrameAddr =
16296         DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16297                     LowerFRAMEADDR(Op, DAG), MachinePointerInfo());
16298     SDValue Offset =
16299         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
16300                         isPPC64 ? MVT::i64 : MVT::i32);
16301     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16302                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
16303                        MachinePointerInfo());
16304   }
16305 
16306   // Just load the return address off the stack.
16307   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
16308   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
16309                      MachinePointerInfo());
16310 }
16311 
16312 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
16313                                           SelectionDAG &DAG) const {
16314   SDLoc dl(Op);
16315   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16316 
16317   MachineFunction &MF = DAG.getMachineFunction();
16318   MachineFrameInfo &MFI = MF.getFrameInfo();
16319   MFI.setFrameAddressIsTaken(true);
16320 
16321   EVT PtrVT = getPointerTy(MF.getDataLayout());
16322   bool isPPC64 = PtrVT == MVT::i64;
16323 
16324   // Naked functions never have a frame pointer, and so we use r1. For all
16325   // other functions, this decision must be delayed until during PEI.
16326   unsigned FrameReg;
16327   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
16328     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
16329   else
16330     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
16331 
16332   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
16333                                          PtrVT);
16334   while (Depth--)
16335     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
16336                             FrameAddr, MachinePointerInfo());
16337   return FrameAddr;
16338 }
16339 
16340 // FIXME? Maybe this could be a TableGen attribute on some registers and
16341 // this table could be generated automatically from RegInfo.
16342 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
16343                                               const MachineFunction &MF) const {
16344   bool isPPC64 = Subtarget.isPPC64();
16345 
16346   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
16347   if (!is64Bit && VT != LLT::scalar(32))
16348     report_fatal_error("Invalid register global variable type");
16349 
16350   Register Reg = StringSwitch<Register>(RegName)
16351                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
16352                      .Case("r2", isPPC64 ? Register() : PPC::R2)
16353                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
16354                      .Default(Register());
16355 
16356   if (Reg)
16357     return Reg;
16358   report_fatal_error("Invalid register name global variable");
16359 }
16360 
16361 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
16362   // 32-bit SVR4 ABI access everything as got-indirect.
16363   if (Subtarget.is32BitELFABI())
16364     return true;
16365 
16366   // AIX accesses everything indirectly through the TOC, which is similar to
16367   // the GOT.
16368   if (Subtarget.isAIXABI())
16369     return true;
16370 
16371   CodeModel::Model CModel = getTargetMachine().getCodeModel();
16372   // If it is small or large code model, module locals are accessed
16373   // indirectly by loading their address from .toc/.got.
16374   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
16375     return true;
16376 
16377   // JumpTable and BlockAddress are accessed as got-indirect.
16378   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
16379     return true;
16380 
16381   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
16382     return Subtarget.isGVIndirectSymbol(G->getGlobal());
16383 
16384   return false;
16385 }
16386 
16387 bool
16388 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16389   // The PowerPC target isn't yet aware of offsets.
16390   return false;
16391 }
16392 
16393 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16394                                            const CallInst &I,
16395                                            MachineFunction &MF,
16396                                            unsigned Intrinsic) const {
16397   switch (Intrinsic) {
16398   case Intrinsic::ppc_atomicrmw_xchg_i128:
16399   case Intrinsic::ppc_atomicrmw_add_i128:
16400   case Intrinsic::ppc_atomicrmw_sub_i128:
16401   case Intrinsic::ppc_atomicrmw_nand_i128:
16402   case Intrinsic::ppc_atomicrmw_and_i128:
16403   case Intrinsic::ppc_atomicrmw_or_i128:
16404   case Intrinsic::ppc_atomicrmw_xor_i128:
16405   case Intrinsic::ppc_cmpxchg_i128:
16406     Info.opc = ISD::INTRINSIC_W_CHAIN;
16407     Info.memVT = MVT::i128;
16408     Info.ptrVal = I.getArgOperand(0);
16409     Info.offset = 0;
16410     Info.align = Align(16);
16411     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
16412                  MachineMemOperand::MOVolatile;
16413     return true;
16414   case Intrinsic::ppc_atomic_load_i128:
16415     Info.opc = ISD::INTRINSIC_W_CHAIN;
16416     Info.memVT = MVT::i128;
16417     Info.ptrVal = I.getArgOperand(0);
16418     Info.offset = 0;
16419     Info.align = Align(16);
16420     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16421     return true;
16422   case Intrinsic::ppc_atomic_store_i128:
16423     Info.opc = ISD::INTRINSIC_VOID;
16424     Info.memVT = MVT::i128;
16425     Info.ptrVal = I.getArgOperand(2);
16426     Info.offset = 0;
16427     Info.align = Align(16);
16428     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16429     return true;
16430   case Intrinsic::ppc_altivec_lvx:
16431   case Intrinsic::ppc_altivec_lvxl:
16432   case Intrinsic::ppc_altivec_lvebx:
16433   case Intrinsic::ppc_altivec_lvehx:
16434   case Intrinsic::ppc_altivec_lvewx:
16435   case Intrinsic::ppc_vsx_lxvd2x:
16436   case Intrinsic::ppc_vsx_lxvw4x:
16437   case Intrinsic::ppc_vsx_lxvd2x_be:
16438   case Intrinsic::ppc_vsx_lxvw4x_be:
16439   case Intrinsic::ppc_vsx_lxvl:
16440   case Intrinsic::ppc_vsx_lxvll: {
16441     EVT VT;
16442     switch (Intrinsic) {
16443     case Intrinsic::ppc_altivec_lvebx:
16444       VT = MVT::i8;
16445       break;
16446     case Intrinsic::ppc_altivec_lvehx:
16447       VT = MVT::i16;
16448       break;
16449     case Intrinsic::ppc_altivec_lvewx:
16450       VT = MVT::i32;
16451       break;
16452     case Intrinsic::ppc_vsx_lxvd2x:
16453     case Intrinsic::ppc_vsx_lxvd2x_be:
16454       VT = MVT::v2f64;
16455       break;
16456     default:
16457       VT = MVT::v4i32;
16458       break;
16459     }
16460 
16461     Info.opc = ISD::INTRINSIC_W_CHAIN;
16462     Info.memVT = VT;
16463     Info.ptrVal = I.getArgOperand(0);
16464     Info.offset = -VT.getStoreSize()+1;
16465     Info.size = 2*VT.getStoreSize()-1;
16466     Info.align = Align(1);
16467     Info.flags = MachineMemOperand::MOLoad;
16468     return true;
16469   }
16470   case Intrinsic::ppc_altivec_stvx:
16471   case Intrinsic::ppc_altivec_stvxl:
16472   case Intrinsic::ppc_altivec_stvebx:
16473   case Intrinsic::ppc_altivec_stvehx:
16474   case Intrinsic::ppc_altivec_stvewx:
16475   case Intrinsic::ppc_vsx_stxvd2x:
16476   case Intrinsic::ppc_vsx_stxvw4x:
16477   case Intrinsic::ppc_vsx_stxvd2x_be:
16478   case Intrinsic::ppc_vsx_stxvw4x_be:
16479   case Intrinsic::ppc_vsx_stxvl:
16480   case Intrinsic::ppc_vsx_stxvll: {
16481     EVT VT;
16482     switch (Intrinsic) {
16483     case Intrinsic::ppc_altivec_stvebx:
16484       VT = MVT::i8;
16485       break;
16486     case Intrinsic::ppc_altivec_stvehx:
16487       VT = MVT::i16;
16488       break;
16489     case Intrinsic::ppc_altivec_stvewx:
16490       VT = MVT::i32;
16491       break;
16492     case Intrinsic::ppc_vsx_stxvd2x:
16493     case Intrinsic::ppc_vsx_stxvd2x_be:
16494       VT = MVT::v2f64;
16495       break;
16496     default:
16497       VT = MVT::v4i32;
16498       break;
16499     }
16500 
16501     Info.opc = ISD::INTRINSIC_VOID;
16502     Info.memVT = VT;
16503     Info.ptrVal = I.getArgOperand(1);
16504     Info.offset = -VT.getStoreSize()+1;
16505     Info.size = 2*VT.getStoreSize()-1;
16506     Info.align = Align(1);
16507     Info.flags = MachineMemOperand::MOStore;
16508     return true;
16509   }
16510   default:
16511     break;
16512   }
16513 
16514   return false;
16515 }
16516 
16517 /// It returns EVT::Other if the type should be determined using generic
16518 /// target-independent logic.
16519 EVT PPCTargetLowering::getOptimalMemOpType(
16520     const MemOp &Op, const AttributeList &FuncAttributes) const {
16521   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
16522     // We should use Altivec/VSX loads and stores when available. For unaligned
16523     // addresses, unaligned VSX loads are only fast starting with the P8.
16524     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
16525         (Op.isAligned(Align(16)) ||
16526          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
16527       return MVT::v4i32;
16528   }
16529 
16530   if (Subtarget.isPPC64()) {
16531     return MVT::i64;
16532   }
16533 
16534   return MVT::i32;
16535 }
16536 
16537 /// Returns true if it is beneficial to convert a load of a constant
16538 /// to just the constant itself.
16539 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16540                                                           Type *Ty) const {
16541   assert(Ty->isIntegerTy());
16542 
16543   unsigned BitSize = Ty->getPrimitiveSizeInBits();
16544   return !(BitSize == 0 || BitSize > 64);
16545 }
16546 
16547 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16548   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16549     return false;
16550   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16551   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16552   return NumBits1 == 64 && NumBits2 == 32;
16553 }
16554 
16555 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16556   if (!VT1.isInteger() || !VT2.isInteger())
16557     return false;
16558   unsigned NumBits1 = VT1.getSizeInBits();
16559   unsigned NumBits2 = VT2.getSizeInBits();
16560   return NumBits1 == 64 && NumBits2 == 32;
16561 }
16562 
16563 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16564   // Generally speaking, zexts are not free, but they are free when they can be
16565   // folded with other operations.
16566   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
16567     EVT MemVT = LD->getMemoryVT();
16568     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
16569          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
16570         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
16571          LD->getExtensionType() == ISD::ZEXTLOAD))
16572       return true;
16573   }
16574 
16575   // FIXME: Add other cases...
16576   //  - 32-bit shifts with a zext to i64
16577   //  - zext after ctlz, bswap, etc.
16578   //  - zext after and by a constant mask
16579 
16580   return TargetLowering::isZExtFree(Val, VT2);
16581 }
16582 
16583 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
16584   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
16585          "invalid fpext types");
16586   // Extending to float128 is not free.
16587   if (DestVT == MVT::f128)
16588     return false;
16589   return true;
16590 }
16591 
16592 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16593   return isInt<16>(Imm) || isUInt<16>(Imm);
16594 }
16595 
16596 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16597   return isInt<16>(Imm) || isUInt<16>(Imm);
16598 }
16599 
16600 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, Align,
16601                                                        MachineMemOperand::Flags,
16602                                                        bool *Fast) const {
16603   if (DisablePPCUnaligned)
16604     return false;
16605 
16606   // PowerPC supports unaligned memory access for simple non-vector types.
16607   // Although accessing unaligned addresses is not as efficient as accessing
16608   // aligned addresses, it is generally more efficient than manual expansion,
16609   // and generally only traps for software emulation when crossing page
16610   // boundaries.
16611 
16612   if (!VT.isSimple())
16613     return false;
16614 
16615   if (VT.isFloatingPoint() && !VT.isVector() &&
16616       !Subtarget.allowsUnalignedFPAccess())
16617     return false;
16618 
16619   if (VT.getSimpleVT().isVector()) {
16620     if (Subtarget.hasVSX()) {
16621       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
16622           VT != MVT::v4f32 && VT != MVT::v4i32)
16623         return false;
16624     } else {
16625       return false;
16626     }
16627   }
16628 
16629   if (VT == MVT::ppcf128)
16630     return false;
16631 
16632   if (Fast)
16633     *Fast = true;
16634 
16635   return true;
16636 }
16637 
16638 bool PPCTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
16639                                                SDValue C) const {
16640   // Check integral scalar types.
16641   if (!VT.isScalarInteger())
16642     return false;
16643   if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
16644     if (!ConstNode->getAPIntValue().isSignedIntN(64))
16645       return false;
16646     // This transformation will generate >= 2 operations. But the following
16647     // cases will generate <= 2 instructions during ISEL. So exclude them.
16648     // 1. If the constant multiplier fits 16 bits, it can be handled by one
16649     // HW instruction, ie. MULLI
16650     // 2. If the multiplier after shifted fits 16 bits, an extra shift
16651     // instruction is needed than case 1, ie. MULLI and RLDICR
16652     int64_t Imm = ConstNode->getSExtValue();
16653     unsigned Shift = countTrailingZeros<uint64_t>(Imm);
16654     Imm >>= Shift;
16655     if (isInt<16>(Imm))
16656       return false;
16657     uint64_t UImm = static_cast<uint64_t>(Imm);
16658     if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
16659         isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
16660       return true;
16661   }
16662   return false;
16663 }
16664 
16665 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16666                                                    EVT VT) const {
16667   return isFMAFasterThanFMulAndFAdd(
16668       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
16669 }
16670 
16671 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
16672                                                    Type *Ty) const {
16673   switch (Ty->getScalarType()->getTypeID()) {
16674   case Type::FloatTyID:
16675   case Type::DoubleTyID:
16676     return true;
16677   case Type::FP128TyID:
16678     return Subtarget.hasP9Vector();
16679   default:
16680     return false;
16681   }
16682 }
16683 
16684 // FIXME: add more patterns which are not profitable to hoist.
16685 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
16686   if (!I->hasOneUse())
16687     return true;
16688 
16689   Instruction *User = I->user_back();
16690   assert(User && "A single use instruction with no uses.");
16691 
16692   switch (I->getOpcode()) {
16693   case Instruction::FMul: {
16694     // Don't break FMA, PowerPC prefers FMA.
16695     if (User->getOpcode() != Instruction::FSub &&
16696         User->getOpcode() != Instruction::FAdd)
16697       return true;
16698 
16699     const TargetOptions &Options = getTargetMachine().Options;
16700     const Function *F = I->getFunction();
16701     const DataLayout &DL = F->getParent()->getDataLayout();
16702     Type *Ty = User->getOperand(0)->getType();
16703 
16704     return !(
16705         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
16706         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
16707         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
16708   }
16709   case Instruction::Load: {
16710     // Don't break "store (load float*)" pattern, this pattern will be combined
16711     // to "store (load int32)" in later InstCombine pass. See function
16712     // combineLoadToOperationType. On PowerPC, loading a float point takes more
16713     // cycles than loading a 32 bit integer.
16714     LoadInst *LI = cast<LoadInst>(I);
16715     // For the loads that combineLoadToOperationType does nothing, like
16716     // ordered load, it should be profitable to hoist them.
16717     // For swifterror load, it can only be used for pointer to pointer type, so
16718     // later type check should get rid of this case.
16719     if (!LI->isUnordered())
16720       return true;
16721 
16722     if (User->getOpcode() != Instruction::Store)
16723       return true;
16724 
16725     if (I->getType()->getTypeID() != Type::FloatTyID)
16726       return true;
16727 
16728     return false;
16729   }
16730   default:
16731     return true;
16732   }
16733   return true;
16734 }
16735 
16736 const MCPhysReg *
16737 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
16738   // LR is a callee-save register, but we must treat it as clobbered by any call
16739   // site. Hence we include LR in the scratch registers, which are in turn added
16740   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
16741   // to CTR, which is used by any indirect call.
16742   static const MCPhysReg ScratchRegs[] = {
16743     PPC::X12, PPC::LR8, PPC::CTR8, 0
16744   };
16745 
16746   return ScratchRegs;
16747 }
16748 
16749 Register PPCTargetLowering::getExceptionPointerRegister(
16750     const Constant *PersonalityFn) const {
16751   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
16752 }
16753 
16754 Register PPCTargetLowering::getExceptionSelectorRegister(
16755     const Constant *PersonalityFn) const {
16756   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
16757 }
16758 
16759 bool
16760 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
16761                      EVT VT , unsigned DefinedValues) const {
16762   if (VT == MVT::v2i64)
16763     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
16764 
16765   if (Subtarget.hasVSX())
16766     return true;
16767 
16768   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
16769 }
16770 
16771 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
16772   if (DisableILPPref || Subtarget.enableMachineScheduler())
16773     return TargetLowering::getSchedulingPreference(N);
16774 
16775   return Sched::ILP;
16776 }
16777 
16778 // Create a fast isel object.
16779 FastISel *
16780 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
16781                                   const TargetLibraryInfo *LibInfo) const {
16782   return PPC::createFastISel(FuncInfo, LibInfo);
16783 }
16784 
16785 // 'Inverted' means the FMA opcode after negating one multiplicand.
16786 // For example, (fma -a b c) = (fnmsub a b c)
16787 static unsigned invertFMAOpcode(unsigned Opc) {
16788   switch (Opc) {
16789   default:
16790     llvm_unreachable("Invalid FMA opcode for PowerPC!");
16791   case ISD::FMA:
16792     return PPCISD::FNMSUB;
16793   case PPCISD::FNMSUB:
16794     return ISD::FMA;
16795   }
16796 }
16797 
16798 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
16799                                                 bool LegalOps, bool OptForSize,
16800                                                 NegatibleCost &Cost,
16801                                                 unsigned Depth) const {
16802   if (Depth > SelectionDAG::MaxRecursionDepth)
16803     return SDValue();
16804 
16805   unsigned Opc = Op.getOpcode();
16806   EVT VT = Op.getValueType();
16807   SDNodeFlags Flags = Op.getNode()->getFlags();
16808 
16809   switch (Opc) {
16810   case PPCISD::FNMSUB:
16811     if (!Op.hasOneUse() || !isTypeLegal(VT))
16812       break;
16813 
16814     const TargetOptions &Options = getTargetMachine().Options;
16815     SDValue N0 = Op.getOperand(0);
16816     SDValue N1 = Op.getOperand(1);
16817     SDValue N2 = Op.getOperand(2);
16818     SDLoc Loc(Op);
16819 
16820     NegatibleCost N2Cost = NegatibleCost::Expensive;
16821     SDValue NegN2 =
16822         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
16823 
16824     if (!NegN2)
16825       return SDValue();
16826 
16827     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
16828     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
16829     // These transformations may change sign of zeroes. For example,
16830     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
16831     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
16832       // Try and choose the cheaper one to negate.
16833       NegatibleCost N0Cost = NegatibleCost::Expensive;
16834       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
16835                                            N0Cost, Depth + 1);
16836 
16837       NegatibleCost N1Cost = NegatibleCost::Expensive;
16838       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
16839                                            N1Cost, Depth + 1);
16840 
16841       if (NegN0 && N0Cost <= N1Cost) {
16842         Cost = std::min(N0Cost, N2Cost);
16843         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
16844       } else if (NegN1) {
16845         Cost = std::min(N1Cost, N2Cost);
16846         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
16847       }
16848     }
16849 
16850     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
16851     if (isOperationLegal(ISD::FMA, VT)) {
16852       Cost = N2Cost;
16853       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
16854     }
16855 
16856     break;
16857   }
16858 
16859   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
16860                                               Cost, Depth);
16861 }
16862 
16863 // Override to enable LOAD_STACK_GUARD lowering on Linux.
16864 bool PPCTargetLowering::useLoadStackGuardNode() const {
16865   if (!Subtarget.isTargetLinux())
16866     return TargetLowering::useLoadStackGuardNode();
16867   return true;
16868 }
16869 
16870 // Override to disable global variable loading on Linux and insert AIX canary
16871 // word declaration.
16872 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
16873   if (Subtarget.isAIXABI()) {
16874     M.getOrInsertGlobal(AIXSSPCanaryWordName,
16875                         Type::getInt8PtrTy(M.getContext()));
16876     return;
16877   }
16878   if (!Subtarget.isTargetLinux())
16879     return TargetLowering::insertSSPDeclarations(M);
16880 }
16881 
16882 Value *PPCTargetLowering::getSDagStackGuard(const Module &M) const {
16883   if (Subtarget.isAIXABI())
16884     return M.getGlobalVariable(AIXSSPCanaryWordName);
16885   return TargetLowering::getSDagStackGuard(M);
16886 }
16887 
16888 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16889                                      bool ForCodeSize) const {
16890   if (!VT.isSimple() || !Subtarget.hasVSX())
16891     return false;
16892 
16893   switch(VT.getSimpleVT().SimpleTy) {
16894   default:
16895     // For FP types that are currently not supported by PPC backend, return
16896     // false. Examples: f16, f80.
16897     return false;
16898   case MVT::f32:
16899   case MVT::f64:
16900     if (Subtarget.hasPrefixInstrs()) {
16901       // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
16902       return true;
16903     }
16904     LLVM_FALLTHROUGH;
16905   case MVT::ppcf128:
16906     return Imm.isPosZero();
16907   }
16908 }
16909 
16910 // For vector shift operation op, fold
16911 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
16912 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
16913                                   SelectionDAG &DAG) {
16914   SDValue N0 = N->getOperand(0);
16915   SDValue N1 = N->getOperand(1);
16916   EVT VT = N0.getValueType();
16917   unsigned OpSizeInBits = VT.getScalarSizeInBits();
16918   unsigned Opcode = N->getOpcode();
16919   unsigned TargetOpcode;
16920 
16921   switch (Opcode) {
16922   default:
16923     llvm_unreachable("Unexpected shift operation");
16924   case ISD::SHL:
16925     TargetOpcode = PPCISD::SHL;
16926     break;
16927   case ISD::SRL:
16928     TargetOpcode = PPCISD::SRL;
16929     break;
16930   case ISD::SRA:
16931     TargetOpcode = PPCISD::SRA;
16932     break;
16933   }
16934 
16935   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
16936       N1->getOpcode() == ISD::AND)
16937     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
16938       if (Mask->getZExtValue() == OpSizeInBits - 1)
16939         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
16940 
16941   return SDValue();
16942 }
16943 
16944 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
16945   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16946     return Value;
16947 
16948   SDValue N0 = N->getOperand(0);
16949   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
16950   if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
16951       N0.getOpcode() != ISD::SIGN_EXTEND ||
16952       N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
16953       N->getValueType(0) != MVT::i64)
16954     return SDValue();
16955 
16956   // We can't save an operation here if the value is already extended, and
16957   // the existing shift is easier to combine.
16958   SDValue ExtsSrc = N0.getOperand(0);
16959   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
16960       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
16961     return SDValue();
16962 
16963   SDLoc DL(N0);
16964   SDValue ShiftBy = SDValue(CN1, 0);
16965   // We want the shift amount to be i32 on the extswli, but the shift could
16966   // have an i64.
16967   if (ShiftBy.getValueType() == MVT::i64)
16968     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
16969 
16970   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
16971                          ShiftBy);
16972 }
16973 
16974 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
16975   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16976     return Value;
16977 
16978   return SDValue();
16979 }
16980 
16981 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
16982   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
16983     return Value;
16984 
16985   return SDValue();
16986 }
16987 
16988 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
16989 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
16990 // When C is zero, the equation (addi Z, -C) can be simplified to Z
16991 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
16992 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
16993                                  const PPCSubtarget &Subtarget) {
16994   if (!Subtarget.isPPC64())
16995     return SDValue();
16996 
16997   SDValue LHS = N->getOperand(0);
16998   SDValue RHS = N->getOperand(1);
16999 
17000   auto isZextOfCompareWithConstant = [](SDValue Op) {
17001     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
17002         Op.getValueType() != MVT::i64)
17003       return false;
17004 
17005     SDValue Cmp = Op.getOperand(0);
17006     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
17007         Cmp.getOperand(0).getValueType() != MVT::i64)
17008       return false;
17009 
17010     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
17011       int64_t NegConstant = 0 - Constant->getSExtValue();
17012       // Due to the limitations of the addi instruction,
17013       // -C is required to be [-32768, 32767].
17014       return isInt<16>(NegConstant);
17015     }
17016 
17017     return false;
17018   };
17019 
17020   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
17021   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
17022 
17023   // If there is a pattern, canonicalize a zext operand to the RHS.
17024   if (LHSHasPattern && !RHSHasPattern)
17025     std::swap(LHS, RHS);
17026   else if (!LHSHasPattern && !RHSHasPattern)
17027     return SDValue();
17028 
17029   SDLoc DL(N);
17030   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
17031   SDValue Cmp = RHS.getOperand(0);
17032   SDValue Z = Cmp.getOperand(0);
17033   auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
17034   int64_t NegConstant = 0 - Constant->getSExtValue();
17035 
17036   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
17037   default: break;
17038   case ISD::SETNE: {
17039     //                                 when C == 0
17040     //                             --> addze X, (addic Z, -1).carry
17041     //                            /
17042     // add X, (zext(setne Z, C))--
17043     //                            \    when -32768 <= -C <= 32767 && C != 0
17044     //                             --> addze X, (addic (addi Z, -C), -1).carry
17045     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17046                               DAG.getConstant(NegConstant, DL, MVT::i64));
17047     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17048     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17049                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
17050     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17051                        SDValue(Addc.getNode(), 1));
17052     }
17053   case ISD::SETEQ: {
17054     //                                 when C == 0
17055     //                             --> addze X, (subfic Z, 0).carry
17056     //                            /
17057     // add X, (zext(sete  Z, C))--
17058     //                            \    when -32768 <= -C <= 32767 && C != 0
17059     //                             --> addze X, (subfic (addi Z, -C), 0).carry
17060     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
17061                               DAG.getConstant(NegConstant, DL, MVT::i64));
17062     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
17063     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
17064                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
17065     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
17066                        SDValue(Subc.getNode(), 1));
17067     }
17068   }
17069 
17070   return SDValue();
17071 }
17072 
17073 // Transform
17074 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
17075 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
17076 // In this case both C1 and C2 must be known constants.
17077 // C1+C2 must fit into a 34 bit signed integer.
17078 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
17079                                           const PPCSubtarget &Subtarget) {
17080   if (!Subtarget.isUsingPCRelativeCalls())
17081     return SDValue();
17082 
17083   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
17084   // If we find that node try to cast the Global Address and the Constant.
17085   SDValue LHS = N->getOperand(0);
17086   SDValue RHS = N->getOperand(1);
17087 
17088   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17089     std::swap(LHS, RHS);
17090 
17091   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
17092     return SDValue();
17093 
17094   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
17095   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
17096   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
17097 
17098   // Check that both casts succeeded.
17099   if (!GSDN || !ConstNode)
17100     return SDValue();
17101 
17102   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
17103   SDLoc DL(GSDN);
17104 
17105   // The signed int offset needs to fit in 34 bits.
17106   if (!isInt<34>(NewOffset))
17107     return SDValue();
17108 
17109   // The new global address is a copy of the old global address except
17110   // that it has the updated Offset.
17111   SDValue GA =
17112       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
17113                                  NewOffset, GSDN->getTargetFlags());
17114   SDValue MatPCRel =
17115       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
17116   return MatPCRel;
17117 }
17118 
17119 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
17120   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
17121     return Value;
17122 
17123   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
17124     return Value;
17125 
17126   return SDValue();
17127 }
17128 
17129 // Detect TRUNCATE operations on bitcasts of float128 values.
17130 // What we are looking for here is the situtation where we extract a subset
17131 // of bits from a 128 bit float.
17132 // This can be of two forms:
17133 // 1) BITCAST of f128 feeding TRUNCATE
17134 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
17135 // The reason this is required is because we do not have a legal i128 type
17136 // and so we want to prevent having to store the f128 and then reload part
17137 // of it.
17138 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
17139                                            DAGCombinerInfo &DCI) const {
17140   // If we are using CRBits then try that first.
17141   if (Subtarget.useCRBits()) {
17142     // Check if CRBits did anything and return that if it did.
17143     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
17144       return CRTruncValue;
17145   }
17146 
17147   SDLoc dl(N);
17148   SDValue Op0 = N->getOperand(0);
17149 
17150   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
17151   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
17152     EVT VT = N->getValueType(0);
17153     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17154       return SDValue();
17155     SDValue Sub = Op0.getOperand(0);
17156     if (Sub.getOpcode() == ISD::SUB) {
17157       SDValue SubOp0 = Sub.getOperand(0);
17158       SDValue SubOp1 = Sub.getOperand(1);
17159       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
17160           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
17161         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
17162                                SubOp1.getOperand(0),
17163                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
17164       }
17165     }
17166   }
17167 
17168   // Looking for a truncate of i128 to i64.
17169   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
17170     return SDValue();
17171 
17172   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
17173 
17174   // SRL feeding TRUNCATE.
17175   if (Op0.getOpcode() == ISD::SRL) {
17176     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
17177     // The right shift has to be by 64 bits.
17178     if (!ConstNode || ConstNode->getZExtValue() != 64)
17179       return SDValue();
17180 
17181     // Switch the element number to extract.
17182     EltToExtract = EltToExtract ? 0 : 1;
17183     // Update Op0 past the SRL.
17184     Op0 = Op0.getOperand(0);
17185   }
17186 
17187   // BITCAST feeding a TRUNCATE possibly via SRL.
17188   if (Op0.getOpcode() == ISD::BITCAST &&
17189       Op0.getValueType() == MVT::i128 &&
17190       Op0.getOperand(0).getValueType() == MVT::f128) {
17191     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
17192     return DCI.DAG.getNode(
17193         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
17194         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
17195   }
17196   return SDValue();
17197 }
17198 
17199 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
17200   SelectionDAG &DAG = DCI.DAG;
17201 
17202   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
17203   if (!ConstOpOrElement)
17204     return SDValue();
17205 
17206   // An imul is usually smaller than the alternative sequence for legal type.
17207   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
17208       isOperationLegal(ISD::MUL, N->getValueType(0)))
17209     return SDValue();
17210 
17211   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
17212     switch (this->Subtarget.getCPUDirective()) {
17213     default:
17214       // TODO: enhance the condition for subtarget before pwr8
17215       return false;
17216     case PPC::DIR_PWR8:
17217       //  type        mul     add    shl
17218       // scalar        4       1      1
17219       // vector        7       2      2
17220       return true;
17221     case PPC::DIR_PWR9:
17222     case PPC::DIR_PWR10:
17223     case PPC::DIR_PWR_FUTURE:
17224       //  type        mul     add    shl
17225       // scalar        5       2      2
17226       // vector        7       2      2
17227 
17228       // The cycle RATIO of related operations are showed as a table above.
17229       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
17230       // scalar and vector type. For 2 instrs patterns, add/sub + shl
17231       // are 4, it is always profitable; but for 3 instrs patterns
17232       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
17233       // So we should only do it for vector type.
17234       return IsAddOne && IsNeg ? VT.isVector() : true;
17235     }
17236   };
17237 
17238   EVT VT = N->getValueType(0);
17239   SDLoc DL(N);
17240 
17241   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
17242   bool IsNeg = MulAmt.isNegative();
17243   APInt MulAmtAbs = MulAmt.abs();
17244 
17245   if ((MulAmtAbs - 1).isPowerOf2()) {
17246     // (mul x, 2^N + 1) => (add (shl x, N), x)
17247     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
17248 
17249     if (!IsProfitable(IsNeg, true, VT))
17250       return SDValue();
17251 
17252     SDValue Op0 = N->getOperand(0);
17253     SDValue Op1 =
17254         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17255                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
17256     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
17257 
17258     if (!IsNeg)
17259       return Res;
17260 
17261     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
17262   } else if ((MulAmtAbs + 1).isPowerOf2()) {
17263     // (mul x, 2^N - 1) => (sub (shl x, N), x)
17264     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
17265 
17266     if (!IsProfitable(IsNeg, false, VT))
17267       return SDValue();
17268 
17269     SDValue Op0 = N->getOperand(0);
17270     SDValue Op1 =
17271         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
17272                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
17273 
17274     if (!IsNeg)
17275       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
17276     else
17277       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
17278 
17279   } else {
17280     return SDValue();
17281   }
17282 }
17283 
17284 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
17285 // in combiner since we need to check SD flags and other subtarget features.
17286 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
17287                                           DAGCombinerInfo &DCI) const {
17288   SDValue N0 = N->getOperand(0);
17289   SDValue N1 = N->getOperand(1);
17290   SDValue N2 = N->getOperand(2);
17291   SDNodeFlags Flags = N->getFlags();
17292   EVT VT = N->getValueType(0);
17293   SelectionDAG &DAG = DCI.DAG;
17294   const TargetOptions &Options = getTargetMachine().Options;
17295   unsigned Opc = N->getOpcode();
17296   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
17297   bool LegalOps = !DCI.isBeforeLegalizeOps();
17298   SDLoc Loc(N);
17299 
17300   if (!isOperationLegal(ISD::FMA, VT))
17301     return SDValue();
17302 
17303   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
17304   // since (fnmsub a b c)=-0 while c-ab=+0.
17305   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
17306     return SDValue();
17307 
17308   // (fma (fneg a) b c) => (fnmsub a b c)
17309   // (fnmsub (fneg a) b c) => (fma a b c)
17310   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
17311     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
17312 
17313   // (fma a (fneg b) c) => (fnmsub a b c)
17314   // (fnmsub a (fneg b) c) => (fma a b c)
17315   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
17316     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
17317 
17318   return SDValue();
17319 }
17320 
17321 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
17322   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
17323   if (!Subtarget.is64BitELFABI())
17324     return false;
17325 
17326   // If not a tail call then no need to proceed.
17327   if (!CI->isTailCall())
17328     return false;
17329 
17330   // If sibling calls have been disabled and tail-calls aren't guaranteed
17331   // there is no reason to duplicate.
17332   auto &TM = getTargetMachine();
17333   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
17334     return false;
17335 
17336   // Can't tail call a function called indirectly, or if it has variadic args.
17337   const Function *Callee = CI->getCalledFunction();
17338   if (!Callee || Callee->isVarArg())
17339     return false;
17340 
17341   // Make sure the callee and caller calling conventions are eligible for tco.
17342   const Function *Caller = CI->getParent()->getParent();
17343   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
17344                                            CI->getCallingConv()))
17345       return false;
17346 
17347   // If the function is local then we have a good chance at tail-calling it
17348   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
17349 }
17350 
17351 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
17352   if (!Subtarget.hasVSX())
17353     return false;
17354   if (Subtarget.hasP9Vector() && VT == MVT::f128)
17355     return true;
17356   return VT == MVT::f32 || VT == MVT::f64 ||
17357     VT == MVT::v4f32 || VT == MVT::v2f64;
17358 }
17359 
17360 bool PPCTargetLowering::
17361 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
17362   const Value *Mask = AndI.getOperand(1);
17363   // If the mask is suitable for andi. or andis. we should sink the and.
17364   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
17365     // Can't handle constants wider than 64-bits.
17366     if (CI->getBitWidth() > 64)
17367       return false;
17368     int64_t ConstVal = CI->getZExtValue();
17369     return isUInt<16>(ConstVal) ||
17370       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
17371   }
17372 
17373   // For non-constant masks, we can always use the record-form and.
17374   return true;
17375 }
17376 
17377 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
17378 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
17379 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
17380 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
17381 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
17382 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
17383   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
17384   assert(Subtarget.hasP9Altivec() &&
17385          "Only combine this when P9 altivec supported!");
17386   EVT VT = N->getValueType(0);
17387   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17388     return SDValue();
17389 
17390   SelectionDAG &DAG = DCI.DAG;
17391   SDLoc dl(N);
17392   if (N->getOperand(0).getOpcode() == ISD::SUB) {
17393     // Even for signed integers, if it's known to be positive (as signed
17394     // integer) due to zero-extended inputs.
17395     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
17396     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
17397     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
17398          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
17399         (SubOpcd1 == ISD::ZERO_EXTEND ||
17400          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
17401       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17402                          N->getOperand(0)->getOperand(0),
17403                          N->getOperand(0)->getOperand(1),
17404                          DAG.getTargetConstant(0, dl, MVT::i32));
17405     }
17406 
17407     // For type v4i32, it can be optimized with xvnegsp + vabsduw
17408     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
17409         N->getOperand(0).hasOneUse()) {
17410       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
17411                          N->getOperand(0)->getOperand(0),
17412                          N->getOperand(0)->getOperand(1),
17413                          DAG.getTargetConstant(1, dl, MVT::i32));
17414     }
17415   }
17416 
17417   return SDValue();
17418 }
17419 
17420 // For type v4i32/v8ii16/v16i8, transform
17421 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
17422 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
17423 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
17424 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
17425 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
17426                                           DAGCombinerInfo &DCI) const {
17427   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
17428   assert(Subtarget.hasP9Altivec() &&
17429          "Only combine this when P9 altivec supported!");
17430 
17431   SelectionDAG &DAG = DCI.DAG;
17432   SDLoc dl(N);
17433   SDValue Cond = N->getOperand(0);
17434   SDValue TrueOpnd = N->getOperand(1);
17435   SDValue FalseOpnd = N->getOperand(2);
17436   EVT VT = N->getOperand(1).getValueType();
17437 
17438   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
17439       FalseOpnd.getOpcode() != ISD::SUB)
17440     return SDValue();
17441 
17442   // ABSD only available for type v4i32/v8i16/v16i8
17443   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
17444     return SDValue();
17445 
17446   // At least to save one more dependent computation
17447   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
17448     return SDValue();
17449 
17450   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17451 
17452   // Can only handle unsigned comparison here
17453   switch (CC) {
17454   default:
17455     return SDValue();
17456   case ISD::SETUGT:
17457   case ISD::SETUGE:
17458     break;
17459   case ISD::SETULT:
17460   case ISD::SETULE:
17461     std::swap(TrueOpnd, FalseOpnd);
17462     break;
17463   }
17464 
17465   SDValue CmpOpnd1 = Cond.getOperand(0);
17466   SDValue CmpOpnd2 = Cond.getOperand(1);
17467 
17468   // SETCC CmpOpnd1 CmpOpnd2 cond
17469   // TrueOpnd = CmpOpnd1 - CmpOpnd2
17470   // FalseOpnd = CmpOpnd2 - CmpOpnd1
17471   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
17472       TrueOpnd.getOperand(1) == CmpOpnd2 &&
17473       FalseOpnd.getOperand(0) == CmpOpnd2 &&
17474       FalseOpnd.getOperand(1) == CmpOpnd1) {
17475     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
17476                        CmpOpnd1, CmpOpnd2,
17477                        DAG.getTargetConstant(0, dl, MVT::i32));
17478   }
17479 
17480   return SDValue();
17481 }
17482 
17483 /// getAddrModeForFlags - Based on the set of address flags, select the most
17484 /// optimal instruction format to match by.
17485 PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
17486   // This is not a node we should be handling here.
17487   if (Flags == PPC::MOF_None)
17488     return PPC::AM_None;
17489   // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
17490   for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
17491     if ((Flags & FlagSet) == FlagSet)
17492       return PPC::AM_DForm;
17493   for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
17494     if ((Flags & FlagSet) == FlagSet)
17495       return PPC::AM_DSForm;
17496   for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
17497     if ((Flags & FlagSet) == FlagSet)
17498       return PPC::AM_DQForm;
17499   for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
17500     if ((Flags & FlagSet) == FlagSet)
17501       return PPC::AM_PrefixDForm;
17502   // If no other forms are selected, return an X-Form as it is the most
17503   // general addressing mode.
17504   return PPC::AM_XForm;
17505 }
17506 
17507 /// Set alignment flags based on whether or not the Frame Index is aligned.
17508 /// Utilized when computing flags for address computation when selecting
17509 /// load and store instructions.
17510 static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
17511                                SelectionDAG &DAG) {
17512   bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
17513   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
17514   if (!FI)
17515     return;
17516   const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
17517   unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
17518   // If this is (add $FI, $S16Imm), the alignment flags are already set
17519   // based on the immediate. We just need to clear the alignment flags
17520   // if the FI alignment is weaker.
17521   if ((FrameIndexAlign % 4) != 0)
17522     FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
17523   if ((FrameIndexAlign % 16) != 0)
17524     FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
17525   // If the address is a plain FrameIndex, set alignment flags based on
17526   // FI alignment.
17527   if (!IsAdd) {
17528     if ((FrameIndexAlign % 4) == 0)
17529       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17530     if ((FrameIndexAlign % 16) == 0)
17531       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17532   }
17533 }
17534 
17535 /// Given a node, compute flags that are used for address computation when
17536 /// selecting load and store instructions. The flags computed are stored in
17537 /// FlagSet. This function takes into account whether the node is a constant,
17538 /// an ADD, OR, or a constant, and computes the address flags accordingly.
17539 static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
17540                                               SelectionDAG &DAG) {
17541   // Set the alignment flags for the node depending on if the node is
17542   // 4-byte or 16-byte aligned.
17543   auto SetAlignFlagsForImm = [&](uint64_t Imm) {
17544     if ((Imm & 0x3) == 0)
17545       FlagSet |= PPC::MOF_RPlusSImm16Mult4;
17546     if ((Imm & 0xf) == 0)
17547       FlagSet |= PPC::MOF_RPlusSImm16Mult16;
17548   };
17549 
17550   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
17551     // All 32-bit constants can be computed as LIS + Disp.
17552     const APInt &ConstImm = CN->getAPIntValue();
17553     if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
17554       FlagSet |= PPC::MOF_AddrIsSImm32;
17555       SetAlignFlagsForImm(ConstImm.getZExtValue());
17556       setAlignFlagsForFI(N, FlagSet, DAG);
17557     }
17558     if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
17559       FlagSet |= PPC::MOF_RPlusSImm34;
17560     else // Let constant materialization handle large constants.
17561       FlagSet |= PPC::MOF_NotAddNorCst;
17562   } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
17563     // This address can be represented as an addition of:
17564     // - Register + Imm16 (possibly a multiple of 4/16)
17565     // - Register + Imm34
17566     // - Register + PPCISD::Lo
17567     // - Register + Register
17568     // In any case, we won't have to match this as Base + Zero.
17569     SDValue RHS = N.getOperand(1);
17570     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
17571       const APInt &ConstImm = CN->getAPIntValue();
17572       if (ConstImm.isSignedIntN(16)) {
17573         FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
17574         SetAlignFlagsForImm(ConstImm.getZExtValue());
17575         setAlignFlagsForFI(N, FlagSet, DAG);
17576       }
17577       if (ConstImm.isSignedIntN(34))
17578         FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
17579       else
17580         FlagSet |= PPC::MOF_RPlusR; // Register.
17581     } else if (RHS.getOpcode() == PPCISD::Lo &&
17582                !cast<ConstantSDNode>(RHS.getOperand(1))->getZExtValue())
17583       FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
17584     else
17585       FlagSet |= PPC::MOF_RPlusR;
17586   } else { // The address computation is not a constant or an addition.
17587     setAlignFlagsForFI(N, FlagSet, DAG);
17588     FlagSet |= PPC::MOF_NotAddNorCst;
17589   }
17590 }
17591 
17592 static bool isPCRelNode(SDValue N) {
17593   return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
17594       isValidPCRelNode<ConstantPoolSDNode>(N) ||
17595       isValidPCRelNode<GlobalAddressSDNode>(N) ||
17596       isValidPCRelNode<JumpTableSDNode>(N) ||
17597       isValidPCRelNode<BlockAddressSDNode>(N));
17598 }
17599 
17600 /// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
17601 /// the address flags of the load/store instruction that is to be matched.
17602 unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
17603                                            SelectionDAG &DAG) const {
17604   unsigned FlagSet = PPC::MOF_None;
17605 
17606   // Compute subtarget flags.
17607   if (!Subtarget.hasP9Vector())
17608     FlagSet |= PPC::MOF_SubtargetBeforeP9;
17609   else {
17610     FlagSet |= PPC::MOF_SubtargetP9;
17611     if (Subtarget.hasPrefixInstrs())
17612       FlagSet |= PPC::MOF_SubtargetP10;
17613   }
17614   if (Subtarget.hasSPE())
17615     FlagSet |= PPC::MOF_SubtargetSPE;
17616 
17617   // Check if we have a PCRel node and return early.
17618   if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
17619     return FlagSet;
17620 
17621   // If the node is the paired load/store intrinsics, compute flags for
17622   // address computation and return early.
17623   unsigned ParentOp = Parent->getOpcode();
17624   if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
17625                                (ParentOp == ISD::INTRINSIC_VOID))) {
17626     unsigned ID = cast<ConstantSDNode>(Parent->getOperand(1))->getZExtValue();
17627     if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
17628       SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
17629                              ? Parent->getOperand(2)
17630                              : Parent->getOperand(3);
17631       computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
17632       FlagSet |= PPC::MOF_Vector;
17633       return FlagSet;
17634     }
17635   }
17636 
17637   // Mark this as something we don't want to handle here if it is atomic
17638   // or pre-increment instruction.
17639   if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
17640     if (LSB->isIndexed())
17641       return PPC::MOF_None;
17642 
17643   // Compute in-memory type flags. This is based on if there are scalars,
17644   // floats or vectors.
17645   const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
17646   assert(MN && "Parent should be a MemSDNode!");
17647   EVT MemVT = MN->getMemoryVT();
17648   unsigned Size = MemVT.getSizeInBits();
17649   if (MemVT.isScalarInteger()) {
17650     assert(Size <= 128 &&
17651            "Not expecting scalar integers larger than 16 bytes!");
17652     if (Size < 32)
17653       FlagSet |= PPC::MOF_SubWordInt;
17654     else if (Size == 32)
17655       FlagSet |= PPC::MOF_WordInt;
17656     else
17657       FlagSet |= PPC::MOF_DoubleWordInt;
17658   } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
17659     if (Size == 128)
17660       FlagSet |= PPC::MOF_Vector;
17661     else if (Size == 256) {
17662       assert(Subtarget.pairedVectorMemops() &&
17663              "256-bit vectors are only available when paired vector memops is "
17664              "enabled!");
17665       FlagSet |= PPC::MOF_Vector;
17666     } else
17667       llvm_unreachable("Not expecting illegal vectors!");
17668   } else { // Floating point type: can be scalar, f128 or vector types.
17669     if (Size == 32 || Size == 64)
17670       FlagSet |= PPC::MOF_ScalarFloat;
17671     else if (MemVT == MVT::f128 || MemVT.isVector())
17672       FlagSet |= PPC::MOF_Vector;
17673     else
17674       llvm_unreachable("Not expecting illegal scalar floats!");
17675   }
17676 
17677   // Compute flags for address computation.
17678   computeFlagsForAddressComputation(N, FlagSet, DAG);
17679 
17680   // Compute type extension flags.
17681   if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
17682     switch (LN->getExtensionType()) {
17683     case ISD::SEXTLOAD:
17684       FlagSet |= PPC::MOF_SExt;
17685       break;
17686     case ISD::EXTLOAD:
17687     case ISD::ZEXTLOAD:
17688       FlagSet |= PPC::MOF_ZExt;
17689       break;
17690     case ISD::NON_EXTLOAD:
17691       FlagSet |= PPC::MOF_NoExt;
17692       break;
17693     }
17694   } else
17695     FlagSet |= PPC::MOF_NoExt;
17696 
17697   // For integers, no extension is the same as zero extension.
17698   // We set the extension mode to zero extension so we don't have
17699   // to add separate entries in AddrModesMap for loads and stores.
17700   if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
17701     FlagSet |= PPC::MOF_ZExt;
17702     FlagSet &= ~PPC::MOF_NoExt;
17703   }
17704 
17705   // If we don't have prefixed instructions, 34-bit constants should be
17706   // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
17707   bool IsNonP1034BitConst =
17708       ((PPC::MOF_RPlusSImm34 | PPC::MOF_AddrIsSImm32 | PPC::MOF_SubtargetP10) &
17709        FlagSet) == PPC::MOF_RPlusSImm34;
17710   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
17711       IsNonP1034BitConst)
17712     FlagSet |= PPC::MOF_NotAddNorCst;
17713 
17714   return FlagSet;
17715 }
17716 
17717 /// SelectForceXFormMode - Given the specified address, force it to be
17718 /// represented as an indexed [r+r] operation (an XForm instruction).
17719 PPC::AddrMode PPCTargetLowering::SelectForceXFormMode(SDValue N, SDValue &Disp,
17720                                                       SDValue &Base,
17721                                                       SelectionDAG &DAG) const {
17722 
17723   PPC::AddrMode Mode = PPC::AM_XForm;
17724   int16_t ForceXFormImm = 0;
17725   if (provablyDisjointOr(DAG, N) &&
17726       !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
17727     Disp = N.getOperand(0);
17728     Base = N.getOperand(1);
17729     return Mode;
17730   }
17731 
17732   // If the address is the result of an add, we will utilize the fact that the
17733   // address calculation includes an implicit add.  However, we can reduce
17734   // register pressure if we do not materialize a constant just for use as the
17735   // index register.  We only get rid of the add if it is not an add of a
17736   // value and a 16-bit signed constant and both have a single use.
17737   if (N.getOpcode() == ISD::ADD &&
17738       (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
17739        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
17740     Disp = N.getOperand(0);
17741     Base = N.getOperand(1);
17742     return Mode;
17743   }
17744 
17745   // Otherwise, use R0 as the base register.
17746   Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17747                          N.getValueType());
17748   Base = N;
17749 
17750   return Mode;
17751 }
17752 
17753 bool PPCTargetLowering::splitValueIntoRegisterParts(
17754     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
17755     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
17756   EVT ValVT = Val.getValueType();
17757   // If we are splitting a scalar integer into f64 parts (i.e. so they
17758   // can be placed into VFRC registers), we need to zero extend and
17759   // bitcast the values. This will ensure the value is placed into a
17760   // VSR using direct moves or stack operations as needed.
17761   if (PartVT == MVT::f64 &&
17762       (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
17763     Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
17764     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
17765     Parts[0] = Val;
17766     return true;
17767   }
17768   return false;
17769 }
17770 
17771 SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
17772                                           SelectionDAG &DAG) const {
17773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17774   TargetLowering::CallLoweringInfo CLI(DAG);
17775   EVT RetVT = Op.getValueType();
17776   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
17777   SDValue Callee =
17778       DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
17779   bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, false);
17780   TargetLowering::ArgListTy Args;
17781   TargetLowering::ArgListEntry Entry;
17782   for (const SDValue &N : Op->op_values()) {
17783     EVT ArgVT = N.getValueType();
17784     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17785     Entry.Node = N;
17786     Entry.Ty = ArgTy;
17787     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, SignExtend);
17788     Entry.IsZExt = !Entry.IsSExt;
17789     Args.push_back(Entry);
17790   }
17791 
17792   SDValue InChain = DAG.getEntryNode();
17793   SDValue TCChain = InChain;
17794   const Function &F = DAG.getMachineFunction().getFunction();
17795   bool isTailCall =
17796       TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
17797       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
17798   if (isTailCall)
17799     InChain = TCChain;
17800   CLI.setDebugLoc(SDLoc(Op))
17801       .setChain(InChain)
17802       .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
17803       .setTailCall(isTailCall)
17804       .setSExtResult(SignExtend)
17805       .setZExtResult(!SignExtend)
17806       .setIsPostTypeLegalization(true);
17807   return TLI.LowerCallTo(CLI).first;
17808 }
17809 
17810 SDValue PPCTargetLowering::lowerLibCallBasedOnType(
17811     const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
17812     SelectionDAG &DAG) const {
17813   if (Op.getValueType() == MVT::f32)
17814     return lowerToLibCall(LibCallFloatName, Op, DAG);
17815 
17816   if (Op.getValueType() == MVT::f64)
17817     return lowerToLibCall(LibCallDoubleName, Op, DAG);
17818 
17819   return SDValue();
17820 }
17821 
17822 bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
17823   SDNodeFlags Flags = Op.getNode()->getFlags();
17824   return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
17825          Flags.hasNoNaNs() && Flags.hasNoInfs();
17826 }
17827 
17828 bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
17829   return Op.getNode()->getFlags().hasApproximateFuncs();
17830 }
17831 
17832 SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
17833                                             const char *LibCallFloatName,
17834                                             const char *LibCallDoubleNameFinite,
17835                                             const char *LibCallFloatNameFinite,
17836                                             SDValue Op,
17837                                             SelectionDAG &DAG) const {
17838   if (!isLowringToMASSSafe(Op))
17839     return SDValue();
17840 
17841   if (!isLowringToMASSFiniteSafe(Op))
17842     return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
17843                                    DAG);
17844 
17845   return lowerLibCallBasedOnType(LibCallFloatNameFinite,
17846                                  LibCallDoubleNameFinite, Op, DAG);
17847 }
17848 
17849 SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
17850   return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
17851                           "__xl_powf_finite", Op, DAG);
17852 }
17853 
17854 SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
17855   return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
17856                           "__xl_sinf_finite", Op, DAG);
17857 }
17858 
17859 SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
17860   return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
17861                           "__xl_cosf_finite", Op, DAG);
17862 }
17863 
17864 SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
17865   return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
17866                           "__xl_logf_finite", Op, DAG);
17867 }
17868 
17869 SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
17870   return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
17871                           "__xl_log10f_finite", Op, DAG);
17872 }
17873 
17874 SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
17875   return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
17876                           "__xl_expf_finite", Op, DAG);
17877 }
17878 
17879 // If we happen to match to an aligned D-Form, check if the Frame Index is
17880 // adequately aligned. If it is not, reset the mode to match to X-Form.
17881 static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
17882                                    PPC::AddrMode &Mode) {
17883   if (!isa<FrameIndexSDNode>(N))
17884     return;
17885   if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
17886       (Mode == PPC::AM_DQForm && !(Flags & PPC::MOF_RPlusSImm16Mult16)))
17887     Mode = PPC::AM_XForm;
17888 }
17889 
17890 /// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
17891 /// compute the address flags of the node, get the optimal address mode based
17892 /// on the flags, and set the Base and Disp based on the address mode.
17893 PPC::AddrMode PPCTargetLowering::SelectOptimalAddrMode(const SDNode *Parent,
17894                                                        SDValue N, SDValue &Disp,
17895                                                        SDValue &Base,
17896                                                        SelectionDAG &DAG,
17897                                                        MaybeAlign Align) const {
17898   SDLoc DL(Parent);
17899 
17900   // Compute the address flags.
17901   unsigned Flags = computeMOFlags(Parent, N, DAG);
17902 
17903   // Get the optimal address mode based on the Flags.
17904   PPC::AddrMode Mode = getAddrModeForFlags(Flags);
17905 
17906   // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
17907   // Select an X-Form load if it is not.
17908   setXFormForUnalignedFI(N, Flags, Mode);
17909 
17910   // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
17911   if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
17912     assert(Subtarget.isUsingPCRelativeCalls() &&
17913            "Must be using PC-Relative calls when a valid PC-Relative node is "
17914            "present!");
17915     Mode = PPC::AM_PCRel;
17916   }
17917 
17918   // Set Base and Disp accordingly depending on the address mode.
17919   switch (Mode) {
17920   case PPC::AM_DForm:
17921   case PPC::AM_DSForm:
17922   case PPC::AM_DQForm: {
17923     // This is a register plus a 16-bit immediate. The base will be the
17924     // register and the displacement will be the immediate unless it
17925     // isn't sufficiently aligned.
17926     if (Flags & PPC::MOF_RPlusSImm16) {
17927       SDValue Op0 = N.getOperand(0);
17928       SDValue Op1 = N.getOperand(1);
17929       int16_t Imm = cast<ConstantSDNode>(Op1)->getAPIntValue().getZExtValue();
17930       if (!Align || isAligned(*Align, Imm)) {
17931         Disp = DAG.getTargetConstant(Imm, DL, N.getValueType());
17932         Base = Op0;
17933         if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op0)) {
17934           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17935           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17936         }
17937         break;
17938       }
17939     }
17940     // This is a register plus the @lo relocation. The base is the register
17941     // and the displacement is the global address.
17942     else if (Flags & PPC::MOF_RPlusLo) {
17943       Disp = N.getOperand(1).getOperand(0); // The global address.
17944       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
17945              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
17946              Disp.getOpcode() == ISD::TargetConstantPool ||
17947              Disp.getOpcode() == ISD::TargetJumpTable);
17948       Base = N.getOperand(0);
17949       break;
17950     }
17951     // This is a constant address at most 32 bits. The base will be
17952     // zero or load-immediate-shifted and the displacement will be
17953     // the low 16 bits of the address.
17954     else if (Flags & PPC::MOF_AddrIsSImm32) {
17955       auto *CN = cast<ConstantSDNode>(N);
17956       EVT CNType = CN->getValueType(0);
17957       uint64_t CNImm = CN->getZExtValue();
17958       // If this address fits entirely in a 16-bit sext immediate field, codegen
17959       // this as "d, 0".
17960       int16_t Imm;
17961       if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
17962         Disp = DAG.getTargetConstant(Imm, DL, CNType);
17963         Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
17964                                CNType);
17965         break;
17966       }
17967       // Handle 32-bit sext immediate with LIS + Addr mode.
17968       if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
17969           (!Align || isAligned(*Align, CNImm))) {
17970         int32_t Addr = (int32_t)CNImm;
17971         // Otherwise, break this down into LIS + Disp.
17972         Disp = DAG.getTargetConstant((int16_t)Addr, DL, MVT::i32);
17973         Base =
17974             DAG.getTargetConstant((Addr - (int16_t)Addr) >> 16, DL, MVT::i32);
17975         uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
17976         Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
17977         break;
17978       }
17979     }
17980     // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
17981     Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
17982     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
17983       Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17984       fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
17985     } else
17986       Base = N;
17987     break;
17988   }
17989   case PPC::AM_PrefixDForm: {
17990     int64_t Imm34 = 0;
17991     unsigned Opcode = N.getOpcode();
17992     if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
17993         (isIntS34Immediate(N.getOperand(1), Imm34))) {
17994       // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
17995       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
17996       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
17997         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
17998       else
17999         Base = N.getOperand(0);
18000     } else if (isIntS34Immediate(N, Imm34)) {
18001       // The address is a 34-bit signed immediate.
18002       Disp = DAG.getTargetConstant(Imm34, DL, N.getValueType());
18003       Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
18004     }
18005     break;
18006   }
18007   case PPC::AM_PCRel: {
18008     // When selecting PC-Relative instructions, "Base" is not utilized as
18009     // we select the address as [PC+imm].
18010     Disp = N;
18011     break;
18012   }
18013   case PPC::AM_None:
18014     break;
18015   default: { // By default, X-Form is always available to be selected.
18016     // When a frame index is not aligned, we also match by XForm.
18017     FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N);
18018     Base = FI ? N : N.getOperand(1);
18019     Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
18020                                 N.getValueType())
18021               : N.getOperand(0);
18022     break;
18023   }
18024   }
18025   return Mode;
18026 }
18027 
18028 CCAssignFn *PPCTargetLowering::ccAssignFnForCall(CallingConv::ID CC,
18029                                                  bool Return,
18030                                                  bool IsVarArg) const {
18031   switch (CC) {
18032   case CallingConv::Cold:
18033     return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF_FIS);
18034   default:
18035     return CC_PPC64_ELF_FIS;
18036   }
18037 }
18038 
18039 TargetLowering::AtomicExpansionKind
18040 PPCTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18041   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18042   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18043     return AtomicExpansionKind::MaskedIntrinsic;
18044   return TargetLowering::shouldExpandAtomicRMWInIR(AI);
18045 }
18046 
18047 TargetLowering::AtomicExpansionKind
18048 PPCTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18049   unsigned Size = AI->getNewValOperand()->getType()->getPrimitiveSizeInBits();
18050   if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() && Size == 128)
18051     return AtomicExpansionKind::MaskedIntrinsic;
18052   return TargetLowering::shouldExpandAtomicCmpXchgInIR(AI);
18053 }
18054 
18055 static Intrinsic::ID
18056 getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp) {
18057   switch (BinOp) {
18058   default:
18059     llvm_unreachable("Unexpected AtomicRMW BinOp");
18060   case AtomicRMWInst::Xchg:
18061     return Intrinsic::ppc_atomicrmw_xchg_i128;
18062   case AtomicRMWInst::Add:
18063     return Intrinsic::ppc_atomicrmw_add_i128;
18064   case AtomicRMWInst::Sub:
18065     return Intrinsic::ppc_atomicrmw_sub_i128;
18066   case AtomicRMWInst::And:
18067     return Intrinsic::ppc_atomicrmw_and_i128;
18068   case AtomicRMWInst::Or:
18069     return Intrinsic::ppc_atomicrmw_or_i128;
18070   case AtomicRMWInst::Xor:
18071     return Intrinsic::ppc_atomicrmw_xor_i128;
18072   case AtomicRMWInst::Nand:
18073     return Intrinsic::ppc_atomicrmw_nand_i128;
18074   }
18075 }
18076 
18077 Value *PPCTargetLowering::emitMaskedAtomicRMWIntrinsic(
18078     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
18079     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
18080   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18081          "Only support quadword now");
18082   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18083   Type *ValTy = Incr->getType();
18084   assert(ValTy->getPrimitiveSizeInBits() == 128);
18085   Function *RMW = Intrinsic::getDeclaration(
18086       M, getIntrinsicForAtomicRMWBinOp128(AI->getOperation()));
18087   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18088   Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
18089   Value *IncrHi =
18090       Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
18091   Value *Addr =
18092       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18093   Value *LoHi = Builder.CreateCall(RMW, {Addr, IncrLo, IncrHi});
18094   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18095   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18096   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18097   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18098   return Builder.CreateOr(
18099       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18100 }
18101 
18102 Value *PPCTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
18103     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
18104     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
18105   assert(EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics() &&
18106          "Only support quadword now");
18107   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18108   Type *ValTy = CmpVal->getType();
18109   assert(ValTy->getPrimitiveSizeInBits() == 128);
18110   Function *IntCmpXchg =
18111       Intrinsic::getDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
18112   Type *Int64Ty = Type::getInt64Ty(M->getContext());
18113   Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
18114   Value *CmpHi =
18115       Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
18116   Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
18117   Value *NewHi =
18118       Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
18119   Value *Addr =
18120       Builder.CreateBitCast(AlignedAddr, Type::getInt8PtrTy(M->getContext()));
18121   emitLeadingFence(Builder, CI, Ord);
18122   Value *LoHi =
18123       Builder.CreateCall(IntCmpXchg, {Addr, CmpLo, CmpHi, NewLo, NewHi});
18124   emitTrailingFence(Builder, CI, Ord);
18125   Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18126   Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18127   Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18128   Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18129   return Builder.CreateOr(
18130       Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
18131 }
18132