1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> EnablePPCPCRelTLS(
125     "enable-ppc-pcrel-tls",
126     cl::desc("enable the use of PC relative memops in TLS instructions on PPC"),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
226                          isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230     } else {
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
232       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
233     }
234 
235     // PowerPC does not support direct load/store of condition registers.
236     setOperationAction(ISD::LOAD, MVT::i1, Custom);
237     setOperationAction(ISD::STORE, MVT::i1, Custom);
238 
239     // FIXME: Remove this once the ANDI glue bug is fixed:
240     if (ANDIGlueBug)
241       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
242 
243     for (MVT VT : MVT::integer_valuetypes()) {
244       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
245       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
246       setTruncStoreAction(VT, MVT::i1, Expand);
247     }
248 
249     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
250   }
251 
252   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
253   // PPC (the libcall is not available).
254   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
255   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
256 
257   // We do not currently implement these libm ops for PowerPC.
258   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
260   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
261   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
262   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
263   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
264 
265   // PowerPC has no SREM/UREM instructions unless we are on P9
266   // On P9 we may use a hardware instruction to compute the remainder.
267   // When the result of both the remainder and the division is required it is
268   // more efficient to compute the remainder from the result of the division
269   // rather than use the remainder instruction. The instructions are legalized
270   // directly because the DivRemPairsPass performs the transformation at the IR
271   // level.
272   if (Subtarget.isISA3_0()) {
273     setOperationAction(ISD::SREM, MVT::i32, Legal);
274     setOperationAction(ISD::UREM, MVT::i32, Legal);
275     setOperationAction(ISD::SREM, MVT::i64, Legal);
276     setOperationAction(ISD::UREM, MVT::i64, Legal);
277   } else {
278     setOperationAction(ISD::SREM, MVT::i32, Expand);
279     setOperationAction(ISD::UREM, MVT::i32, Expand);
280     setOperationAction(ISD::SREM, MVT::i64, Expand);
281     setOperationAction(ISD::UREM, MVT::i64, Expand);
282   }
283 
284   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
285   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
286   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
287   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
288   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
289   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
290   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
291   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
292   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
293 
294   // Handle constrained floating-point operations of scalar.
295   // TODO: Handle SPE specific operation.
296   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
297   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
298   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
299   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
300   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
301   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
302 
303   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
304   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
305   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
306   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
307   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
308   if (Subtarget.hasVSX())
309     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
310 
311   if (Subtarget.hasFSQRT()) {
312     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
314   }
315 
316   if (Subtarget.hasFPRND()) {
317     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
318     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
319     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
320     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
321 
322     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
323     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
324     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
325     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
326   }
327 
328   // We don't support sin/cos/sqrt/fmod/pow
329   setOperationAction(ISD::FSIN , MVT::f64, Expand);
330   setOperationAction(ISD::FCOS , MVT::f64, Expand);
331   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
332   setOperationAction(ISD::FREM , MVT::f64, Expand);
333   setOperationAction(ISD::FPOW , MVT::f64, Expand);
334   setOperationAction(ISD::FSIN , MVT::f32, Expand);
335   setOperationAction(ISD::FCOS , MVT::f32, Expand);
336   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
337   setOperationAction(ISD::FREM , MVT::f32, Expand);
338   setOperationAction(ISD::FPOW , MVT::f32, Expand);
339   if (Subtarget.hasSPE()) {
340     setOperationAction(ISD::FMA  , MVT::f64, Expand);
341     setOperationAction(ISD::FMA  , MVT::f32, Expand);
342   } else {
343     setOperationAction(ISD::FMA  , MVT::f64, Legal);
344     setOperationAction(ISD::FMA  , MVT::f32, Legal);
345   }
346 
347   if (Subtarget.hasSPE())
348     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
349 
350   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
351 
352   // If we're enabling GP optimizations, use hardware square root
353   if (!Subtarget.hasFSQRT() &&
354       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
355         Subtarget.hasFRE()))
356     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
357 
358   if (!Subtarget.hasFSQRT() &&
359       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
360         Subtarget.hasFRES()))
361     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
362 
363   if (Subtarget.hasFCPSGN()) {
364     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
365     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
366   } else {
367     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
368     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
369   }
370 
371   if (Subtarget.hasFPRND()) {
372     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
373     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
374     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
375     setOperationAction(ISD::FROUND, MVT::f64, Legal);
376 
377     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
378     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
379     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
380     setOperationAction(ISD::FROUND, MVT::f32, Legal);
381   }
382 
383   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
384   // to speed up scalar BSWAP64.
385   // CTPOP or CTTZ were introduced in P8/P9 respectively
386   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
387   if (Subtarget.hasP9Vector())
388     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
389   else
390     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
391   if (Subtarget.isISA3_0()) {
392     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
393     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
394   } else {
395     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
396     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
397   }
398 
399   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
400     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
401     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
402   } else {
403     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
404     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
405   }
406 
407   // PowerPC does not have ROTR
408   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
409   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
410 
411   if (!Subtarget.useCRBits()) {
412     // PowerPC does not have Select
413     setOperationAction(ISD::SELECT, MVT::i32, Expand);
414     setOperationAction(ISD::SELECT, MVT::i64, Expand);
415     setOperationAction(ISD::SELECT, MVT::f32, Expand);
416     setOperationAction(ISD::SELECT, MVT::f64, Expand);
417   }
418 
419   // PowerPC wants to turn select_cc of FP into fsel when possible.
420   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
421   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
422 
423   // PowerPC wants to optimize integer setcc a bit
424   if (!Subtarget.useCRBits())
425     setOperationAction(ISD::SETCC, MVT::i32, Custom);
426 
427   if (Subtarget.hasFPU()) {
428     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
429     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
431 
432     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
433     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
435   }
436 
437   // PowerPC does not have BRCOND which requires SetCC
438   if (!Subtarget.useCRBits())
439     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
440 
441   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
442 
443   if (Subtarget.hasSPE()) {
444     // SPE has built-in conversions
445     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
446     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
447     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
448     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
449     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
450     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
451   } else {
452     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
453     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
454 
455     // PowerPC does not have [U|S]INT_TO_FP
456     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
457     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
458   }
459 
460   if (Subtarget.hasDirectMove() && isPPC64) {
461     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
462     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
463     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
464     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
465     if (TM.Options.UnsafeFPMath) {
466       setOperationAction(ISD::LRINT, MVT::f64, Legal);
467       setOperationAction(ISD::LRINT, MVT::f32, Legal);
468       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
469       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
470       setOperationAction(ISD::LROUND, MVT::f64, Legal);
471       setOperationAction(ISD::LROUND, MVT::f32, Legal);
472       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
473       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
474     }
475   } else {
476     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
477     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
478     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
479     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
480   }
481 
482   // We cannot sextinreg(i1).  Expand to shifts.
483   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
484 
485   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
486   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
487   // support continuation, user-level threading, and etc.. As a result, no
488   // other SjLj exception interfaces are implemented and please don't build
489   // your own exception handling based on them.
490   // LLVM/Clang supports zero-cost DWARF exception handling.
491   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
492   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
493 
494   // We want to legalize GlobalAddress and ConstantPool nodes into the
495   // appropriate instructions to materialize the address.
496   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
497   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
498   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
499   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
500   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
501   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
502   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
503   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
504   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
505   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
506 
507   // TRAP is legal.
508   setOperationAction(ISD::TRAP, MVT::Other, Legal);
509 
510   // TRAMPOLINE is custom lowered.
511   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
512   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
513 
514   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
515   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
516 
517   if (Subtarget.is64BitELFABI()) {
518     // VAARG always uses double-word chunks, so promote anything smaller.
519     setOperationAction(ISD::VAARG, MVT::i1, Promote);
520     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
521     setOperationAction(ISD::VAARG, MVT::i8, Promote);
522     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
523     setOperationAction(ISD::VAARG, MVT::i16, Promote);
524     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
525     setOperationAction(ISD::VAARG, MVT::i32, Promote);
526     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
527     setOperationAction(ISD::VAARG, MVT::Other, Expand);
528   } else if (Subtarget.is32BitELFABI()) {
529     // VAARG is custom lowered with the 32-bit SVR4 ABI.
530     setOperationAction(ISD::VAARG, MVT::Other, Custom);
531     setOperationAction(ISD::VAARG, MVT::i64, Custom);
532   } else
533     setOperationAction(ISD::VAARG, MVT::Other, Expand);
534 
535   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
536   if (Subtarget.is32BitELFABI())
537     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
538   else
539     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
540 
541   // Use the default implementation.
542   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
543   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
544   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
545   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
546   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
547   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
548   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
549   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
550   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
551 
552   // We want to custom lower some of our intrinsics.
553   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
554 
555   // To handle counter-based loop conditions.
556   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
557 
558   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
559   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
560   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
561   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
562 
563   // Comparisons that require checking two conditions.
564   if (Subtarget.hasSPE()) {
565     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
566     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
567     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
568     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
569   }
570   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
571   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
572   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
573   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
574   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
575   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
576   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
577   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
578   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
579   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
580   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
581   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
582 
583   if (Subtarget.has64BitSupport()) {
584     // They also have instructions for converting between i64 and fp.
585     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
586     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
587     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
588     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
589     // This is just the low 32 bits of a (signed) fp->i64 conversion.
590     // We cannot do this with Promote because i64 is not a legal type.
591     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
592 
593     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
594       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
595   } else {
596     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
597     if (Subtarget.hasSPE()) {
598       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
599       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
600     } else
601       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
602   }
603 
604   // With the instructions enabled under FPCVT, we can do everything.
605   if (Subtarget.hasFPCVT()) {
606     if (Subtarget.has64BitSupport()) {
607       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
608       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
609       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
610       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
611     }
612 
613     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
614     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
615     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
616     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
617   }
618 
619   if (Subtarget.use64BitRegs()) {
620     // 64-bit PowerPC implementations can support i64 types directly
621     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
622     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
623     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
624     // 64-bit PowerPC wants to expand i128 shifts itself.
625     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
626     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
627     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
628   } else {
629     // 32-bit PowerPC wants to expand i64 shifts itself.
630     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
631     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
632     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
633   }
634 
635   // PowerPC has better expansions for funnel shifts than the generic
636   // TargetLowering::expandFunnelShift.
637   if (Subtarget.has64BitSupport()) {
638     setOperationAction(ISD::FSHL, MVT::i64, Custom);
639     setOperationAction(ISD::FSHR, MVT::i64, Custom);
640   }
641   setOperationAction(ISD::FSHL, MVT::i32, Custom);
642   setOperationAction(ISD::FSHR, MVT::i32, Custom);
643 
644   if (Subtarget.hasVSX()) {
645     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
646     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
647     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
648     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
649   }
650 
651   if (Subtarget.hasAltivec()) {
652     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
653       setOperationAction(ISD::SADDSAT, VT, Legal);
654       setOperationAction(ISD::SSUBSAT, VT, Legal);
655       setOperationAction(ISD::UADDSAT, VT, Legal);
656       setOperationAction(ISD::USUBSAT, VT, Legal);
657     }
658     // First set operation action for all vector types to expand. Then we
659     // will selectively turn on ones that can be effectively codegen'd.
660     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
661       // add/sub are legal for all supported vector VT's.
662       setOperationAction(ISD::ADD, VT, Legal);
663       setOperationAction(ISD::SUB, VT, Legal);
664 
665       // For v2i64, these are only valid with P8Vector. This is corrected after
666       // the loop.
667       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
668         setOperationAction(ISD::SMAX, VT, Legal);
669         setOperationAction(ISD::SMIN, VT, Legal);
670         setOperationAction(ISD::UMAX, VT, Legal);
671         setOperationAction(ISD::UMIN, VT, Legal);
672       }
673       else {
674         setOperationAction(ISD::SMAX, VT, Expand);
675         setOperationAction(ISD::SMIN, VT, Expand);
676         setOperationAction(ISD::UMAX, VT, Expand);
677         setOperationAction(ISD::UMIN, VT, Expand);
678       }
679 
680       if (Subtarget.hasVSX()) {
681         setOperationAction(ISD::FMAXNUM, VT, Legal);
682         setOperationAction(ISD::FMINNUM, VT, Legal);
683       }
684 
685       // Vector instructions introduced in P8
686       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
687         setOperationAction(ISD::CTPOP, VT, Legal);
688         setOperationAction(ISD::CTLZ, VT, Legal);
689       }
690       else {
691         setOperationAction(ISD::CTPOP, VT, Expand);
692         setOperationAction(ISD::CTLZ, VT, Expand);
693       }
694 
695       // Vector instructions introduced in P9
696       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
697         setOperationAction(ISD::CTTZ, VT, Legal);
698       else
699         setOperationAction(ISD::CTTZ, VT, Expand);
700 
701       // We promote all shuffles to v16i8.
702       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
703       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
704 
705       // We promote all non-typed operations to v4i32.
706       setOperationAction(ISD::AND   , VT, Promote);
707       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
708       setOperationAction(ISD::OR    , VT, Promote);
709       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
710       setOperationAction(ISD::XOR   , VT, Promote);
711       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
712       setOperationAction(ISD::LOAD  , VT, Promote);
713       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
714       setOperationAction(ISD::SELECT, VT, Promote);
715       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
716       setOperationAction(ISD::VSELECT, VT, Legal);
717       setOperationAction(ISD::SELECT_CC, VT, Promote);
718       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
719       setOperationAction(ISD::STORE, VT, Promote);
720       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
721 
722       // No other operations are legal.
723       setOperationAction(ISD::MUL , VT, Expand);
724       setOperationAction(ISD::SDIV, VT, Expand);
725       setOperationAction(ISD::SREM, VT, Expand);
726       setOperationAction(ISD::UDIV, VT, Expand);
727       setOperationAction(ISD::UREM, VT, Expand);
728       setOperationAction(ISD::FDIV, VT, Expand);
729       setOperationAction(ISD::FREM, VT, Expand);
730       setOperationAction(ISD::FNEG, VT, Expand);
731       setOperationAction(ISD::FSQRT, VT, Expand);
732       setOperationAction(ISD::FLOG, VT, Expand);
733       setOperationAction(ISD::FLOG10, VT, Expand);
734       setOperationAction(ISD::FLOG2, VT, Expand);
735       setOperationAction(ISD::FEXP, VT, Expand);
736       setOperationAction(ISD::FEXP2, VT, Expand);
737       setOperationAction(ISD::FSIN, VT, Expand);
738       setOperationAction(ISD::FCOS, VT, Expand);
739       setOperationAction(ISD::FABS, VT, Expand);
740       setOperationAction(ISD::FFLOOR, VT, Expand);
741       setOperationAction(ISD::FCEIL,  VT, Expand);
742       setOperationAction(ISD::FTRUNC, VT, Expand);
743       setOperationAction(ISD::FRINT,  VT, Expand);
744       setOperationAction(ISD::FNEARBYINT, VT, Expand);
745       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
746       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
748       setOperationAction(ISD::MULHU, VT, Expand);
749       setOperationAction(ISD::MULHS, VT, Expand);
750       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
751       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
752       setOperationAction(ISD::UDIVREM, VT, Expand);
753       setOperationAction(ISD::SDIVREM, VT, Expand);
754       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
755       setOperationAction(ISD::FPOW, VT, Expand);
756       setOperationAction(ISD::BSWAP, VT, Expand);
757       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
758       setOperationAction(ISD::ROTL, VT, Expand);
759       setOperationAction(ISD::ROTR, VT, Expand);
760 
761       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
762         setTruncStoreAction(VT, InnerVT, Expand);
763         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
764         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
765         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
766       }
767     }
768     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
769     if (!Subtarget.hasP8Vector()) {
770       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
771       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
772       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
773       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
774     }
775 
776     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
777       setOperationAction(ISD::ABS, VT, Custom);
778 
779     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
780     // with merges, splats, etc.
781     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
782 
783     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
784     // are cheap, so handle them before they get expanded to scalar.
785     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
786     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
787     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
788     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
789     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
790 
791     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
792     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
793     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
794     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
795     setOperationAction(ISD::SELECT, MVT::v4i32,
796                        Subtarget.useCRBits() ? Legal : Expand);
797     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
798     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
799     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
800     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
801     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
802     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
803     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
804     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
805     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
806 
807     // Without hasP8Altivec set, v2i64 SMAX isn't available.
808     // But ABS custom lowering requires SMAX support.
809     if (!Subtarget.hasP8Altivec())
810       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
811 
812     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
813     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
814     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
815     if (Subtarget.hasAltivec())
816       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
817         setOperationAction(ISD::ROTL, VT, Legal);
818     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
819     if (Subtarget.hasP8Altivec())
820       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
821 
822     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
823     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
824     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
825     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
826 
827     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
828     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
829 
830     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
831       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
832       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
833     }
834 
835     if (Subtarget.hasP8Altivec())
836       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
837     else
838       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
839 
840     if (Subtarget.isISA3_1()) {
841       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
842       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
843       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
844       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
845       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
846       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
847       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
848       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
849       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
850       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
851       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
852       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
853       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
854     }
855 
856     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
857     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
858 
859     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
860     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
861 
862     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
863     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
864     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
865     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
866 
867     // Altivec does not contain unordered floating-point compare instructions
868     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
869     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
870     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
871     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
872 
873     if (Subtarget.hasVSX()) {
874       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
876       if (Subtarget.hasP8Vector()) {
877         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
878         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
879       }
880       if (Subtarget.hasDirectMove() && isPPC64) {
881         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
882         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
883         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
884         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
885         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
886         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
887         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
888         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
889       }
890       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
891 
892       // The nearbyint variants are not allowed to raise the inexact exception
893       // so we can only code-gen them with unsafe math.
894       if (TM.Options.UnsafeFPMath) {
895         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
896         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
897       }
898 
899       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
900       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
901       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
902       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
903       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
904       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
905       setOperationAction(ISD::FROUND, MVT::f64, Legal);
906       setOperationAction(ISD::FRINT, MVT::f64, Legal);
907 
908       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
909       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
910       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
911       setOperationAction(ISD::FROUND, MVT::f32, Legal);
912       setOperationAction(ISD::FRINT, MVT::f32, Legal);
913 
914       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
915       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
916 
917       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
918       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
919 
920       // Share the Altivec comparison restrictions.
921       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
922       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
923       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
924       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
925 
926       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
927       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
928 
929       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
930 
931       if (Subtarget.hasP8Vector())
932         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
933 
934       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
935 
936       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
937       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
938       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
939 
940       if (Subtarget.hasP8Altivec()) {
941         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
942         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
943         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
944 
945         // 128 bit shifts can be accomplished via 3 instructions for SHL and
946         // SRL, but not for SRA because of the instructions available:
947         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
948         // doing
949         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
950         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
951         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
952 
953         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
954       }
955       else {
956         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
957         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
958         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
959 
960         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
961 
962         // VSX v2i64 only supports non-arithmetic operations.
963         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
964         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
965       }
966 
967       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
968 
969       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
970       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
971       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
972       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
973 
974       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
975 
976       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
977       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
978       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
979       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
980 
981       // Custom handling for partial vectors of integers converted to
982       // floating point. We already have optimal handling for v2i32 through
983       // the DAG combine, so those aren't necessary.
984       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
985       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
986       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
987       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
988       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
989       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
990       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
991       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
992 
993       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
994       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
995       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
996       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
997       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
998       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
999 
1000       if (Subtarget.hasDirectMove())
1001         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1002       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1003 
1004       // Handle constrained floating-point operations of vector.
1005       // The predictor is `hasVSX` because altivec instruction has
1006       // no exception but VSX vector instruction has.
1007       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1008       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1009       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1010       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1011       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1012       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1013       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1014       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1015       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
1016       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1017       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1018       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1019       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1020 
1021       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1022       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1023       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1024       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1025       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1026       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1027       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1028       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1029       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1030       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1031       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1032       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1033       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1034 
1035       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1036     }
1037 
1038     if (Subtarget.hasP8Altivec()) {
1039       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1040       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1041     }
1042 
1043     if (Subtarget.hasP9Vector()) {
1044       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1045       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1046 
1047       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1048       // SRL, but not for SRA because of the instructions available:
1049       // VS{RL} and VS{RL}O.
1050       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1051       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1052       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1053 
1054       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1055       setOperationAction(ISD::FADD, MVT::f128, Legal);
1056       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1057       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1058       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1059       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1060       // No extending loads to f128 on PPC.
1061       for (MVT FPT : MVT::fp_valuetypes())
1062         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1063       setOperationAction(ISD::FMA, MVT::f128, Legal);
1064       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1065       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1066       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1067       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1068       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1069       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1070 
1071       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1072       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1073       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1074       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1075       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1076       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1077 
1078       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1079       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1080       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1081       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1082       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1083       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1084       // No implementation for these ops for PowerPC.
1085       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1086       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1087       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1088       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1089       setOperationAction(ISD::FREM, MVT::f128, Expand);
1090 
1091       // Handle constrained floating-point operations of fp128
1092       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1093       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1094       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1095       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1096       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1097       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1098       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1099       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1100       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1101       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1102       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1103       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1104       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1105       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1106       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1107       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1108       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1109       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1110       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1111       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1112     }
1113 
1114     if (Subtarget.hasP9Altivec()) {
1115       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1116       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1117 
1118       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1119       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1120       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1121       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1122       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1123       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1124       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1125     }
1126   }
1127 
1128   if (Subtarget.has64BitSupport())
1129     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1130 
1131   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1132 
1133   if (!isPPC64) {
1134     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1135     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1136   }
1137 
1138   setBooleanContents(ZeroOrOneBooleanContent);
1139 
1140   if (Subtarget.hasAltivec()) {
1141     // Altivec instructions set fields to all zeros or all ones.
1142     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1143   }
1144 
1145   if (!isPPC64) {
1146     // These libcalls are not available in 32-bit.
1147     setLibcallName(RTLIB::SHL_I128, nullptr);
1148     setLibcallName(RTLIB::SRL_I128, nullptr);
1149     setLibcallName(RTLIB::SRA_I128, nullptr);
1150   }
1151 
1152   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1153 
1154   // We have target-specific dag combine patterns for the following nodes:
1155   setTargetDAGCombine(ISD::ADD);
1156   setTargetDAGCombine(ISD::SHL);
1157   setTargetDAGCombine(ISD::SRA);
1158   setTargetDAGCombine(ISD::SRL);
1159   setTargetDAGCombine(ISD::MUL);
1160   setTargetDAGCombine(ISD::FMA);
1161   setTargetDAGCombine(ISD::SINT_TO_FP);
1162   setTargetDAGCombine(ISD::BUILD_VECTOR);
1163   if (Subtarget.hasFPCVT())
1164     setTargetDAGCombine(ISD::UINT_TO_FP);
1165   setTargetDAGCombine(ISD::LOAD);
1166   setTargetDAGCombine(ISD::STORE);
1167   setTargetDAGCombine(ISD::BR_CC);
1168   if (Subtarget.useCRBits())
1169     setTargetDAGCombine(ISD::BRCOND);
1170   setTargetDAGCombine(ISD::BSWAP);
1171   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1172   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1173   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1174 
1175   setTargetDAGCombine(ISD::SIGN_EXTEND);
1176   setTargetDAGCombine(ISD::ZERO_EXTEND);
1177   setTargetDAGCombine(ISD::ANY_EXTEND);
1178 
1179   setTargetDAGCombine(ISD::TRUNCATE);
1180   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1181 
1182 
1183   if (Subtarget.useCRBits()) {
1184     setTargetDAGCombine(ISD::TRUNCATE);
1185     setTargetDAGCombine(ISD::SETCC);
1186     setTargetDAGCombine(ISD::SELECT_CC);
1187   }
1188 
1189   // Use reciprocal estimates.
1190   if (TM.Options.UnsafeFPMath) {
1191     setTargetDAGCombine(ISD::FDIV);
1192     setTargetDAGCombine(ISD::FSQRT);
1193   }
1194 
1195   if (Subtarget.hasP9Altivec()) {
1196     setTargetDAGCombine(ISD::ABS);
1197     setTargetDAGCombine(ISD::VSELECT);
1198   }
1199 
1200   setLibcallName(RTLIB::LOG_F128, "logf128");
1201   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1202   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1203   setLibcallName(RTLIB::EXP_F128, "expf128");
1204   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1205   setLibcallName(RTLIB::SIN_F128, "sinf128");
1206   setLibcallName(RTLIB::COS_F128, "cosf128");
1207   setLibcallName(RTLIB::POW_F128, "powf128");
1208   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1209   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1210   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1211   setLibcallName(RTLIB::REM_F128, "fmodf128");
1212 
1213   // With 32 condition bits, we don't need to sink (and duplicate) compares
1214   // aggressively in CodeGenPrep.
1215   if (Subtarget.useCRBits()) {
1216     setHasMultipleConditionRegisters();
1217     setJumpIsExpensive();
1218   }
1219 
1220   setMinFunctionAlignment(Align(4));
1221 
1222   switch (Subtarget.getCPUDirective()) {
1223   default: break;
1224   case PPC::DIR_970:
1225   case PPC::DIR_A2:
1226   case PPC::DIR_E500:
1227   case PPC::DIR_E500mc:
1228   case PPC::DIR_E5500:
1229   case PPC::DIR_PWR4:
1230   case PPC::DIR_PWR5:
1231   case PPC::DIR_PWR5X:
1232   case PPC::DIR_PWR6:
1233   case PPC::DIR_PWR6X:
1234   case PPC::DIR_PWR7:
1235   case PPC::DIR_PWR8:
1236   case PPC::DIR_PWR9:
1237   case PPC::DIR_PWR10:
1238   case PPC::DIR_PWR_FUTURE:
1239     setPrefLoopAlignment(Align(16));
1240     setPrefFunctionAlignment(Align(16));
1241     break;
1242   }
1243 
1244   if (Subtarget.enableMachineScheduler())
1245     setSchedulingPreference(Sched::Source);
1246   else
1247     setSchedulingPreference(Sched::Hybrid);
1248 
1249   computeRegisterProperties(STI.getRegisterInfo());
1250 
1251   // The Freescale cores do better with aggressive inlining of memcpy and
1252   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1253   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1254       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1255     MaxStoresPerMemset = 32;
1256     MaxStoresPerMemsetOptSize = 16;
1257     MaxStoresPerMemcpy = 32;
1258     MaxStoresPerMemcpyOptSize = 8;
1259     MaxStoresPerMemmove = 32;
1260     MaxStoresPerMemmoveOptSize = 8;
1261   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1262     // The A2 also benefits from (very) aggressive inlining of memcpy and
1263     // friends. The overhead of a the function call, even when warm, can be
1264     // over one hundred cycles.
1265     MaxStoresPerMemset = 128;
1266     MaxStoresPerMemcpy = 128;
1267     MaxStoresPerMemmove = 128;
1268     MaxLoadsPerMemcmp = 128;
1269   } else {
1270     MaxLoadsPerMemcmp = 8;
1271     MaxLoadsPerMemcmpOptSize = 4;
1272   }
1273 
1274   // Let the subtarget (CPU) decide if a predictable select is more expensive
1275   // than the corresponding branch. This information is used in CGP to decide
1276   // when to convert selects into branches.
1277   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1278 }
1279 
1280 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1281 /// the desired ByVal argument alignment.
1282 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1283   if (MaxAlign == MaxMaxAlign)
1284     return;
1285   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1286     if (MaxMaxAlign >= 32 &&
1287         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1288       MaxAlign = Align(32);
1289     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1290              MaxAlign < 16)
1291       MaxAlign = Align(16);
1292   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1293     Align EltAlign;
1294     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1295     if (EltAlign > MaxAlign)
1296       MaxAlign = EltAlign;
1297   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1298     for (auto *EltTy : STy->elements()) {
1299       Align EltAlign;
1300       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1301       if (EltAlign > MaxAlign)
1302         MaxAlign = EltAlign;
1303       if (MaxAlign == MaxMaxAlign)
1304         break;
1305     }
1306   }
1307 }
1308 
1309 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1310 /// function arguments in the caller parameter area.
1311 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1312                                                   const DataLayout &DL) const {
1313   // 16byte and wider vectors are passed on 16byte boundary.
1314   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1315   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1316   if (Subtarget.hasAltivec())
1317     getMaxByValAlign(Ty, Alignment, Align(16));
1318   return Alignment.value();
1319 }
1320 
1321 bool PPCTargetLowering::useSoftFloat() const {
1322   return Subtarget.useSoftFloat();
1323 }
1324 
1325 bool PPCTargetLowering::hasSPE() const {
1326   return Subtarget.hasSPE();
1327 }
1328 
1329 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1330   return VT.isScalarInteger();
1331 }
1332 
1333 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1334 /// type is cheaper than a multiply followed by a shift.
1335 /// This is true for words and doublewords on 64-bit PowerPC.
1336 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1337   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1338                               isOperationLegal(ISD::MULHU, Type)))
1339     return true;
1340   return TargetLowering::isMulhCheaperThanMulShift(Type);
1341 }
1342 
1343 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1344   switch ((PPCISD::NodeType)Opcode) {
1345   case PPCISD::FIRST_NUMBER:    break;
1346   case PPCISD::FSEL:            return "PPCISD::FSEL";
1347   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1348   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1349   case PPCISD::FCFID:           return "PPCISD::FCFID";
1350   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1351   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1352   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1353   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1354   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1355   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1356   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1357   case PPCISD::FP_TO_UINT_IN_VSR:
1358                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1359   case PPCISD::FP_TO_SINT_IN_VSR:
1360                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1361   case PPCISD::FRE:             return "PPCISD::FRE";
1362   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1363   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1364   case PPCISD::VPERM:           return "PPCISD::VPERM";
1365   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1366   case PPCISD::XXSPLTI_SP_TO_DP:
1367     return "PPCISD::XXSPLTI_SP_TO_DP";
1368   case PPCISD::XXSPLTI32DX:
1369     return "PPCISD::XXSPLTI32DX";
1370   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1371   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1372   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1373   case PPCISD::CMPB:            return "PPCISD::CMPB";
1374   case PPCISD::Hi:              return "PPCISD::Hi";
1375   case PPCISD::Lo:              return "PPCISD::Lo";
1376   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1377   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1378   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1379   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1380   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1381   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1382   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1383   case PPCISD::SRL:             return "PPCISD::SRL";
1384   case PPCISD::SRA:             return "PPCISD::SRA";
1385   case PPCISD::SHL:             return "PPCISD::SHL";
1386   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1387   case PPCISD::CALL:            return "PPCISD::CALL";
1388   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1389   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1390   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1391   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1392   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1393   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1394   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1395   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1396   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1397   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1398   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1399   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1400   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1401   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1402   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1403   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1404     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1405   case PPCISD::ANDI_rec_1_EQ_BIT:
1406     return "PPCISD::ANDI_rec_1_EQ_BIT";
1407   case PPCISD::ANDI_rec_1_GT_BIT:
1408     return "PPCISD::ANDI_rec_1_GT_BIT";
1409   case PPCISD::VCMP:            return "PPCISD::VCMP";
1410   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1411   case PPCISD::LBRX:            return "PPCISD::LBRX";
1412   case PPCISD::STBRX:           return "PPCISD::STBRX";
1413   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1414   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1415   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1416   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1417   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1418   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1419   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1420   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1421   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1422   case PPCISD::ST_VSR_SCAL_INT:
1423                                 return "PPCISD::ST_VSR_SCAL_INT";
1424   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1425   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1426   case PPCISD::BDZ:             return "PPCISD::BDZ";
1427   case PPCISD::MFFS:            return "PPCISD::MFFS";
1428   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1429   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1430   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1431   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1432   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1433   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1434   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1435   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1436   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1437   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1438   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1439   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1440   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1441   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1442   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1443   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1444   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1445   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1446   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1447   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1448   case PPCISD::SC:              return "PPCISD::SC";
1449   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1450   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1451   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1452   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1453   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1454   case PPCISD::VABSD:           return "PPCISD::VABSD";
1455   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1456   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1457   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1458   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1459   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1460   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1461   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1462   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1463   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1464   }
1465   return nullptr;
1466 }
1467 
1468 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1469                                           EVT VT) const {
1470   if (!VT.isVector())
1471     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1472 
1473   return VT.changeVectorElementTypeToInteger();
1474 }
1475 
1476 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1477   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1478   return true;
1479 }
1480 
1481 //===----------------------------------------------------------------------===//
1482 // Node matching predicates, for use by the tblgen matching code.
1483 //===----------------------------------------------------------------------===//
1484 
1485 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1486 static bool isFloatingPointZero(SDValue Op) {
1487   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1488     return CFP->getValueAPF().isZero();
1489   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1490     // Maybe this has already been legalized into the constant pool?
1491     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1492       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1493         return CFP->getValueAPF().isZero();
1494   }
1495   return false;
1496 }
1497 
1498 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1499 /// true if Op is undef or if it matches the specified value.
1500 static bool isConstantOrUndef(int Op, int Val) {
1501   return Op < 0 || Op == Val;
1502 }
1503 
1504 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1505 /// VPKUHUM instruction.
1506 /// The ShuffleKind distinguishes between big-endian operations with
1507 /// two different inputs (0), either-endian operations with two identical
1508 /// inputs (1), and little-endian operations with two different inputs (2).
1509 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1510 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1511                                SelectionDAG &DAG) {
1512   bool IsLE = DAG.getDataLayout().isLittleEndian();
1513   if (ShuffleKind == 0) {
1514     if (IsLE)
1515       return false;
1516     for (unsigned i = 0; i != 16; ++i)
1517       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1518         return false;
1519   } else if (ShuffleKind == 2) {
1520     if (!IsLE)
1521       return false;
1522     for (unsigned i = 0; i != 16; ++i)
1523       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1524         return false;
1525   } else if (ShuffleKind == 1) {
1526     unsigned j = IsLE ? 0 : 1;
1527     for (unsigned i = 0; i != 8; ++i)
1528       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1529           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1530         return false;
1531   }
1532   return true;
1533 }
1534 
1535 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1536 /// VPKUWUM instruction.
1537 /// The ShuffleKind distinguishes between big-endian operations with
1538 /// two different inputs (0), either-endian operations with two identical
1539 /// inputs (1), and little-endian operations with two different inputs (2).
1540 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1541 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1542                                SelectionDAG &DAG) {
1543   bool IsLE = DAG.getDataLayout().isLittleEndian();
1544   if (ShuffleKind == 0) {
1545     if (IsLE)
1546       return false;
1547     for (unsigned i = 0; i != 16; i += 2)
1548       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1549           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1550         return false;
1551   } else if (ShuffleKind == 2) {
1552     if (!IsLE)
1553       return false;
1554     for (unsigned i = 0; i != 16; i += 2)
1555       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1556           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1557         return false;
1558   } else if (ShuffleKind == 1) {
1559     unsigned j = IsLE ? 0 : 2;
1560     for (unsigned i = 0; i != 8; i += 2)
1561       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1562           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1563           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1564           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1565         return false;
1566   }
1567   return true;
1568 }
1569 
1570 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1571 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1572 /// current subtarget.
1573 ///
1574 /// The ShuffleKind distinguishes between big-endian operations with
1575 /// two different inputs (0), either-endian operations with two identical
1576 /// inputs (1), and little-endian operations with two different inputs (2).
1577 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1578 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1579                                SelectionDAG &DAG) {
1580   const PPCSubtarget& Subtarget =
1581       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1582   if (!Subtarget.hasP8Vector())
1583     return false;
1584 
1585   bool IsLE = DAG.getDataLayout().isLittleEndian();
1586   if (ShuffleKind == 0) {
1587     if (IsLE)
1588       return false;
1589     for (unsigned i = 0; i != 16; i += 4)
1590       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1591           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1592           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1593           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1594         return false;
1595   } else if (ShuffleKind == 2) {
1596     if (!IsLE)
1597       return false;
1598     for (unsigned i = 0; i != 16; i += 4)
1599       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1600           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1601           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1602           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1603         return false;
1604   } else if (ShuffleKind == 1) {
1605     unsigned j = IsLE ? 0 : 4;
1606     for (unsigned i = 0; i != 8; i += 4)
1607       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1608           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1609           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1610           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1611           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1612           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1613           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1614           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1615         return false;
1616   }
1617   return true;
1618 }
1619 
1620 /// isVMerge - Common function, used to match vmrg* shuffles.
1621 ///
1622 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1623                      unsigned LHSStart, unsigned RHSStart) {
1624   if (N->getValueType(0) != MVT::v16i8)
1625     return false;
1626   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1627          "Unsupported merge size!");
1628 
1629   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1630     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1631       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1632                              LHSStart+j+i*UnitSize) ||
1633           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1634                              RHSStart+j+i*UnitSize))
1635         return false;
1636     }
1637   return true;
1638 }
1639 
1640 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1641 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1642 /// The ShuffleKind distinguishes between big-endian merges with two
1643 /// different inputs (0), either-endian merges with two identical inputs (1),
1644 /// and little-endian merges with two different inputs (2).  For the latter,
1645 /// the input operands are swapped (see PPCInstrAltivec.td).
1646 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1647                              unsigned ShuffleKind, SelectionDAG &DAG) {
1648   if (DAG.getDataLayout().isLittleEndian()) {
1649     if (ShuffleKind == 1) // unary
1650       return isVMerge(N, UnitSize, 0, 0);
1651     else if (ShuffleKind == 2) // swapped
1652       return isVMerge(N, UnitSize, 0, 16);
1653     else
1654       return false;
1655   } else {
1656     if (ShuffleKind == 1) // unary
1657       return isVMerge(N, UnitSize, 8, 8);
1658     else if (ShuffleKind == 0) // normal
1659       return isVMerge(N, UnitSize, 8, 24);
1660     else
1661       return false;
1662   }
1663 }
1664 
1665 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1666 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1667 /// The ShuffleKind distinguishes between big-endian merges with two
1668 /// different inputs (0), either-endian merges with two identical inputs (1),
1669 /// and little-endian merges with two different inputs (2).  For the latter,
1670 /// the input operands are swapped (see PPCInstrAltivec.td).
1671 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1672                              unsigned ShuffleKind, SelectionDAG &DAG) {
1673   if (DAG.getDataLayout().isLittleEndian()) {
1674     if (ShuffleKind == 1) // unary
1675       return isVMerge(N, UnitSize, 8, 8);
1676     else if (ShuffleKind == 2) // swapped
1677       return isVMerge(N, UnitSize, 8, 24);
1678     else
1679       return false;
1680   } else {
1681     if (ShuffleKind == 1) // unary
1682       return isVMerge(N, UnitSize, 0, 0);
1683     else if (ShuffleKind == 0) // normal
1684       return isVMerge(N, UnitSize, 0, 16);
1685     else
1686       return false;
1687   }
1688 }
1689 
1690 /**
1691  * Common function used to match vmrgew and vmrgow shuffles
1692  *
1693  * The indexOffset determines whether to look for even or odd words in
1694  * the shuffle mask. This is based on the of the endianness of the target
1695  * machine.
1696  *   - Little Endian:
1697  *     - Use offset of 0 to check for odd elements
1698  *     - Use offset of 4 to check for even elements
1699  *   - Big Endian:
1700  *     - Use offset of 0 to check for even elements
1701  *     - Use offset of 4 to check for odd elements
1702  * A detailed description of the vector element ordering for little endian and
1703  * big endian can be found at
1704  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1705  * Targeting your applications - what little endian and big endian IBM XL C/C++
1706  * compiler differences mean to you
1707  *
1708  * The mask to the shuffle vector instruction specifies the indices of the
1709  * elements from the two input vectors to place in the result. The elements are
1710  * numbered in array-access order, starting with the first vector. These vectors
1711  * are always of type v16i8, thus each vector will contain 16 elements of size
1712  * 8. More info on the shuffle vector can be found in the
1713  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1714  * Language Reference.
1715  *
1716  * The RHSStartValue indicates whether the same input vectors are used (unary)
1717  * or two different input vectors are used, based on the following:
1718  *   - If the instruction uses the same vector for both inputs, the range of the
1719  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1720  *     be 0.
1721  *   - If the instruction has two different vectors then the range of the
1722  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1723  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1724  *     to 31 specify elements in the second vector).
1725  *
1726  * \param[in] N The shuffle vector SD Node to analyze
1727  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1728  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1729  * vector to the shuffle_vector instruction
1730  * \return true iff this shuffle vector represents an even or odd word merge
1731  */
1732 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1733                      unsigned RHSStartValue) {
1734   if (N->getValueType(0) != MVT::v16i8)
1735     return false;
1736 
1737   for (unsigned i = 0; i < 2; ++i)
1738     for (unsigned j = 0; j < 4; ++j)
1739       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1740                              i*RHSStartValue+j+IndexOffset) ||
1741           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1742                              i*RHSStartValue+j+IndexOffset+8))
1743         return false;
1744   return true;
1745 }
1746 
1747 /**
1748  * Determine if the specified shuffle mask is suitable for the vmrgew or
1749  * vmrgow instructions.
1750  *
1751  * \param[in] N The shuffle vector SD Node to analyze
1752  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1753  * \param[in] ShuffleKind Identify the type of merge:
1754  *   - 0 = big-endian merge with two different inputs;
1755  *   - 1 = either-endian merge with two identical inputs;
1756  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1757  *     little-endian merges).
1758  * \param[in] DAG The current SelectionDAG
1759  * \return true iff this shuffle mask
1760  */
1761 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1762                               unsigned ShuffleKind, SelectionDAG &DAG) {
1763   if (DAG.getDataLayout().isLittleEndian()) {
1764     unsigned indexOffset = CheckEven ? 4 : 0;
1765     if (ShuffleKind == 1) // Unary
1766       return isVMerge(N, indexOffset, 0);
1767     else if (ShuffleKind == 2) // swapped
1768       return isVMerge(N, indexOffset, 16);
1769     else
1770       return false;
1771   }
1772   else {
1773     unsigned indexOffset = CheckEven ? 0 : 4;
1774     if (ShuffleKind == 1) // Unary
1775       return isVMerge(N, indexOffset, 0);
1776     else if (ShuffleKind == 0) // Normal
1777       return isVMerge(N, indexOffset, 16);
1778     else
1779       return false;
1780   }
1781   return false;
1782 }
1783 
1784 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1785 /// amount, otherwise return -1.
1786 /// The ShuffleKind distinguishes between big-endian operations with two
1787 /// different inputs (0), either-endian operations with two identical inputs
1788 /// (1), and little-endian operations with two different inputs (2).  For the
1789 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1790 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1791                              SelectionDAG &DAG) {
1792   if (N->getValueType(0) != MVT::v16i8)
1793     return -1;
1794 
1795   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1796 
1797   // Find the first non-undef value in the shuffle mask.
1798   unsigned i;
1799   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1800     /*search*/;
1801 
1802   if (i == 16) return -1;  // all undef.
1803 
1804   // Otherwise, check to see if the rest of the elements are consecutively
1805   // numbered from this value.
1806   unsigned ShiftAmt = SVOp->getMaskElt(i);
1807   if (ShiftAmt < i) return -1;
1808 
1809   ShiftAmt -= i;
1810   bool isLE = DAG.getDataLayout().isLittleEndian();
1811 
1812   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1813     // Check the rest of the elements to see if they are consecutive.
1814     for (++i; i != 16; ++i)
1815       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1816         return -1;
1817   } else if (ShuffleKind == 1) {
1818     // Check the rest of the elements to see if they are consecutive.
1819     for (++i; i != 16; ++i)
1820       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1821         return -1;
1822   } else
1823     return -1;
1824 
1825   if (isLE)
1826     ShiftAmt = 16 - ShiftAmt;
1827 
1828   return ShiftAmt;
1829 }
1830 
1831 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1832 /// specifies a splat of a single element that is suitable for input to
1833 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1834 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1835   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1836          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1837 
1838   // The consecutive indices need to specify an element, not part of two
1839   // different elements.  So abandon ship early if this isn't the case.
1840   if (N->getMaskElt(0) % EltSize != 0)
1841     return false;
1842 
1843   // This is a splat operation if each element of the permute is the same, and
1844   // if the value doesn't reference the second vector.
1845   unsigned ElementBase = N->getMaskElt(0);
1846 
1847   // FIXME: Handle UNDEF elements too!
1848   if (ElementBase >= 16)
1849     return false;
1850 
1851   // Check that the indices are consecutive, in the case of a multi-byte element
1852   // splatted with a v16i8 mask.
1853   for (unsigned i = 1; i != EltSize; ++i)
1854     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1855       return false;
1856 
1857   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1858     if (N->getMaskElt(i) < 0) continue;
1859     for (unsigned j = 0; j != EltSize; ++j)
1860       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1861         return false;
1862   }
1863   return true;
1864 }
1865 
1866 /// Check that the mask is shuffling N byte elements. Within each N byte
1867 /// element of the mask, the indices could be either in increasing or
1868 /// decreasing order as long as they are consecutive.
1869 /// \param[in] N the shuffle vector SD Node to analyze
1870 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1871 /// Word/DoubleWord/QuadWord).
1872 /// \param[in] StepLen the delta indices number among the N byte element, if
1873 /// the mask is in increasing/decreasing order then it is 1/-1.
1874 /// \return true iff the mask is shuffling N byte elements.
1875 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1876                                    int StepLen) {
1877   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1878          "Unexpected element width.");
1879   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1880 
1881   unsigned NumOfElem = 16 / Width;
1882   unsigned MaskVal[16]; //  Width is never greater than 16
1883   for (unsigned i = 0; i < NumOfElem; ++i) {
1884     MaskVal[0] = N->getMaskElt(i * Width);
1885     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1886       return false;
1887     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1888       return false;
1889     }
1890 
1891     for (unsigned int j = 1; j < Width; ++j) {
1892       MaskVal[j] = N->getMaskElt(i * Width + j);
1893       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1894         return false;
1895       }
1896     }
1897   }
1898 
1899   return true;
1900 }
1901 
1902 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1903                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1904   if (!isNByteElemShuffleMask(N, 4, 1))
1905     return false;
1906 
1907   // Now we look at mask elements 0,4,8,12
1908   unsigned M0 = N->getMaskElt(0) / 4;
1909   unsigned M1 = N->getMaskElt(4) / 4;
1910   unsigned M2 = N->getMaskElt(8) / 4;
1911   unsigned M3 = N->getMaskElt(12) / 4;
1912   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1913   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1914 
1915   // Below, let H and L be arbitrary elements of the shuffle mask
1916   // where H is in the range [4,7] and L is in the range [0,3].
1917   // H, 1, 2, 3 or L, 5, 6, 7
1918   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1919       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1920     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1921     InsertAtByte = IsLE ? 12 : 0;
1922     Swap = M0 < 4;
1923     return true;
1924   }
1925   // 0, H, 2, 3 or 4, L, 6, 7
1926   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1927       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1928     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1929     InsertAtByte = IsLE ? 8 : 4;
1930     Swap = M1 < 4;
1931     return true;
1932   }
1933   // 0, 1, H, 3 or 4, 5, L, 7
1934   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1935       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1936     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1937     InsertAtByte = IsLE ? 4 : 8;
1938     Swap = M2 < 4;
1939     return true;
1940   }
1941   // 0, 1, 2, H or 4, 5, 6, L
1942   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1943       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1944     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1945     InsertAtByte = IsLE ? 0 : 12;
1946     Swap = M3 < 4;
1947     return true;
1948   }
1949 
1950   // If both vector operands for the shuffle are the same vector, the mask will
1951   // contain only elements from the first one and the second one will be undef.
1952   if (N->getOperand(1).isUndef()) {
1953     ShiftElts = 0;
1954     Swap = true;
1955     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1956     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1957       InsertAtByte = IsLE ? 12 : 0;
1958       return true;
1959     }
1960     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1961       InsertAtByte = IsLE ? 8 : 4;
1962       return true;
1963     }
1964     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1965       InsertAtByte = IsLE ? 4 : 8;
1966       return true;
1967     }
1968     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1969       InsertAtByte = IsLE ? 0 : 12;
1970       return true;
1971     }
1972   }
1973 
1974   return false;
1975 }
1976 
1977 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1978                                bool &Swap, bool IsLE) {
1979   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1980   // Ensure each byte index of the word is consecutive.
1981   if (!isNByteElemShuffleMask(N, 4, 1))
1982     return false;
1983 
1984   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1985   unsigned M0 = N->getMaskElt(0) / 4;
1986   unsigned M1 = N->getMaskElt(4) / 4;
1987   unsigned M2 = N->getMaskElt(8) / 4;
1988   unsigned M3 = N->getMaskElt(12) / 4;
1989 
1990   // If both vector operands for the shuffle are the same vector, the mask will
1991   // contain only elements from the first one and the second one will be undef.
1992   if (N->getOperand(1).isUndef()) {
1993     assert(M0 < 4 && "Indexing into an undef vector?");
1994     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1995       return false;
1996 
1997     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1998     Swap = false;
1999     return true;
2000   }
2001 
2002   // Ensure each word index of the ShuffleVector Mask is consecutive.
2003   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2004     return false;
2005 
2006   if (IsLE) {
2007     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2008       // Input vectors don't need to be swapped if the leading element
2009       // of the result is one of the 3 left elements of the second vector
2010       // (or if there is no shift to be done at all).
2011       Swap = false;
2012       ShiftElts = (8 - M0) % 8;
2013     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2014       // Input vectors need to be swapped if the leading element
2015       // of the result is one of the 3 left elements of the first vector
2016       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2017       Swap = true;
2018       ShiftElts = (4 - M0) % 4;
2019     }
2020 
2021     return true;
2022   } else {                                          // BE
2023     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2024       // Input vectors don't need to be swapped if the leading element
2025       // of the result is one of the 4 elements of the first vector.
2026       Swap = false;
2027       ShiftElts = M0;
2028     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2029       // Input vectors need to be swapped if the leading element
2030       // of the result is one of the 4 elements of the right vector.
2031       Swap = true;
2032       ShiftElts = M0 - 4;
2033     }
2034 
2035     return true;
2036   }
2037 }
2038 
2039 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2040   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2041 
2042   if (!isNByteElemShuffleMask(N, Width, -1))
2043     return false;
2044 
2045   for (int i = 0; i < 16; i += Width)
2046     if (N->getMaskElt(i) != i + Width - 1)
2047       return false;
2048 
2049   return true;
2050 }
2051 
2052 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2053   return isXXBRShuffleMaskHelper(N, 2);
2054 }
2055 
2056 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2057   return isXXBRShuffleMaskHelper(N, 4);
2058 }
2059 
2060 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2061   return isXXBRShuffleMaskHelper(N, 8);
2062 }
2063 
2064 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2065   return isXXBRShuffleMaskHelper(N, 16);
2066 }
2067 
2068 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2069 /// if the inputs to the instruction should be swapped and set \p DM to the
2070 /// value for the immediate.
2071 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2072 /// AND element 0 of the result comes from the first input (LE) or second input
2073 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2074 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2075 /// mask.
2076 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2077                                bool &Swap, bool IsLE) {
2078   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2079 
2080   // Ensure each byte index of the double word is consecutive.
2081   if (!isNByteElemShuffleMask(N, 8, 1))
2082     return false;
2083 
2084   unsigned M0 = N->getMaskElt(0) / 8;
2085   unsigned M1 = N->getMaskElt(8) / 8;
2086   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2087 
2088   // If both vector operands for the shuffle are the same vector, the mask will
2089   // contain only elements from the first one and the second one will be undef.
2090   if (N->getOperand(1).isUndef()) {
2091     if ((M0 | M1) < 2) {
2092       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2093       Swap = false;
2094       return true;
2095     } else
2096       return false;
2097   }
2098 
2099   if (IsLE) {
2100     if (M0 > 1 && M1 < 2) {
2101       Swap = false;
2102     } else if (M0 < 2 && M1 > 1) {
2103       M0 = (M0 + 2) % 4;
2104       M1 = (M1 + 2) % 4;
2105       Swap = true;
2106     } else
2107       return false;
2108 
2109     // Note: if control flow comes here that means Swap is already set above
2110     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2111     return true;
2112   } else { // BE
2113     if (M0 < 2 && M1 > 1) {
2114       Swap = false;
2115     } else if (M0 > 1 && M1 < 2) {
2116       M0 = (M0 + 2) % 4;
2117       M1 = (M1 + 2) % 4;
2118       Swap = true;
2119     } else
2120       return false;
2121 
2122     // Note: if control flow comes here that means Swap is already set above
2123     DM = (M0 << 1) + (M1 & 1);
2124     return true;
2125   }
2126 }
2127 
2128 
2129 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2130 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2131 /// elements are counted from the left of the vector register).
2132 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2133                                          SelectionDAG &DAG) {
2134   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2135   assert(isSplatShuffleMask(SVOp, EltSize));
2136   if (DAG.getDataLayout().isLittleEndian())
2137     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2138   else
2139     return SVOp->getMaskElt(0) / EltSize;
2140 }
2141 
2142 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2143 /// by using a vspltis[bhw] instruction of the specified element size, return
2144 /// the constant being splatted.  The ByteSize field indicates the number of
2145 /// bytes of each element [124] -> [bhw].
2146 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2147   SDValue OpVal(nullptr, 0);
2148 
2149   // If ByteSize of the splat is bigger than the element size of the
2150   // build_vector, then we have a case where we are checking for a splat where
2151   // multiple elements of the buildvector are folded together into a single
2152   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2153   unsigned EltSize = 16/N->getNumOperands();
2154   if (EltSize < ByteSize) {
2155     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2156     SDValue UniquedVals[4];
2157     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2158 
2159     // See if all of the elements in the buildvector agree across.
2160     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2161       if (N->getOperand(i).isUndef()) continue;
2162       // If the element isn't a constant, bail fully out.
2163       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2164 
2165       if (!UniquedVals[i&(Multiple-1)].getNode())
2166         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2167       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2168         return SDValue();  // no match.
2169     }
2170 
2171     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2172     // either constant or undef values that are identical for each chunk.  See
2173     // if these chunks can form into a larger vspltis*.
2174 
2175     // Check to see if all of the leading entries are either 0 or -1.  If
2176     // neither, then this won't fit into the immediate field.
2177     bool LeadingZero = true;
2178     bool LeadingOnes = true;
2179     for (unsigned i = 0; i != Multiple-1; ++i) {
2180       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2181 
2182       LeadingZero &= isNullConstant(UniquedVals[i]);
2183       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2184     }
2185     // Finally, check the least significant entry.
2186     if (LeadingZero) {
2187       if (!UniquedVals[Multiple-1].getNode())
2188         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2189       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2190       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2191         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2192     }
2193     if (LeadingOnes) {
2194       if (!UniquedVals[Multiple-1].getNode())
2195         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2196       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2197       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2198         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2199     }
2200 
2201     return SDValue();
2202   }
2203 
2204   // Check to see if this buildvec has a single non-undef value in its elements.
2205   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2206     if (N->getOperand(i).isUndef()) continue;
2207     if (!OpVal.getNode())
2208       OpVal = N->getOperand(i);
2209     else if (OpVal != N->getOperand(i))
2210       return SDValue();
2211   }
2212 
2213   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2214 
2215   unsigned ValSizeInBytes = EltSize;
2216   uint64_t Value = 0;
2217   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2218     Value = CN->getZExtValue();
2219   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2220     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2221     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2222   }
2223 
2224   // If the splat value is larger than the element value, then we can never do
2225   // this splat.  The only case that we could fit the replicated bits into our
2226   // immediate field for would be zero, and we prefer to use vxor for it.
2227   if (ValSizeInBytes < ByteSize) return SDValue();
2228 
2229   // If the element value is larger than the splat value, check if it consists
2230   // of a repeated bit pattern of size ByteSize.
2231   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2232     return SDValue();
2233 
2234   // Properly sign extend the value.
2235   int MaskVal = SignExtend32(Value, ByteSize * 8);
2236 
2237   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2238   if (MaskVal == 0) return SDValue();
2239 
2240   // Finally, if this value fits in a 5 bit sext field, return it
2241   if (SignExtend32<5>(MaskVal) == MaskVal)
2242     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2243   return SDValue();
2244 }
2245 
2246 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2247 /// amount, otherwise return -1.
2248 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2249   EVT VT = N->getValueType(0);
2250   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2251     return -1;
2252 
2253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2254 
2255   // Find the first non-undef value in the shuffle mask.
2256   unsigned i;
2257   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2258     /*search*/;
2259 
2260   if (i == 4) return -1;  // all undef.
2261 
2262   // Otherwise, check to see if the rest of the elements are consecutively
2263   // numbered from this value.
2264   unsigned ShiftAmt = SVOp->getMaskElt(i);
2265   if (ShiftAmt < i) return -1;
2266   ShiftAmt -= i;
2267 
2268   // Check the rest of the elements to see if they are consecutive.
2269   for (++i; i != 4; ++i)
2270     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2271       return -1;
2272 
2273   return ShiftAmt;
2274 }
2275 
2276 //===----------------------------------------------------------------------===//
2277 //  Addressing Mode Selection
2278 //===----------------------------------------------------------------------===//
2279 
2280 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2281 /// or 64-bit immediate, and if the value can be accurately represented as a
2282 /// sign extension from a 16-bit value.  If so, this returns true and the
2283 /// immediate.
2284 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2285   if (!isa<ConstantSDNode>(N))
2286     return false;
2287 
2288   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2289   if (N->getValueType(0) == MVT::i32)
2290     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2291   else
2292     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2293 }
2294 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2295   return isIntS16Immediate(Op.getNode(), Imm);
2296 }
2297 
2298 
2299 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2300 /// be represented as an indexed [r+r] operation.
2301 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2302                                                SDValue &Index,
2303                                                SelectionDAG &DAG) const {
2304   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2305       UI != E; ++UI) {
2306     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2307       if (Memop->getMemoryVT() == MVT::f64) {
2308           Base = N.getOperand(0);
2309           Index = N.getOperand(1);
2310           return true;
2311       }
2312     }
2313   }
2314   return false;
2315 }
2316 
2317 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2318 /// can be represented as an indexed [r+r] operation.  Returns false if it
2319 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2320 /// non-zero and N can be represented by a base register plus a signed 16-bit
2321 /// displacement, make a more precise judgement by checking (displacement % \p
2322 /// EncodingAlignment).
2323 bool PPCTargetLowering::SelectAddressRegReg(
2324     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2325     MaybeAlign EncodingAlignment) const {
2326   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2327   // a [pc+imm].
2328   if (SelectAddressPCRel(N, Base))
2329     return false;
2330 
2331   int16_t Imm = 0;
2332   if (N.getOpcode() == ISD::ADD) {
2333     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2334     // SPE load/store can only handle 8-bit offsets.
2335     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2336         return true;
2337     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2338         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2339       return false; // r+i
2340     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2341       return false;    // r+i
2342 
2343     Base = N.getOperand(0);
2344     Index = N.getOperand(1);
2345     return true;
2346   } else if (N.getOpcode() == ISD::OR) {
2347     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2348         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2349       return false; // r+i can fold it if we can.
2350 
2351     // If this is an or of disjoint bitfields, we can codegen this as an add
2352     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2353     // disjoint.
2354     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2355 
2356     if (LHSKnown.Zero.getBoolValue()) {
2357       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2358       // If all of the bits are known zero on the LHS or RHS, the add won't
2359       // carry.
2360       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2361         Base = N.getOperand(0);
2362         Index = N.getOperand(1);
2363         return true;
2364       }
2365     }
2366   }
2367 
2368   return false;
2369 }
2370 
2371 // If we happen to be doing an i64 load or store into a stack slot that has
2372 // less than a 4-byte alignment, then the frame-index elimination may need to
2373 // use an indexed load or store instruction (because the offset may not be a
2374 // multiple of 4). The extra register needed to hold the offset comes from the
2375 // register scavenger, and it is possible that the scavenger will need to use
2376 // an emergency spill slot. As a result, we need to make sure that a spill slot
2377 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2378 // stack slot.
2379 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2380   // FIXME: This does not handle the LWA case.
2381   if (VT != MVT::i64)
2382     return;
2383 
2384   // NOTE: We'll exclude negative FIs here, which come from argument
2385   // lowering, because there are no known test cases triggering this problem
2386   // using packed structures (or similar). We can remove this exclusion if
2387   // we find such a test case. The reason why this is so test-case driven is
2388   // because this entire 'fixup' is only to prevent crashes (from the
2389   // register scavenger) on not-really-valid inputs. For example, if we have:
2390   //   %a = alloca i1
2391   //   %b = bitcast i1* %a to i64*
2392   //   store i64* a, i64 b
2393   // then the store should really be marked as 'align 1', but is not. If it
2394   // were marked as 'align 1' then the indexed form would have been
2395   // instruction-selected initially, and the problem this 'fixup' is preventing
2396   // won't happen regardless.
2397   if (FrameIdx < 0)
2398     return;
2399 
2400   MachineFunction &MF = DAG.getMachineFunction();
2401   MachineFrameInfo &MFI = MF.getFrameInfo();
2402 
2403   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2404     return;
2405 
2406   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2407   FuncInfo->setHasNonRISpills();
2408 }
2409 
2410 /// Returns true if the address N can be represented by a base register plus
2411 /// a signed 16-bit displacement [r+imm], and if it is not better
2412 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2413 /// displacements that are multiples of that value.
2414 bool PPCTargetLowering::SelectAddressRegImm(
2415     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2416     MaybeAlign EncodingAlignment) const {
2417   // FIXME dl should come from parent load or store, not from address
2418   SDLoc dl(N);
2419 
2420   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2421   // a [pc+imm].
2422   if (SelectAddressPCRel(N, Base))
2423     return false;
2424 
2425   // If this can be more profitably realized as r+r, fail.
2426   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2427     return false;
2428 
2429   if (N.getOpcode() == ISD::ADD) {
2430     int16_t imm = 0;
2431     if (isIntS16Immediate(N.getOperand(1), imm) &&
2432         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2433       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2434       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2435         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2436         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2437       } else {
2438         Base = N.getOperand(0);
2439       }
2440       return true; // [r+i]
2441     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2442       // Match LOAD (ADD (X, Lo(G))).
2443       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2444              && "Cannot handle constant offsets yet!");
2445       Disp = N.getOperand(1).getOperand(0);  // The global address.
2446       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2447              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2448              Disp.getOpcode() == ISD::TargetConstantPool ||
2449              Disp.getOpcode() == ISD::TargetJumpTable);
2450       Base = N.getOperand(0);
2451       return true;  // [&g+r]
2452     }
2453   } else if (N.getOpcode() == ISD::OR) {
2454     int16_t imm = 0;
2455     if (isIntS16Immediate(N.getOperand(1), imm) &&
2456         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2457       // If this is an or of disjoint bitfields, we can codegen this as an add
2458       // (for better address arithmetic) if the LHS and RHS of the OR are
2459       // provably disjoint.
2460       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2461 
2462       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2463         // If all of the bits are known zero on the LHS or RHS, the add won't
2464         // carry.
2465         if (FrameIndexSDNode *FI =
2466               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2467           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2468           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2469         } else {
2470           Base = N.getOperand(0);
2471         }
2472         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2473         return true;
2474       }
2475     }
2476   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2477     // Loading from a constant address.
2478 
2479     // If this address fits entirely in a 16-bit sext immediate field, codegen
2480     // this as "d, 0"
2481     int16_t Imm;
2482     if (isIntS16Immediate(CN, Imm) &&
2483         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2484       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2485       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2486                              CN->getValueType(0));
2487       return true;
2488     }
2489 
2490     // Handle 32-bit sext immediates with LIS + addr mode.
2491     if ((CN->getValueType(0) == MVT::i32 ||
2492          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2493         (!EncodingAlignment ||
2494          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2495       int Addr = (int)CN->getZExtValue();
2496 
2497       // Otherwise, break this down into an LIS + disp.
2498       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2499 
2500       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2501                                    MVT::i32);
2502       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2503       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2504       return true;
2505     }
2506   }
2507 
2508   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2509   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2510     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2511     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2512   } else
2513     Base = N;
2514   return true;      // [r+0]
2515 }
2516 
2517 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2518 /// represented as an indexed [r+r] operation.
2519 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2520                                                 SDValue &Index,
2521                                                 SelectionDAG &DAG) const {
2522   // Check to see if we can easily represent this as an [r+r] address.  This
2523   // will fail if it thinks that the address is more profitably represented as
2524   // reg+imm, e.g. where imm = 0.
2525   if (SelectAddressRegReg(N, Base, Index, DAG))
2526     return true;
2527 
2528   // If the address is the result of an add, we will utilize the fact that the
2529   // address calculation includes an implicit add.  However, we can reduce
2530   // register pressure if we do not materialize a constant just for use as the
2531   // index register.  We only get rid of the add if it is not an add of a
2532   // value and a 16-bit signed constant and both have a single use.
2533   int16_t imm = 0;
2534   if (N.getOpcode() == ISD::ADD &&
2535       (!isIntS16Immediate(N.getOperand(1), imm) ||
2536        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2537     Base = N.getOperand(0);
2538     Index = N.getOperand(1);
2539     return true;
2540   }
2541 
2542   // Otherwise, do it the hard way, using R0 as the base register.
2543   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2544                          N.getValueType());
2545   Index = N;
2546   return true;
2547 }
2548 
2549 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2550   Ty *PCRelCand = dyn_cast<Ty>(N);
2551   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2552 }
2553 
2554 /// Returns true if this address is a PC Relative address.
2555 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2556 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2557 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2558   // This is a materialize PC Relative node. Always select this as PC Relative.
2559   Base = N;
2560   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2561     return true;
2562   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2563       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2564       isValidPCRelNode<JumpTableSDNode>(N) ||
2565       isValidPCRelNode<BlockAddressSDNode>(N))
2566     return true;
2567   return false;
2568 }
2569 
2570 /// Returns true if we should use a direct load into vector instruction
2571 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2572 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2573 
2574   // If there are any other uses other than scalar to vector, then we should
2575   // keep it as a scalar load -> direct move pattern to prevent multiple
2576   // loads.
2577   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2578   if (!LD)
2579     return false;
2580 
2581   EVT MemVT = LD->getMemoryVT();
2582   if (!MemVT.isSimple())
2583     return false;
2584   switch(MemVT.getSimpleVT().SimpleTy) {
2585   case MVT::i64:
2586     break;
2587   case MVT::i32:
2588     if (!ST.hasP8Vector())
2589       return false;
2590     break;
2591   case MVT::i16:
2592   case MVT::i8:
2593     if (!ST.hasP9Vector())
2594       return false;
2595     break;
2596   default:
2597     return false;
2598   }
2599 
2600   SDValue LoadedVal(N, 0);
2601   if (!LoadedVal.hasOneUse())
2602     return false;
2603 
2604   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2605        UI != UE; ++UI)
2606     if (UI.getUse().get().getResNo() == 0 &&
2607         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2608         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2609       return false;
2610 
2611   return true;
2612 }
2613 
2614 /// getPreIndexedAddressParts - returns true by value, base pointer and
2615 /// offset pointer and addressing mode by reference if the node's address
2616 /// can be legally represented as pre-indexed load / store address.
2617 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2618                                                   SDValue &Offset,
2619                                                   ISD::MemIndexedMode &AM,
2620                                                   SelectionDAG &DAG) const {
2621   if (DisablePPCPreinc) return false;
2622 
2623   bool isLoad = true;
2624   SDValue Ptr;
2625   EVT VT;
2626   unsigned Alignment;
2627   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2628     Ptr = LD->getBasePtr();
2629     VT = LD->getMemoryVT();
2630     Alignment = LD->getAlignment();
2631   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2632     Ptr = ST->getBasePtr();
2633     VT  = ST->getMemoryVT();
2634     Alignment = ST->getAlignment();
2635     isLoad = false;
2636   } else
2637     return false;
2638 
2639   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2640   // instructions because we can fold these into a more efficient instruction
2641   // instead, (such as LXSD).
2642   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2643     return false;
2644   }
2645 
2646   // PowerPC doesn't have preinc load/store instructions for vectors
2647   if (VT.isVector())
2648     return false;
2649 
2650   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2651     // Common code will reject creating a pre-inc form if the base pointer
2652     // is a frame index, or if N is a store and the base pointer is either
2653     // the same as or a predecessor of the value being stored.  Check for
2654     // those situations here, and try with swapped Base/Offset instead.
2655     bool Swap = false;
2656 
2657     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2658       Swap = true;
2659     else if (!isLoad) {
2660       SDValue Val = cast<StoreSDNode>(N)->getValue();
2661       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2662         Swap = true;
2663     }
2664 
2665     if (Swap)
2666       std::swap(Base, Offset);
2667 
2668     AM = ISD::PRE_INC;
2669     return true;
2670   }
2671 
2672   // LDU/STU can only handle immediates that are a multiple of 4.
2673   if (VT != MVT::i64) {
2674     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2675       return false;
2676   } else {
2677     // LDU/STU need an address with at least 4-byte alignment.
2678     if (Alignment < 4)
2679       return false;
2680 
2681     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2682       return false;
2683   }
2684 
2685   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2686     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2687     // sext i32 to i64 when addr mode is r+i.
2688     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2689         LD->getExtensionType() == ISD::SEXTLOAD &&
2690         isa<ConstantSDNode>(Offset))
2691       return false;
2692   }
2693 
2694   AM = ISD::PRE_INC;
2695   return true;
2696 }
2697 
2698 //===----------------------------------------------------------------------===//
2699 //  LowerOperation implementation
2700 //===----------------------------------------------------------------------===//
2701 
2702 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2703 /// and LoOpFlags to the target MO flags.
2704 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2705                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2706                                const GlobalValue *GV = nullptr) {
2707   HiOpFlags = PPCII::MO_HA;
2708   LoOpFlags = PPCII::MO_LO;
2709 
2710   // Don't use the pic base if not in PIC relocation model.
2711   if (IsPIC) {
2712     HiOpFlags |= PPCII::MO_PIC_FLAG;
2713     LoOpFlags |= PPCII::MO_PIC_FLAG;
2714   }
2715 }
2716 
2717 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2718                              SelectionDAG &DAG) {
2719   SDLoc DL(HiPart);
2720   EVT PtrVT = HiPart.getValueType();
2721   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2722 
2723   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2724   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2725 
2726   // With PIC, the first instruction is actually "GR+hi(&G)".
2727   if (isPIC)
2728     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2729                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2730 
2731   // Generate non-pic code that has direct accesses to the constant pool.
2732   // The address of the global is just (hi(&g)+lo(&g)).
2733   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2734 }
2735 
2736 static void setUsesTOCBasePtr(MachineFunction &MF) {
2737   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2738   FuncInfo->setUsesTOCBasePtr();
2739 }
2740 
2741 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2742   setUsesTOCBasePtr(DAG.getMachineFunction());
2743 }
2744 
2745 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2746                                        SDValue GA) const {
2747   const bool Is64Bit = Subtarget.isPPC64();
2748   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2749   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2750                         : Subtarget.isAIXABI()
2751                               ? DAG.getRegister(PPC::R2, VT)
2752                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2753   SDValue Ops[] = { GA, Reg };
2754   return DAG.getMemIntrinsicNode(
2755       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2756       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2757       MachineMemOperand::MOLoad);
2758 }
2759 
2760 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2761                                              SelectionDAG &DAG) const {
2762   EVT PtrVT = Op.getValueType();
2763   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2764   const Constant *C = CP->getConstVal();
2765 
2766   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2767   // The actual address of the GlobalValue is stored in the TOC.
2768   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2769     if (Subtarget.isUsingPCRelativeCalls()) {
2770       SDLoc DL(CP);
2771       EVT Ty = getPointerTy(DAG.getDataLayout());
2772       SDValue ConstPool = DAG.getTargetConstantPool(
2773           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2774       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2775     }
2776     setUsesTOCBasePtr(DAG);
2777     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2778     return getTOCEntry(DAG, SDLoc(CP), GA);
2779   }
2780 
2781   unsigned MOHiFlag, MOLoFlag;
2782   bool IsPIC = isPositionIndependent();
2783   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2784 
2785   if (IsPIC && Subtarget.isSVR4ABI()) {
2786     SDValue GA =
2787         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2788     return getTOCEntry(DAG, SDLoc(CP), GA);
2789   }
2790 
2791   SDValue CPIHi =
2792       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2793   SDValue CPILo =
2794       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2795   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2796 }
2797 
2798 // For 64-bit PowerPC, prefer the more compact relative encodings.
2799 // This trades 32 bits per jump table entry for one or two instructions
2800 // on the jump site.
2801 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2802   if (isJumpTableRelative())
2803     return MachineJumpTableInfo::EK_LabelDifference32;
2804 
2805   return TargetLowering::getJumpTableEncoding();
2806 }
2807 
2808 bool PPCTargetLowering::isJumpTableRelative() const {
2809   if (UseAbsoluteJumpTables)
2810     return false;
2811   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2812     return true;
2813   return TargetLowering::isJumpTableRelative();
2814 }
2815 
2816 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2817                                                     SelectionDAG &DAG) const {
2818   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2819     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2820 
2821   switch (getTargetMachine().getCodeModel()) {
2822   case CodeModel::Small:
2823   case CodeModel::Medium:
2824     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2825   default:
2826     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2827                        getPointerTy(DAG.getDataLayout()));
2828   }
2829 }
2830 
2831 const MCExpr *
2832 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2833                                                 unsigned JTI,
2834                                                 MCContext &Ctx) const {
2835   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2836     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2837 
2838   switch (getTargetMachine().getCodeModel()) {
2839   case CodeModel::Small:
2840   case CodeModel::Medium:
2841     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2842   default:
2843     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2844   }
2845 }
2846 
2847 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2848   EVT PtrVT = Op.getValueType();
2849   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2850 
2851   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2852   if (Subtarget.isUsingPCRelativeCalls()) {
2853     SDLoc DL(JT);
2854     EVT Ty = getPointerTy(DAG.getDataLayout());
2855     SDValue GA =
2856         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2857     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2858     return MatAddr;
2859   }
2860 
2861   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2862   // The actual address of the GlobalValue is stored in the TOC.
2863   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2864     setUsesTOCBasePtr(DAG);
2865     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2866     return getTOCEntry(DAG, SDLoc(JT), GA);
2867   }
2868 
2869   unsigned MOHiFlag, MOLoFlag;
2870   bool IsPIC = isPositionIndependent();
2871   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2872 
2873   if (IsPIC && Subtarget.isSVR4ABI()) {
2874     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2875                                         PPCII::MO_PIC_FLAG);
2876     return getTOCEntry(DAG, SDLoc(GA), GA);
2877   }
2878 
2879   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2880   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2881   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2882 }
2883 
2884 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2885                                              SelectionDAG &DAG) const {
2886   EVT PtrVT = Op.getValueType();
2887   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2888   const BlockAddress *BA = BASDN->getBlockAddress();
2889 
2890   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2891   if (Subtarget.isUsingPCRelativeCalls()) {
2892     SDLoc DL(BASDN);
2893     EVT Ty = getPointerTy(DAG.getDataLayout());
2894     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2895                                            PPCII::MO_PCREL_FLAG);
2896     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2897     return MatAddr;
2898   }
2899 
2900   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2901   // The actual BlockAddress is stored in the TOC.
2902   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2903     setUsesTOCBasePtr(DAG);
2904     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2905     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2906   }
2907 
2908   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2909   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2910     return getTOCEntry(
2911         DAG, SDLoc(BASDN),
2912         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2913 
2914   unsigned MOHiFlag, MOLoFlag;
2915   bool IsPIC = isPositionIndependent();
2916   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2917   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2918   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2919   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2920 }
2921 
2922 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2923                                               SelectionDAG &DAG) const {
2924   // FIXME: TLS addresses currently use medium model code sequences,
2925   // which is the most useful form.  Eventually support for small and
2926   // large models could be added if users need it, at the cost of
2927   // additional complexity.
2928   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
2929     report_fatal_error("Thread local storage is not supported with pc-relative"
2930                        " addressing - please compile with -mno-pcrel");
2931   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2932   if (DAG.getTarget().useEmulatedTLS())
2933     return LowerToTLSEmulatedModel(GA, DAG);
2934 
2935   SDLoc dl(GA);
2936   const GlobalValue *GV = GA->getGlobal();
2937   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2938   bool is64bit = Subtarget.isPPC64();
2939   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2940   PICLevel::Level picLevel = M->getPICLevel();
2941 
2942   const TargetMachine &TM = getTargetMachine();
2943   TLSModel::Model Model = TM.getTLSModel(GV);
2944 
2945   if (Model == TLSModel::LocalExec) {
2946     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2947                                                PPCII::MO_TPREL_HA);
2948     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2949                                                PPCII::MO_TPREL_LO);
2950     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2951                              : DAG.getRegister(PPC::R2, MVT::i32);
2952 
2953     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2954     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2955   }
2956 
2957   if (Model == TLSModel::InitialExec) {
2958     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2959     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2960                                                 PPCII::MO_TLS);
2961     SDValue GOTPtr;
2962     if (is64bit) {
2963       setUsesTOCBasePtr(DAG);
2964       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2965       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2966                            PtrVT, GOTReg, TGA);
2967     } else {
2968       if (!TM.isPositionIndependent())
2969         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2970       else if (picLevel == PICLevel::SmallPIC)
2971         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2972       else
2973         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2974     }
2975     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2976                                    PtrVT, TGA, GOTPtr);
2977     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2978   }
2979 
2980   if (Model == TLSModel::GeneralDynamic) {
2981     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2982     SDValue GOTPtr;
2983     if (is64bit) {
2984       setUsesTOCBasePtr(DAG);
2985       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2986       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2987                                    GOTReg, TGA);
2988     } else {
2989       if (picLevel == PICLevel::SmallPIC)
2990         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2991       else
2992         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2993     }
2994     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2995                        GOTPtr, TGA, TGA);
2996   }
2997 
2998   if (Model == TLSModel::LocalDynamic) {
2999     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3000     SDValue GOTPtr;
3001     if (is64bit) {
3002       setUsesTOCBasePtr(DAG);
3003       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3004       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3005                            GOTReg, TGA);
3006     } else {
3007       if (picLevel == PICLevel::SmallPIC)
3008         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3009       else
3010         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3011     }
3012     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3013                                   PtrVT, GOTPtr, TGA, TGA);
3014     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3015                                       PtrVT, TLSAddr, TGA);
3016     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3017   }
3018 
3019   llvm_unreachable("Unknown TLS model!");
3020 }
3021 
3022 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3023                                               SelectionDAG &DAG) const {
3024   EVT PtrVT = Op.getValueType();
3025   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3026   SDLoc DL(GSDN);
3027   const GlobalValue *GV = GSDN->getGlobal();
3028 
3029   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3030   // The actual address of the GlobalValue is stored in the TOC.
3031   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3032     if (Subtarget.isUsingPCRelativeCalls()) {
3033       EVT Ty = getPointerTy(DAG.getDataLayout());
3034       if (isAccessedAsGotIndirect(Op)) {
3035         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3036                                                 PPCII::MO_PCREL_FLAG |
3037                                                     PPCII::MO_GOT_FLAG);
3038         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3039         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3040                                    MachinePointerInfo());
3041         return Load;
3042       } else {
3043         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3044                                                 PPCII::MO_PCREL_FLAG);
3045         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3046       }
3047     }
3048     setUsesTOCBasePtr(DAG);
3049     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3050     return getTOCEntry(DAG, DL, GA);
3051   }
3052 
3053   unsigned MOHiFlag, MOLoFlag;
3054   bool IsPIC = isPositionIndependent();
3055   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3056 
3057   if (IsPIC && Subtarget.isSVR4ABI()) {
3058     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3059                                             GSDN->getOffset(),
3060                                             PPCII::MO_PIC_FLAG);
3061     return getTOCEntry(DAG, DL, GA);
3062   }
3063 
3064   SDValue GAHi =
3065     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3066   SDValue GALo =
3067     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3068 
3069   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3070 }
3071 
3072 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3073   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3074   SDLoc dl(Op);
3075 
3076   if (Op.getValueType() == MVT::v2i64) {
3077     // When the operands themselves are v2i64 values, we need to do something
3078     // special because VSX has no underlying comparison operations for these.
3079     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3080       // Equality can be handled by casting to the legal type for Altivec
3081       // comparisons, everything else needs to be expanded.
3082       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3083         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3084                  DAG.getSetCC(dl, MVT::v4i32,
3085                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3086                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3087                    CC));
3088       }
3089 
3090       return SDValue();
3091     }
3092 
3093     // We handle most of these in the usual way.
3094     return Op;
3095   }
3096 
3097   // If we're comparing for equality to zero, expose the fact that this is
3098   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3099   // fold the new nodes.
3100   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3101     return V;
3102 
3103   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3104     // Leave comparisons against 0 and -1 alone for now, since they're usually
3105     // optimized.  FIXME: revisit this when we can custom lower all setcc
3106     // optimizations.
3107     if (C->isAllOnesValue() || C->isNullValue())
3108       return SDValue();
3109   }
3110 
3111   // If we have an integer seteq/setne, turn it into a compare against zero
3112   // by xor'ing the rhs with the lhs, which is faster than setting a
3113   // condition register, reading it back out, and masking the correct bit.  The
3114   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3115   // the result to other bit-twiddling opportunities.
3116   EVT LHSVT = Op.getOperand(0).getValueType();
3117   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3118     EVT VT = Op.getValueType();
3119     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3120                                 Op.getOperand(1));
3121     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3122   }
3123   return SDValue();
3124 }
3125 
3126 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3127   SDNode *Node = Op.getNode();
3128   EVT VT = Node->getValueType(0);
3129   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3130   SDValue InChain = Node->getOperand(0);
3131   SDValue VAListPtr = Node->getOperand(1);
3132   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3133   SDLoc dl(Node);
3134 
3135   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3136 
3137   // gpr_index
3138   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3139                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3140   InChain = GprIndex.getValue(1);
3141 
3142   if (VT == MVT::i64) {
3143     // Check if GprIndex is even
3144     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3145                                  DAG.getConstant(1, dl, MVT::i32));
3146     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3147                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3148     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3149                                           DAG.getConstant(1, dl, MVT::i32));
3150     // Align GprIndex to be even if it isn't
3151     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3152                            GprIndex);
3153   }
3154 
3155   // fpr index is 1 byte after gpr
3156   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3157                                DAG.getConstant(1, dl, MVT::i32));
3158 
3159   // fpr
3160   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3161                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3162   InChain = FprIndex.getValue(1);
3163 
3164   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3165                                        DAG.getConstant(8, dl, MVT::i32));
3166 
3167   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3168                                         DAG.getConstant(4, dl, MVT::i32));
3169 
3170   // areas
3171   SDValue OverflowArea =
3172       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3173   InChain = OverflowArea.getValue(1);
3174 
3175   SDValue RegSaveArea =
3176       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3177   InChain = RegSaveArea.getValue(1);
3178 
3179   // select overflow_area if index > 8
3180   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3181                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3182 
3183   // adjustment constant gpr_index * 4/8
3184   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3185                                     VT.isInteger() ? GprIndex : FprIndex,
3186                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3187                                                     MVT::i32));
3188 
3189   // OurReg = RegSaveArea + RegConstant
3190   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3191                                RegConstant);
3192 
3193   // Floating types are 32 bytes into RegSaveArea
3194   if (VT.isFloatingPoint())
3195     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3196                          DAG.getConstant(32, dl, MVT::i32));
3197 
3198   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3199   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3200                                    VT.isInteger() ? GprIndex : FprIndex,
3201                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3202                                                    MVT::i32));
3203 
3204   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3205                               VT.isInteger() ? VAListPtr : FprPtr,
3206                               MachinePointerInfo(SV), MVT::i8);
3207 
3208   // determine if we should load from reg_save_area or overflow_area
3209   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3210 
3211   // increase overflow_area by 4/8 if gpr/fpr > 8
3212   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3213                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3214                                           dl, MVT::i32));
3215 
3216   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3217                              OverflowAreaPlusN);
3218 
3219   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3220                               MachinePointerInfo(), MVT::i32);
3221 
3222   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3223 }
3224 
3225 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3226   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3227 
3228   // We have to copy the entire va_list struct:
3229   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3230   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3231                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3232                        false, true, false, MachinePointerInfo(),
3233                        MachinePointerInfo());
3234 }
3235 
3236 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3237                                                   SelectionDAG &DAG) const {
3238   if (Subtarget.isAIXABI())
3239     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3240 
3241   return Op.getOperand(0);
3242 }
3243 
3244 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3245                                                 SelectionDAG &DAG) const {
3246   if (Subtarget.isAIXABI())
3247     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3248 
3249   SDValue Chain = Op.getOperand(0);
3250   SDValue Trmp = Op.getOperand(1); // trampoline
3251   SDValue FPtr = Op.getOperand(2); // nested function
3252   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3253   SDLoc dl(Op);
3254 
3255   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3256   bool isPPC64 = (PtrVT == MVT::i64);
3257   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3258 
3259   TargetLowering::ArgListTy Args;
3260   TargetLowering::ArgListEntry Entry;
3261 
3262   Entry.Ty = IntPtrTy;
3263   Entry.Node = Trmp; Args.push_back(Entry);
3264 
3265   // TrampSize == (isPPC64 ? 48 : 40);
3266   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3267                                isPPC64 ? MVT::i64 : MVT::i32);
3268   Args.push_back(Entry);
3269 
3270   Entry.Node = FPtr; Args.push_back(Entry);
3271   Entry.Node = Nest; Args.push_back(Entry);
3272 
3273   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3274   TargetLowering::CallLoweringInfo CLI(DAG);
3275   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3276       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3277       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3278 
3279   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3280   return CallResult.second;
3281 }
3282 
3283 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3284   MachineFunction &MF = DAG.getMachineFunction();
3285   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3286   EVT PtrVT = getPointerTy(MF.getDataLayout());
3287 
3288   SDLoc dl(Op);
3289 
3290   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3291     // vastart just stores the address of the VarArgsFrameIndex slot into the
3292     // memory location argument.
3293     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3294     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3295     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3296                         MachinePointerInfo(SV));
3297   }
3298 
3299   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3300   // We suppose the given va_list is already allocated.
3301   //
3302   // typedef struct {
3303   //  char gpr;     /* index into the array of 8 GPRs
3304   //                 * stored in the register save area
3305   //                 * gpr=0 corresponds to r3,
3306   //                 * gpr=1 to r4, etc.
3307   //                 */
3308   //  char fpr;     /* index into the array of 8 FPRs
3309   //                 * stored in the register save area
3310   //                 * fpr=0 corresponds to f1,
3311   //                 * fpr=1 to f2, etc.
3312   //                 */
3313   //  char *overflow_arg_area;
3314   //                /* location on stack that holds
3315   //                 * the next overflow argument
3316   //                 */
3317   //  char *reg_save_area;
3318   //               /* where r3:r10 and f1:f8 (if saved)
3319   //                * are stored
3320   //                */
3321   // } va_list[1];
3322 
3323   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3324   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3325   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3326                                             PtrVT);
3327   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3328                                  PtrVT);
3329 
3330   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3331   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3332 
3333   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3334   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3335 
3336   uint64_t FPROffset = 1;
3337   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3338 
3339   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3340 
3341   // Store first byte : number of int regs
3342   SDValue firstStore =
3343       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3344                         MachinePointerInfo(SV), MVT::i8);
3345   uint64_t nextOffset = FPROffset;
3346   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3347                                   ConstFPROffset);
3348 
3349   // Store second byte : number of float regs
3350   SDValue secondStore =
3351       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3352                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3353   nextOffset += StackOffset;
3354   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3355 
3356   // Store second word : arguments given on stack
3357   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3358                                     MachinePointerInfo(SV, nextOffset));
3359   nextOffset += FrameOffset;
3360   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3361 
3362   // Store third word : arguments given in registers
3363   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3364                       MachinePointerInfo(SV, nextOffset));
3365 }
3366 
3367 /// FPR - The set of FP registers that should be allocated for arguments
3368 /// on Darwin and AIX.
3369 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3370                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3371                                 PPC::F11, PPC::F12, PPC::F13};
3372 
3373 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3374 /// the stack.
3375 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3376                                        unsigned PtrByteSize) {
3377   unsigned ArgSize = ArgVT.getStoreSize();
3378   if (Flags.isByVal())
3379     ArgSize = Flags.getByValSize();
3380 
3381   // Round up to multiples of the pointer size, except for array members,
3382   // which are always packed.
3383   if (!Flags.isInConsecutiveRegs())
3384     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3385 
3386   return ArgSize;
3387 }
3388 
3389 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3390 /// on the stack.
3391 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3392                                          ISD::ArgFlagsTy Flags,
3393                                          unsigned PtrByteSize) {
3394   Align Alignment(PtrByteSize);
3395 
3396   // Altivec parameters are padded to a 16 byte boundary.
3397   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3398       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3399       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3400       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3401     Alignment = Align(16);
3402 
3403   // ByVal parameters are aligned as requested.
3404   if (Flags.isByVal()) {
3405     auto BVAlign = Flags.getNonZeroByValAlign();
3406     if (BVAlign > PtrByteSize) {
3407       if (BVAlign.value() % PtrByteSize != 0)
3408         llvm_unreachable(
3409             "ByVal alignment is not a multiple of the pointer size");
3410 
3411       Alignment = BVAlign;
3412     }
3413   }
3414 
3415   // Array members are always packed to their original alignment.
3416   if (Flags.isInConsecutiveRegs()) {
3417     // If the array member was split into multiple registers, the first
3418     // needs to be aligned to the size of the full type.  (Except for
3419     // ppcf128, which is only aligned as its f64 components.)
3420     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3421       Alignment = Align(OrigVT.getStoreSize());
3422     else
3423       Alignment = Align(ArgVT.getStoreSize());
3424   }
3425 
3426   return Alignment;
3427 }
3428 
3429 /// CalculateStackSlotUsed - Return whether this argument will use its
3430 /// stack slot (instead of being passed in registers).  ArgOffset,
3431 /// AvailableFPRs, and AvailableVRs must hold the current argument
3432 /// position, and will be updated to account for this argument.
3433 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3434                                    unsigned PtrByteSize, unsigned LinkageSize,
3435                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3436                                    unsigned &AvailableFPRs,
3437                                    unsigned &AvailableVRs) {
3438   bool UseMemory = false;
3439 
3440   // Respect alignment of argument on the stack.
3441   Align Alignment =
3442       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3443   ArgOffset = alignTo(ArgOffset, Alignment);
3444   // If there's no space left in the argument save area, we must
3445   // use memory (this check also catches zero-sized arguments).
3446   if (ArgOffset >= LinkageSize + ParamAreaSize)
3447     UseMemory = true;
3448 
3449   // Allocate argument on the stack.
3450   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3451   if (Flags.isInConsecutiveRegsLast())
3452     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3453   // If we overran the argument save area, we must use memory
3454   // (this check catches arguments passed partially in memory)
3455   if (ArgOffset > LinkageSize + ParamAreaSize)
3456     UseMemory = true;
3457 
3458   // However, if the argument is actually passed in an FPR or a VR,
3459   // we don't use memory after all.
3460   if (!Flags.isByVal()) {
3461     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3462       if (AvailableFPRs > 0) {
3463         --AvailableFPRs;
3464         return false;
3465       }
3466     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3467         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3468         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3469         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3470       if (AvailableVRs > 0) {
3471         --AvailableVRs;
3472         return false;
3473       }
3474   }
3475 
3476   return UseMemory;
3477 }
3478 
3479 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3480 /// ensure minimum alignment required for target.
3481 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3482                                      unsigned NumBytes) {
3483   return alignTo(NumBytes, Lowering->getStackAlign());
3484 }
3485 
3486 SDValue PPCTargetLowering::LowerFormalArguments(
3487     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3488     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3489     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3490   if (Subtarget.isAIXABI())
3491     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3492                                     InVals);
3493   if (Subtarget.is64BitELFABI())
3494     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3495                                        InVals);
3496   if (Subtarget.is32BitELFABI())
3497     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3498                                        InVals);
3499 
3500   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3501                                      InVals);
3502 }
3503 
3504 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3505     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3506     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3507     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3508 
3509   // 32-bit SVR4 ABI Stack Frame Layout:
3510   //              +-----------------------------------+
3511   //        +-->  |            Back chain             |
3512   //        |     +-----------------------------------+
3513   //        |     | Floating-point register save area |
3514   //        |     +-----------------------------------+
3515   //        |     |    General register save area     |
3516   //        |     +-----------------------------------+
3517   //        |     |          CR save word             |
3518   //        |     +-----------------------------------+
3519   //        |     |         VRSAVE save word          |
3520   //        |     +-----------------------------------+
3521   //        |     |         Alignment padding         |
3522   //        |     +-----------------------------------+
3523   //        |     |     Vector register save area     |
3524   //        |     +-----------------------------------+
3525   //        |     |       Local variable space        |
3526   //        |     +-----------------------------------+
3527   //        |     |        Parameter list area        |
3528   //        |     +-----------------------------------+
3529   //        |     |           LR save word            |
3530   //        |     +-----------------------------------+
3531   // SP-->  +---  |            Back chain             |
3532   //              +-----------------------------------+
3533   //
3534   // Specifications:
3535   //   System V Application Binary Interface PowerPC Processor Supplement
3536   //   AltiVec Technology Programming Interface Manual
3537 
3538   MachineFunction &MF = DAG.getMachineFunction();
3539   MachineFrameInfo &MFI = MF.getFrameInfo();
3540   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3541 
3542   EVT PtrVT = getPointerTy(MF.getDataLayout());
3543   // Potential tail calls could cause overwriting of argument stack slots.
3544   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3545                        (CallConv == CallingConv::Fast));
3546   const Align PtrAlign(4);
3547 
3548   // Assign locations to all of the incoming arguments.
3549   SmallVector<CCValAssign, 16> ArgLocs;
3550   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3551                  *DAG.getContext());
3552 
3553   // Reserve space for the linkage area on the stack.
3554   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3555   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3556   if (useSoftFloat())
3557     CCInfo.PreAnalyzeFormalArguments(Ins);
3558 
3559   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3560   CCInfo.clearWasPPCF128();
3561 
3562   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3563     CCValAssign &VA = ArgLocs[i];
3564 
3565     // Arguments stored in registers.
3566     if (VA.isRegLoc()) {
3567       const TargetRegisterClass *RC;
3568       EVT ValVT = VA.getValVT();
3569 
3570       switch (ValVT.getSimpleVT().SimpleTy) {
3571         default:
3572           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3573         case MVT::i1:
3574         case MVT::i32:
3575           RC = &PPC::GPRCRegClass;
3576           break;
3577         case MVT::f32:
3578           if (Subtarget.hasP8Vector())
3579             RC = &PPC::VSSRCRegClass;
3580           else if (Subtarget.hasSPE())
3581             RC = &PPC::GPRCRegClass;
3582           else
3583             RC = &PPC::F4RCRegClass;
3584           break;
3585         case MVT::f64:
3586           if (Subtarget.hasVSX())
3587             RC = &PPC::VSFRCRegClass;
3588           else if (Subtarget.hasSPE())
3589             // SPE passes doubles in GPR pairs.
3590             RC = &PPC::GPRCRegClass;
3591           else
3592             RC = &PPC::F8RCRegClass;
3593           break;
3594         case MVT::v16i8:
3595         case MVT::v8i16:
3596         case MVT::v4i32:
3597           RC = &PPC::VRRCRegClass;
3598           break;
3599         case MVT::v4f32:
3600           RC = &PPC::VRRCRegClass;
3601           break;
3602         case MVT::v2f64:
3603         case MVT::v2i64:
3604           RC = &PPC::VRRCRegClass;
3605           break;
3606       }
3607 
3608       SDValue ArgValue;
3609       // Transform the arguments stored in physical registers into
3610       // virtual ones.
3611       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3612         assert(i + 1 < e && "No second half of double precision argument");
3613         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3614         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3615         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3616         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3617         if (!Subtarget.isLittleEndian())
3618           std::swap (ArgValueLo, ArgValueHi);
3619         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3620                                ArgValueHi);
3621       } else {
3622         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3623         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3624                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3625         if (ValVT == MVT::i1)
3626           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3627       }
3628 
3629       InVals.push_back(ArgValue);
3630     } else {
3631       // Argument stored in memory.
3632       assert(VA.isMemLoc());
3633 
3634       // Get the extended size of the argument type in stack
3635       unsigned ArgSize = VA.getLocVT().getStoreSize();
3636       // Get the actual size of the argument type
3637       unsigned ObjSize = VA.getValVT().getStoreSize();
3638       unsigned ArgOffset = VA.getLocMemOffset();
3639       // Stack objects in PPC32 are right justified.
3640       ArgOffset += ArgSize - ObjSize;
3641       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3642 
3643       // Create load nodes to retrieve arguments from the stack.
3644       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3645       InVals.push_back(
3646           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3647     }
3648   }
3649 
3650   // Assign locations to all of the incoming aggregate by value arguments.
3651   // Aggregates passed by value are stored in the local variable space of the
3652   // caller's stack frame, right above the parameter list area.
3653   SmallVector<CCValAssign, 16> ByValArgLocs;
3654   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3655                       ByValArgLocs, *DAG.getContext());
3656 
3657   // Reserve stack space for the allocations in CCInfo.
3658   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3659 
3660   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3661 
3662   // Area that is at least reserved in the caller of this function.
3663   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3664   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3665 
3666   // Set the size that is at least reserved in caller of this function.  Tail
3667   // call optimized function's reserved stack space needs to be aligned so that
3668   // taking the difference between two stack areas will result in an aligned
3669   // stack.
3670   MinReservedArea =
3671       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3672   FuncInfo->setMinReservedArea(MinReservedArea);
3673 
3674   SmallVector<SDValue, 8> MemOps;
3675 
3676   // If the function takes variable number of arguments, make a frame index for
3677   // the start of the first vararg value... for expansion of llvm.va_start.
3678   if (isVarArg) {
3679     static const MCPhysReg GPArgRegs[] = {
3680       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3681       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3682     };
3683     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3684 
3685     static const MCPhysReg FPArgRegs[] = {
3686       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3687       PPC::F8
3688     };
3689     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3690 
3691     if (useSoftFloat() || hasSPE())
3692        NumFPArgRegs = 0;
3693 
3694     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3695     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3696 
3697     // Make room for NumGPArgRegs and NumFPArgRegs.
3698     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3699                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3700 
3701     FuncInfo->setVarArgsStackOffset(
3702       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3703                             CCInfo.getNextStackOffset(), true));
3704 
3705     FuncInfo->setVarArgsFrameIndex(
3706         MFI.CreateStackObject(Depth, Align(8), false));
3707     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3708 
3709     // The fixed integer arguments of a variadic function are stored to the
3710     // VarArgsFrameIndex on the stack so that they may be loaded by
3711     // dereferencing the result of va_next.
3712     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3713       // Get an existing live-in vreg, or add a new one.
3714       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3715       if (!VReg)
3716         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3717 
3718       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3719       SDValue Store =
3720           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3721       MemOps.push_back(Store);
3722       // Increment the address by four for the next argument to store
3723       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3724       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3725     }
3726 
3727     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3728     // is set.
3729     // The double arguments are stored to the VarArgsFrameIndex
3730     // on the stack.
3731     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3732       // Get an existing live-in vreg, or add a new one.
3733       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3734       if (!VReg)
3735         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3736 
3737       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3738       SDValue Store =
3739           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3740       MemOps.push_back(Store);
3741       // Increment the address by eight for the next argument to store
3742       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3743                                          PtrVT);
3744       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3745     }
3746   }
3747 
3748   if (!MemOps.empty())
3749     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3750 
3751   return Chain;
3752 }
3753 
3754 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3755 // value to MVT::i64 and then truncate to the correct register size.
3756 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3757                                              EVT ObjectVT, SelectionDAG &DAG,
3758                                              SDValue ArgVal,
3759                                              const SDLoc &dl) const {
3760   if (Flags.isSExt())
3761     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3762                          DAG.getValueType(ObjectVT));
3763   else if (Flags.isZExt())
3764     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3765                          DAG.getValueType(ObjectVT));
3766 
3767   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3768 }
3769 
3770 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3771     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3772     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3773     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3774   // TODO: add description of PPC stack frame format, or at least some docs.
3775   //
3776   bool isELFv2ABI = Subtarget.isELFv2ABI();
3777   bool isLittleEndian = Subtarget.isLittleEndian();
3778   MachineFunction &MF = DAG.getMachineFunction();
3779   MachineFrameInfo &MFI = MF.getFrameInfo();
3780   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3781 
3782   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3783          "fastcc not supported on varargs functions");
3784 
3785   EVT PtrVT = getPointerTy(MF.getDataLayout());
3786   // Potential tail calls could cause overwriting of argument stack slots.
3787   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3788                        (CallConv == CallingConv::Fast));
3789   unsigned PtrByteSize = 8;
3790   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3791 
3792   static const MCPhysReg GPR[] = {
3793     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3794     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3795   };
3796   static const MCPhysReg VR[] = {
3797     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3798     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3799   };
3800 
3801   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3802   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3803   const unsigned Num_VR_Regs  = array_lengthof(VR);
3804 
3805   // Do a first pass over the arguments to determine whether the ABI
3806   // guarantees that our caller has allocated the parameter save area
3807   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3808   // in the ELFv2 ABI, it is true if this is a vararg function or if
3809   // any parameter is located in a stack slot.
3810 
3811   bool HasParameterArea = !isELFv2ABI || isVarArg;
3812   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3813   unsigned NumBytes = LinkageSize;
3814   unsigned AvailableFPRs = Num_FPR_Regs;
3815   unsigned AvailableVRs = Num_VR_Regs;
3816   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3817     if (Ins[i].Flags.isNest())
3818       continue;
3819 
3820     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3821                                PtrByteSize, LinkageSize, ParamAreaSize,
3822                                NumBytes, AvailableFPRs, AvailableVRs))
3823       HasParameterArea = true;
3824   }
3825 
3826   // Add DAG nodes to load the arguments or copy them out of registers.  On
3827   // entry to a function on PPC, the arguments start after the linkage area,
3828   // although the first ones are often in registers.
3829 
3830   unsigned ArgOffset = LinkageSize;
3831   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3832   SmallVector<SDValue, 8> MemOps;
3833   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3834   unsigned CurArgIdx = 0;
3835   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3836     SDValue ArgVal;
3837     bool needsLoad = false;
3838     EVT ObjectVT = Ins[ArgNo].VT;
3839     EVT OrigVT = Ins[ArgNo].ArgVT;
3840     unsigned ObjSize = ObjectVT.getStoreSize();
3841     unsigned ArgSize = ObjSize;
3842     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3843     if (Ins[ArgNo].isOrigArg()) {
3844       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3845       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3846     }
3847     // We re-align the argument offset for each argument, except when using the
3848     // fast calling convention, when we need to make sure we do that only when
3849     // we'll actually use a stack slot.
3850     unsigned CurArgOffset;
3851     Align Alignment;
3852     auto ComputeArgOffset = [&]() {
3853       /* Respect alignment of argument on the stack.  */
3854       Alignment =
3855           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3856       ArgOffset = alignTo(ArgOffset, Alignment);
3857       CurArgOffset = ArgOffset;
3858     };
3859 
3860     if (CallConv != CallingConv::Fast) {
3861       ComputeArgOffset();
3862 
3863       /* Compute GPR index associated with argument offset.  */
3864       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3865       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3866     }
3867 
3868     // FIXME the codegen can be much improved in some cases.
3869     // We do not have to keep everything in memory.
3870     if (Flags.isByVal()) {
3871       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3872 
3873       if (CallConv == CallingConv::Fast)
3874         ComputeArgOffset();
3875 
3876       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3877       ObjSize = Flags.getByValSize();
3878       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3879       // Empty aggregate parameters do not take up registers.  Examples:
3880       //   struct { } a;
3881       //   union  { } b;
3882       //   int c[0];
3883       // etc.  However, we have to provide a place-holder in InVals, so
3884       // pretend we have an 8-byte item at the current address for that
3885       // purpose.
3886       if (!ObjSize) {
3887         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3888         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3889         InVals.push_back(FIN);
3890         continue;
3891       }
3892 
3893       // Create a stack object covering all stack doublewords occupied
3894       // by the argument.  If the argument is (fully or partially) on
3895       // the stack, or if the argument is fully in registers but the
3896       // caller has allocated the parameter save anyway, we can refer
3897       // directly to the caller's stack frame.  Otherwise, create a
3898       // local copy in our own frame.
3899       int FI;
3900       if (HasParameterArea ||
3901           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3902         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3903       else
3904         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3905       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3906 
3907       // Handle aggregates smaller than 8 bytes.
3908       if (ObjSize < PtrByteSize) {
3909         // The value of the object is its address, which differs from the
3910         // address of the enclosing doubleword on big-endian systems.
3911         SDValue Arg = FIN;
3912         if (!isLittleEndian) {
3913           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3914           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3915         }
3916         InVals.push_back(Arg);
3917 
3918         if (GPR_idx != Num_GPR_Regs) {
3919           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3920           FuncInfo->addLiveInAttr(VReg, Flags);
3921           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3922           SDValue Store;
3923 
3924           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3925             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3926                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3927             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3928                                       MachinePointerInfo(&*FuncArg), ObjType);
3929           } else {
3930             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3931             // store the whole register as-is to the parameter save area
3932             // slot.
3933             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3934                                  MachinePointerInfo(&*FuncArg));
3935           }
3936 
3937           MemOps.push_back(Store);
3938         }
3939         // Whether we copied from a register or not, advance the offset
3940         // into the parameter save area by a full doubleword.
3941         ArgOffset += PtrByteSize;
3942         continue;
3943       }
3944 
3945       // The value of the object is its address, which is the address of
3946       // its first stack doubleword.
3947       InVals.push_back(FIN);
3948 
3949       // Store whatever pieces of the object are in registers to memory.
3950       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3951         if (GPR_idx == Num_GPR_Regs)
3952           break;
3953 
3954         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3955         FuncInfo->addLiveInAttr(VReg, Flags);
3956         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3957         SDValue Addr = FIN;
3958         if (j) {
3959           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3960           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3961         }
3962         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3963                                      MachinePointerInfo(&*FuncArg, j));
3964         MemOps.push_back(Store);
3965         ++GPR_idx;
3966       }
3967       ArgOffset += ArgSize;
3968       continue;
3969     }
3970 
3971     switch (ObjectVT.getSimpleVT().SimpleTy) {
3972     default: llvm_unreachable("Unhandled argument type!");
3973     case MVT::i1:
3974     case MVT::i32:
3975     case MVT::i64:
3976       if (Flags.isNest()) {
3977         // The 'nest' parameter, if any, is passed in R11.
3978         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3979         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3980 
3981         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3982           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3983 
3984         break;
3985       }
3986 
3987       // These can be scalar arguments or elements of an integer array type
3988       // passed directly.  Clang may use those instead of "byval" aggregate
3989       // types to avoid forcing arguments to memory unnecessarily.
3990       if (GPR_idx != Num_GPR_Regs) {
3991         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3992         FuncInfo->addLiveInAttr(VReg, Flags);
3993         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3994 
3995         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3996           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3997           // value to MVT::i64 and then truncate to the correct register size.
3998           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3999       } else {
4000         if (CallConv == CallingConv::Fast)
4001           ComputeArgOffset();
4002 
4003         needsLoad = true;
4004         ArgSize = PtrByteSize;
4005       }
4006       if (CallConv != CallingConv::Fast || needsLoad)
4007         ArgOffset += 8;
4008       break;
4009 
4010     case MVT::f32:
4011     case MVT::f64:
4012       // These can be scalar arguments or elements of a float array type
4013       // passed directly.  The latter are used to implement ELFv2 homogenous
4014       // float aggregates.
4015       if (FPR_idx != Num_FPR_Regs) {
4016         unsigned VReg;
4017 
4018         if (ObjectVT == MVT::f32)
4019           VReg = MF.addLiveIn(FPR[FPR_idx],
4020                               Subtarget.hasP8Vector()
4021                                   ? &PPC::VSSRCRegClass
4022                                   : &PPC::F4RCRegClass);
4023         else
4024           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4025                                                 ? &PPC::VSFRCRegClass
4026                                                 : &PPC::F8RCRegClass);
4027 
4028         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4029         ++FPR_idx;
4030       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4031         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4032         // once we support fp <-> gpr moves.
4033 
4034         // This can only ever happen in the presence of f32 array types,
4035         // since otherwise we never run out of FPRs before running out
4036         // of GPRs.
4037         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4038         FuncInfo->addLiveInAttr(VReg, Flags);
4039         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4040 
4041         if (ObjectVT == MVT::f32) {
4042           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4043             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4044                                  DAG.getConstant(32, dl, MVT::i32));
4045           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4046         }
4047 
4048         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4049       } else {
4050         if (CallConv == CallingConv::Fast)
4051           ComputeArgOffset();
4052 
4053         needsLoad = true;
4054       }
4055 
4056       // When passing an array of floats, the array occupies consecutive
4057       // space in the argument area; only round up to the next doubleword
4058       // at the end of the array.  Otherwise, each float takes 8 bytes.
4059       if (CallConv != CallingConv::Fast || needsLoad) {
4060         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4061         ArgOffset += ArgSize;
4062         if (Flags.isInConsecutiveRegsLast())
4063           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4064       }
4065       break;
4066     case MVT::v4f32:
4067     case MVT::v4i32:
4068     case MVT::v8i16:
4069     case MVT::v16i8:
4070     case MVT::v2f64:
4071     case MVT::v2i64:
4072     case MVT::v1i128:
4073     case MVT::f128:
4074       // These can be scalar arguments or elements of a vector array type
4075       // passed directly.  The latter are used to implement ELFv2 homogenous
4076       // vector aggregates.
4077       if (VR_idx != Num_VR_Regs) {
4078         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4079         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4080         ++VR_idx;
4081       } else {
4082         if (CallConv == CallingConv::Fast)
4083           ComputeArgOffset();
4084         needsLoad = true;
4085       }
4086       if (CallConv != CallingConv::Fast || needsLoad)
4087         ArgOffset += 16;
4088       break;
4089     }
4090 
4091     // We need to load the argument to a virtual register if we determined
4092     // above that we ran out of physical registers of the appropriate type.
4093     if (needsLoad) {
4094       if (ObjSize < ArgSize && !isLittleEndian)
4095         CurArgOffset += ArgSize - ObjSize;
4096       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4097       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4098       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4099     }
4100 
4101     InVals.push_back(ArgVal);
4102   }
4103 
4104   // Area that is at least reserved in the caller of this function.
4105   unsigned MinReservedArea;
4106   if (HasParameterArea)
4107     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4108   else
4109     MinReservedArea = LinkageSize;
4110 
4111   // Set the size that is at least reserved in caller of this function.  Tail
4112   // call optimized functions' reserved stack space needs to be aligned so that
4113   // taking the difference between two stack areas will result in an aligned
4114   // stack.
4115   MinReservedArea =
4116       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4117   FuncInfo->setMinReservedArea(MinReservedArea);
4118 
4119   // If the function takes variable number of arguments, make a frame index for
4120   // the start of the first vararg value... for expansion of llvm.va_start.
4121   // On ELFv2ABI spec, it writes:
4122   // C programs that are intended to be *portable* across different compilers
4123   // and architectures must use the header file <stdarg.h> to deal with variable
4124   // argument lists.
4125   if (isVarArg && MFI.hasVAStart()) {
4126     int Depth = ArgOffset;
4127 
4128     FuncInfo->setVarArgsFrameIndex(
4129       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4130     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4131 
4132     // If this function is vararg, store any remaining integer argument regs
4133     // to their spots on the stack so that they may be loaded by dereferencing
4134     // the result of va_next.
4135     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4136          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4137       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4138       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4139       SDValue Store =
4140           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4141       MemOps.push_back(Store);
4142       // Increment the address by four for the next argument to store
4143       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4144       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4145     }
4146   }
4147 
4148   if (!MemOps.empty())
4149     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4150 
4151   return Chain;
4152 }
4153 
4154 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4155     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4156     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4157     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4158   // TODO: add description of PPC stack frame format, or at least some docs.
4159   //
4160   MachineFunction &MF = DAG.getMachineFunction();
4161   MachineFrameInfo &MFI = MF.getFrameInfo();
4162   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4163 
4164   EVT PtrVT = getPointerTy(MF.getDataLayout());
4165   bool isPPC64 = PtrVT == MVT::i64;
4166   // Potential tail calls could cause overwriting of argument stack slots.
4167   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4168                        (CallConv == CallingConv::Fast));
4169   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4170   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4171   unsigned ArgOffset = LinkageSize;
4172   // Area that is at least reserved in caller of this function.
4173   unsigned MinReservedArea = ArgOffset;
4174 
4175   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4176     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4177     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4178   };
4179   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4180     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4181     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4182   };
4183   static const MCPhysReg VR[] = {
4184     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4185     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4186   };
4187 
4188   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4189   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4190   const unsigned Num_VR_Regs  = array_lengthof( VR);
4191 
4192   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4193 
4194   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4195 
4196   // In 32-bit non-varargs functions, the stack space for vectors is after the
4197   // stack space for non-vectors.  We do not use this space unless we have
4198   // too many vectors to fit in registers, something that only occurs in
4199   // constructed examples:), but we have to walk the arglist to figure
4200   // that out...for the pathological case, compute VecArgOffset as the
4201   // start of the vector parameter area.  Computing VecArgOffset is the
4202   // entire point of the following loop.
4203   unsigned VecArgOffset = ArgOffset;
4204   if (!isVarArg && !isPPC64) {
4205     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4206          ++ArgNo) {
4207       EVT ObjectVT = Ins[ArgNo].VT;
4208       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4209 
4210       if (Flags.isByVal()) {
4211         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4212         unsigned ObjSize = Flags.getByValSize();
4213         unsigned ArgSize =
4214                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4215         VecArgOffset += ArgSize;
4216         continue;
4217       }
4218 
4219       switch(ObjectVT.getSimpleVT().SimpleTy) {
4220       default: llvm_unreachable("Unhandled argument type!");
4221       case MVT::i1:
4222       case MVT::i32:
4223       case MVT::f32:
4224         VecArgOffset += 4;
4225         break;
4226       case MVT::i64:  // PPC64
4227       case MVT::f64:
4228         // FIXME: We are guaranteed to be !isPPC64 at this point.
4229         // Does MVT::i64 apply?
4230         VecArgOffset += 8;
4231         break;
4232       case MVT::v4f32:
4233       case MVT::v4i32:
4234       case MVT::v8i16:
4235       case MVT::v16i8:
4236         // Nothing to do, we're only looking at Nonvector args here.
4237         break;
4238       }
4239     }
4240   }
4241   // We've found where the vector parameter area in memory is.  Skip the
4242   // first 12 parameters; these don't use that memory.
4243   VecArgOffset = ((VecArgOffset+15)/16)*16;
4244   VecArgOffset += 12*16;
4245 
4246   // Add DAG nodes to load the arguments or copy them out of registers.  On
4247   // entry to a function on PPC, the arguments start after the linkage area,
4248   // although the first ones are often in registers.
4249 
4250   SmallVector<SDValue, 8> MemOps;
4251   unsigned nAltivecParamsAtEnd = 0;
4252   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4253   unsigned CurArgIdx = 0;
4254   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4255     SDValue ArgVal;
4256     bool needsLoad = false;
4257     EVT ObjectVT = Ins[ArgNo].VT;
4258     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4259     unsigned ArgSize = ObjSize;
4260     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4261     if (Ins[ArgNo].isOrigArg()) {
4262       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4263       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4264     }
4265     unsigned CurArgOffset = ArgOffset;
4266 
4267     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4268     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4269         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4270       if (isVarArg || isPPC64) {
4271         MinReservedArea = ((MinReservedArea+15)/16)*16;
4272         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4273                                                   Flags,
4274                                                   PtrByteSize);
4275       } else  nAltivecParamsAtEnd++;
4276     } else
4277       // Calculate min reserved area.
4278       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4279                                                 Flags,
4280                                                 PtrByteSize);
4281 
4282     // FIXME the codegen can be much improved in some cases.
4283     // We do not have to keep everything in memory.
4284     if (Flags.isByVal()) {
4285       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4286 
4287       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4288       ObjSize = Flags.getByValSize();
4289       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4290       // Objects of size 1 and 2 are right justified, everything else is
4291       // left justified.  This means the memory address is adjusted forwards.
4292       if (ObjSize==1 || ObjSize==2) {
4293         CurArgOffset = CurArgOffset + (4 - ObjSize);
4294       }
4295       // The value of the object is its address.
4296       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4297       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4298       InVals.push_back(FIN);
4299       if (ObjSize==1 || ObjSize==2) {
4300         if (GPR_idx != Num_GPR_Regs) {
4301           unsigned VReg;
4302           if (isPPC64)
4303             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4304           else
4305             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4306           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4307           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4308           SDValue Store =
4309               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4310                                 MachinePointerInfo(&*FuncArg), ObjType);
4311           MemOps.push_back(Store);
4312           ++GPR_idx;
4313         }
4314 
4315         ArgOffset += PtrByteSize;
4316 
4317         continue;
4318       }
4319       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4320         // Store whatever pieces of the object are in registers
4321         // to memory.  ArgOffset will be the address of the beginning
4322         // of the object.
4323         if (GPR_idx != Num_GPR_Regs) {
4324           unsigned VReg;
4325           if (isPPC64)
4326             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4327           else
4328             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4329           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4330           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4331           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4332           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4333                                        MachinePointerInfo(&*FuncArg, j));
4334           MemOps.push_back(Store);
4335           ++GPR_idx;
4336           ArgOffset += PtrByteSize;
4337         } else {
4338           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4339           break;
4340         }
4341       }
4342       continue;
4343     }
4344 
4345     switch (ObjectVT.getSimpleVT().SimpleTy) {
4346     default: llvm_unreachable("Unhandled argument type!");
4347     case MVT::i1:
4348     case MVT::i32:
4349       if (!isPPC64) {
4350         if (GPR_idx != Num_GPR_Regs) {
4351           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4352           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4353 
4354           if (ObjectVT == MVT::i1)
4355             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4356 
4357           ++GPR_idx;
4358         } else {
4359           needsLoad = true;
4360           ArgSize = PtrByteSize;
4361         }
4362         // All int arguments reserve stack space in the Darwin ABI.
4363         ArgOffset += PtrByteSize;
4364         break;
4365       }
4366       LLVM_FALLTHROUGH;
4367     case MVT::i64:  // PPC64
4368       if (GPR_idx != Num_GPR_Regs) {
4369         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4370         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4371 
4372         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4373           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4374           // value to MVT::i64 and then truncate to the correct register size.
4375           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4376 
4377         ++GPR_idx;
4378       } else {
4379         needsLoad = true;
4380         ArgSize = PtrByteSize;
4381       }
4382       // All int arguments reserve stack space in the Darwin ABI.
4383       ArgOffset += 8;
4384       break;
4385 
4386     case MVT::f32:
4387     case MVT::f64:
4388       // Every 4 bytes of argument space consumes one of the GPRs available for
4389       // argument passing.
4390       if (GPR_idx != Num_GPR_Regs) {
4391         ++GPR_idx;
4392         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4393           ++GPR_idx;
4394       }
4395       if (FPR_idx != Num_FPR_Regs) {
4396         unsigned VReg;
4397 
4398         if (ObjectVT == MVT::f32)
4399           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4400         else
4401           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4402 
4403         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4404         ++FPR_idx;
4405       } else {
4406         needsLoad = true;
4407       }
4408 
4409       // All FP arguments reserve stack space in the Darwin ABI.
4410       ArgOffset += isPPC64 ? 8 : ObjSize;
4411       break;
4412     case MVT::v4f32:
4413     case MVT::v4i32:
4414     case MVT::v8i16:
4415     case MVT::v16i8:
4416       // Note that vector arguments in registers don't reserve stack space,
4417       // except in varargs functions.
4418       if (VR_idx != Num_VR_Regs) {
4419         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4420         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4421         if (isVarArg) {
4422           while ((ArgOffset % 16) != 0) {
4423             ArgOffset += PtrByteSize;
4424             if (GPR_idx != Num_GPR_Regs)
4425               GPR_idx++;
4426           }
4427           ArgOffset += 16;
4428           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4429         }
4430         ++VR_idx;
4431       } else {
4432         if (!isVarArg && !isPPC64) {
4433           // Vectors go after all the nonvectors.
4434           CurArgOffset = VecArgOffset;
4435           VecArgOffset += 16;
4436         } else {
4437           // Vectors are aligned.
4438           ArgOffset = ((ArgOffset+15)/16)*16;
4439           CurArgOffset = ArgOffset;
4440           ArgOffset += 16;
4441         }
4442         needsLoad = true;
4443       }
4444       break;
4445     }
4446 
4447     // We need to load the argument to a virtual register if we determined above
4448     // that we ran out of physical registers of the appropriate type.
4449     if (needsLoad) {
4450       int FI = MFI.CreateFixedObject(ObjSize,
4451                                      CurArgOffset + (ArgSize - ObjSize),
4452                                      isImmutable);
4453       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4454       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4455     }
4456 
4457     InVals.push_back(ArgVal);
4458   }
4459 
4460   // Allow for Altivec parameters at the end, if needed.
4461   if (nAltivecParamsAtEnd) {
4462     MinReservedArea = ((MinReservedArea+15)/16)*16;
4463     MinReservedArea += 16*nAltivecParamsAtEnd;
4464   }
4465 
4466   // Area that is at least reserved in the caller of this function.
4467   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4468 
4469   // Set the size that is at least reserved in caller of this function.  Tail
4470   // call optimized functions' reserved stack space needs to be aligned so that
4471   // taking the difference between two stack areas will result in an aligned
4472   // stack.
4473   MinReservedArea =
4474       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4475   FuncInfo->setMinReservedArea(MinReservedArea);
4476 
4477   // If the function takes variable number of arguments, make a frame index for
4478   // the start of the first vararg value... for expansion of llvm.va_start.
4479   if (isVarArg) {
4480     int Depth = ArgOffset;
4481 
4482     FuncInfo->setVarArgsFrameIndex(
4483       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4484                             Depth, true));
4485     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4486 
4487     // If this function is vararg, store any remaining integer argument regs
4488     // to their spots on the stack so that they may be loaded by dereferencing
4489     // the result of va_next.
4490     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4491       unsigned VReg;
4492 
4493       if (isPPC64)
4494         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4495       else
4496         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4497 
4498       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4499       SDValue Store =
4500           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4501       MemOps.push_back(Store);
4502       // Increment the address by four for the next argument to store
4503       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4504       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4505     }
4506   }
4507 
4508   if (!MemOps.empty())
4509     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4510 
4511   return Chain;
4512 }
4513 
4514 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4515 /// adjusted to accommodate the arguments for the tailcall.
4516 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4517                                    unsigned ParamSize) {
4518 
4519   if (!isTailCall) return 0;
4520 
4521   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4522   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4523   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4524   // Remember only if the new adjustment is bigger.
4525   if (SPDiff < FI->getTailCallSPDelta())
4526     FI->setTailCallSPDelta(SPDiff);
4527 
4528   return SPDiff;
4529 }
4530 
4531 static bool isFunctionGlobalAddress(SDValue Callee);
4532 
4533 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4534                               const TargetMachine &TM) {
4535   // It does not make sense to call callsShareTOCBase() with a caller that
4536   // is PC Relative since PC Relative callers do not have a TOC.
4537 #ifndef NDEBUG
4538   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4539   assert(!STICaller->isUsingPCRelativeCalls() &&
4540          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4541 #endif
4542 
4543   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4544   // don't have enough information to determine if the caller and callee share
4545   // the same  TOC base, so we have to pessimistically assume they don't for
4546   // correctness.
4547   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4548   if (!G)
4549     return false;
4550 
4551   const GlobalValue *GV = G->getGlobal();
4552 
4553   // If the callee is preemptable, then the static linker will use a plt-stub
4554   // which saves the toc to the stack, and needs a nop after the call
4555   // instruction to convert to a toc-restore.
4556   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4557     return false;
4558 
4559   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4560   // We may need a TOC restore in the situation where the caller requires a
4561   // valid TOC but the callee is PC Relative and does not.
4562   const Function *F = dyn_cast<Function>(GV);
4563   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4564 
4565   // If we have an Alias we can try to get the function from there.
4566   if (Alias) {
4567     const GlobalObject *GlobalObj = Alias->getBaseObject();
4568     F = dyn_cast<Function>(GlobalObj);
4569   }
4570 
4571   // If we still have no valid function pointer we do not have enough
4572   // information to determine if the callee uses PC Relative calls so we must
4573   // assume that it does.
4574   if (!F)
4575     return false;
4576 
4577   // If the callee uses PC Relative we cannot guarantee that the callee won't
4578   // clobber the TOC of the caller and so we must assume that the two
4579   // functions do not share a TOC base.
4580   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4581   if (STICallee->isUsingPCRelativeCalls())
4582     return false;
4583 
4584   // The medium and large code models are expected to provide a sufficiently
4585   // large TOC to provide all data addressing needs of a module with a
4586   // single TOC.
4587   if (CodeModel::Medium == TM.getCodeModel() ||
4588       CodeModel::Large == TM.getCodeModel())
4589     return true;
4590 
4591   // Otherwise we need to ensure callee and caller are in the same section,
4592   // since the linker may allocate multiple TOCs, and we don't know which
4593   // sections will belong to the same TOC base.
4594   if (!GV->isStrongDefinitionForLinker())
4595     return false;
4596 
4597   // Any explicitly-specified sections and section prefixes must also match.
4598   // Also, if we're using -ffunction-sections, then each function is always in
4599   // a different section (the same is true for COMDAT functions).
4600   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4601       GV->getSection() != Caller->getSection())
4602     return false;
4603   if (const auto *F = dyn_cast<Function>(GV)) {
4604     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4605       return false;
4606   }
4607 
4608   return true;
4609 }
4610 
4611 static bool
4612 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4613                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4614   assert(Subtarget.is64BitELFABI());
4615 
4616   const unsigned PtrByteSize = 8;
4617   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4618 
4619   static const MCPhysReg GPR[] = {
4620     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4621     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4622   };
4623   static const MCPhysReg VR[] = {
4624     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4625     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4626   };
4627 
4628   const unsigned NumGPRs = array_lengthof(GPR);
4629   const unsigned NumFPRs = 13;
4630   const unsigned NumVRs = array_lengthof(VR);
4631   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4632 
4633   unsigned NumBytes = LinkageSize;
4634   unsigned AvailableFPRs = NumFPRs;
4635   unsigned AvailableVRs = NumVRs;
4636 
4637   for (const ISD::OutputArg& Param : Outs) {
4638     if (Param.Flags.isNest()) continue;
4639 
4640     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4641                                LinkageSize, ParamAreaSize, NumBytes,
4642                                AvailableFPRs, AvailableVRs))
4643       return true;
4644   }
4645   return false;
4646 }
4647 
4648 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4649   if (CB.arg_size() != CallerFn->arg_size())
4650     return false;
4651 
4652   auto CalleeArgIter = CB.arg_begin();
4653   auto CalleeArgEnd = CB.arg_end();
4654   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4655 
4656   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4657     const Value* CalleeArg = *CalleeArgIter;
4658     const Value* CallerArg = &(*CallerArgIter);
4659     if (CalleeArg == CallerArg)
4660       continue;
4661 
4662     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4663     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4664     //      }
4665     // 1st argument of callee is undef and has the same type as caller.
4666     if (CalleeArg->getType() == CallerArg->getType() &&
4667         isa<UndefValue>(CalleeArg))
4668       continue;
4669 
4670     return false;
4671   }
4672 
4673   return true;
4674 }
4675 
4676 // Returns true if TCO is possible between the callers and callees
4677 // calling conventions.
4678 static bool
4679 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4680                                     CallingConv::ID CalleeCC) {
4681   // Tail calls are possible with fastcc and ccc.
4682   auto isTailCallableCC  = [] (CallingConv::ID CC){
4683       return  CC == CallingConv::C || CC == CallingConv::Fast;
4684   };
4685   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4686     return false;
4687 
4688   // We can safely tail call both fastcc and ccc callees from a c calling
4689   // convention caller. If the caller is fastcc, we may have less stack space
4690   // than a non-fastcc caller with the same signature so disable tail-calls in
4691   // that case.
4692   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4693 }
4694 
4695 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4696     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4697     const SmallVectorImpl<ISD::OutputArg> &Outs,
4698     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4699   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4700 
4701   if (DisableSCO && !TailCallOpt) return false;
4702 
4703   // Variadic argument functions are not supported.
4704   if (isVarArg) return false;
4705 
4706   auto &Caller = DAG.getMachineFunction().getFunction();
4707   // Check that the calling conventions are compatible for tco.
4708   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4709     return false;
4710 
4711   // Caller contains any byval parameter is not supported.
4712   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4713     return false;
4714 
4715   // Callee contains any byval parameter is not supported, too.
4716   // Note: This is a quick work around, because in some cases, e.g.
4717   // caller's stack size > callee's stack size, we are still able to apply
4718   // sibling call optimization. For example, gcc is able to do SCO for caller1
4719   // in the following example, but not for caller2.
4720   //   struct test {
4721   //     long int a;
4722   //     char ary[56];
4723   //   } gTest;
4724   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4725   //     b->a = v.a;
4726   //     return 0;
4727   //   }
4728   //   void caller1(struct test a, struct test c, struct test *b) {
4729   //     callee(gTest, b); }
4730   //   void caller2(struct test *b) { callee(gTest, b); }
4731   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4732     return false;
4733 
4734   // If callee and caller use different calling conventions, we cannot pass
4735   // parameters on stack since offsets for the parameter area may be different.
4736   if (Caller.getCallingConv() != CalleeCC &&
4737       needStackSlotPassParameters(Subtarget, Outs))
4738     return false;
4739 
4740   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4741   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4742   // callee potentially have different TOC bases then we cannot tail call since
4743   // we need to restore the TOC pointer after the call.
4744   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4745   // We cannot guarantee this for indirect calls or calls to external functions.
4746   // When PC-Relative addressing is used, the concept of the TOC is no longer
4747   // applicable so this check is not required.
4748   // Check first for indirect calls.
4749   if (!Subtarget.isUsingPCRelativeCalls() &&
4750       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4751     return false;
4752 
4753   // Check if we share the TOC base.
4754   if (!Subtarget.isUsingPCRelativeCalls() &&
4755       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4756     return false;
4757 
4758   // TCO allows altering callee ABI, so we don't have to check further.
4759   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4760     return true;
4761 
4762   if (DisableSCO) return false;
4763 
4764   // If callee use the same argument list that caller is using, then we can
4765   // apply SCO on this case. If it is not, then we need to check if callee needs
4766   // stack for passing arguments.
4767   // PC Relative tail calls may not have a CallBase.
4768   // If there is no CallBase we cannot verify if we have the same argument
4769   // list so assume that we don't have the same argument list.
4770   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4771       needStackSlotPassParameters(Subtarget, Outs))
4772     return false;
4773   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4774     return false;
4775 
4776   return true;
4777 }
4778 
4779 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4780 /// for tail call optimization. Targets which want to do tail call
4781 /// optimization should implement this function.
4782 bool
4783 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4784                                                      CallingConv::ID CalleeCC,
4785                                                      bool isVarArg,
4786                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4787                                                      SelectionDAG& DAG) const {
4788   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4789     return false;
4790 
4791   // Variable argument functions are not supported.
4792   if (isVarArg)
4793     return false;
4794 
4795   MachineFunction &MF = DAG.getMachineFunction();
4796   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4797   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4798     // Functions containing by val parameters are not supported.
4799     for (unsigned i = 0; i != Ins.size(); i++) {
4800        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4801        if (Flags.isByVal()) return false;
4802     }
4803 
4804     // Non-PIC/GOT tail calls are supported.
4805     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4806       return true;
4807 
4808     // At the moment we can only do local tail calls (in same module, hidden
4809     // or protected) if we are generating PIC.
4810     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4811       return G->getGlobal()->hasHiddenVisibility()
4812           || G->getGlobal()->hasProtectedVisibility();
4813   }
4814 
4815   return false;
4816 }
4817 
4818 /// isCallCompatibleAddress - Return the immediate to use if the specified
4819 /// 32-bit value is representable in the immediate field of a BxA instruction.
4820 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4821   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4822   if (!C) return nullptr;
4823 
4824   int Addr = C->getZExtValue();
4825   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4826       SignExtend32<26>(Addr) != Addr)
4827     return nullptr;  // Top 6 bits have to be sext of immediate.
4828 
4829   return DAG
4830       .getConstant(
4831           (int)C->getZExtValue() >> 2, SDLoc(Op),
4832           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4833       .getNode();
4834 }
4835 
4836 namespace {
4837 
4838 struct TailCallArgumentInfo {
4839   SDValue Arg;
4840   SDValue FrameIdxOp;
4841   int FrameIdx = 0;
4842 
4843   TailCallArgumentInfo() = default;
4844 };
4845 
4846 } // end anonymous namespace
4847 
4848 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4849 static void StoreTailCallArgumentsToStackSlot(
4850     SelectionDAG &DAG, SDValue Chain,
4851     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4852     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4853   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4854     SDValue Arg = TailCallArgs[i].Arg;
4855     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4856     int FI = TailCallArgs[i].FrameIdx;
4857     // Store relative to framepointer.
4858     MemOpChains.push_back(DAG.getStore(
4859         Chain, dl, Arg, FIN,
4860         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4861   }
4862 }
4863 
4864 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4865 /// the appropriate stack slot for the tail call optimized function call.
4866 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4867                                              SDValue OldRetAddr, SDValue OldFP,
4868                                              int SPDiff, const SDLoc &dl) {
4869   if (SPDiff) {
4870     // Calculate the new stack slot for the return address.
4871     MachineFunction &MF = DAG.getMachineFunction();
4872     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4873     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4874     bool isPPC64 = Subtarget.isPPC64();
4875     int SlotSize = isPPC64 ? 8 : 4;
4876     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4877     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4878                                                          NewRetAddrLoc, true);
4879     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4880     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4881     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4882                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4883   }
4884   return Chain;
4885 }
4886 
4887 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4888 /// the position of the argument.
4889 static void
4890 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4891                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4892                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4893   int Offset = ArgOffset + SPDiff;
4894   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4895   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4896   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4897   SDValue FIN = DAG.getFrameIndex(FI, VT);
4898   TailCallArgumentInfo Info;
4899   Info.Arg = Arg;
4900   Info.FrameIdxOp = FIN;
4901   Info.FrameIdx = FI;
4902   TailCallArguments.push_back(Info);
4903 }
4904 
4905 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4906 /// stack slot. Returns the chain as result and the loaded frame pointers in
4907 /// LROpOut/FPOpout. Used when tail calling.
4908 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4909     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4910     SDValue &FPOpOut, const SDLoc &dl) const {
4911   if (SPDiff) {
4912     // Load the LR and FP stack slot for later adjusting.
4913     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4914     LROpOut = getReturnAddrFrameIndex(DAG);
4915     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4916     Chain = SDValue(LROpOut.getNode(), 1);
4917   }
4918   return Chain;
4919 }
4920 
4921 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4922 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4923 /// specified by the specific parameter attribute. The copy will be passed as
4924 /// a byval function parameter.
4925 /// Sometimes what we are copying is the end of a larger object, the part that
4926 /// does not fit in registers.
4927 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4928                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4929                                          SelectionDAG &DAG, const SDLoc &dl) {
4930   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4931   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4932                        Flags.getNonZeroByValAlign(), false, false, false,
4933                        MachinePointerInfo(), MachinePointerInfo());
4934 }
4935 
4936 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4937 /// tail calls.
4938 static void LowerMemOpCallTo(
4939     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4940     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4941     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4942     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4943   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4944   if (!isTailCall) {
4945     if (isVector) {
4946       SDValue StackPtr;
4947       if (isPPC64)
4948         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4949       else
4950         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4951       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4952                            DAG.getConstant(ArgOffset, dl, PtrVT));
4953     }
4954     MemOpChains.push_back(
4955         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4956     // Calculate and remember argument location.
4957   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4958                                   TailCallArguments);
4959 }
4960 
4961 static void
4962 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4963                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4964                 SDValue FPOp,
4965                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4966   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4967   // might overwrite each other in case of tail call optimization.
4968   SmallVector<SDValue, 8> MemOpChains2;
4969   // Do not flag preceding copytoreg stuff together with the following stuff.
4970   InFlag = SDValue();
4971   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4972                                     MemOpChains2, dl);
4973   if (!MemOpChains2.empty())
4974     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4975 
4976   // Store the return address to the appropriate stack slot.
4977   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4978 
4979   // Emit callseq_end just before tailcall node.
4980   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4981                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4982   InFlag = Chain.getValue(1);
4983 }
4984 
4985 // Is this global address that of a function that can be called by name? (as
4986 // opposed to something that must hold a descriptor for an indirect call).
4987 static bool isFunctionGlobalAddress(SDValue Callee) {
4988   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4989     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4990         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4991       return false;
4992 
4993     return G->getGlobal()->getValueType()->isFunctionTy();
4994   }
4995 
4996   return false;
4997 }
4998 
4999 SDValue PPCTargetLowering::LowerCallResult(
5000     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5001     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5002     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5003   SmallVector<CCValAssign, 16> RVLocs;
5004   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5005                     *DAG.getContext());
5006 
5007   CCRetInfo.AnalyzeCallResult(
5008       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5009                ? RetCC_PPC_Cold
5010                : RetCC_PPC);
5011 
5012   // Copy all of the result registers out of their specified physreg.
5013   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5014     CCValAssign &VA = RVLocs[i];
5015     assert(VA.isRegLoc() && "Can only return in registers!");
5016 
5017     SDValue Val;
5018 
5019     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5020       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5021                                       InFlag);
5022       Chain = Lo.getValue(1);
5023       InFlag = Lo.getValue(2);
5024       VA = RVLocs[++i]; // skip ahead to next loc
5025       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5026                                       InFlag);
5027       Chain = Hi.getValue(1);
5028       InFlag = Hi.getValue(2);
5029       if (!Subtarget.isLittleEndian())
5030         std::swap (Lo, Hi);
5031       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5032     } else {
5033       Val = DAG.getCopyFromReg(Chain, dl,
5034                                VA.getLocReg(), VA.getLocVT(), InFlag);
5035       Chain = Val.getValue(1);
5036       InFlag = Val.getValue(2);
5037     }
5038 
5039     switch (VA.getLocInfo()) {
5040     default: llvm_unreachable("Unknown loc info!");
5041     case CCValAssign::Full: break;
5042     case CCValAssign::AExt:
5043       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5044       break;
5045     case CCValAssign::ZExt:
5046       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5047                         DAG.getValueType(VA.getValVT()));
5048       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5049       break;
5050     case CCValAssign::SExt:
5051       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5052                         DAG.getValueType(VA.getValVT()));
5053       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5054       break;
5055     }
5056 
5057     InVals.push_back(Val);
5058   }
5059 
5060   return Chain;
5061 }
5062 
5063 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5064                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5065   // PatchPoint calls are not indirect.
5066   if (isPatchPoint)
5067     return false;
5068 
5069   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5070     return false;
5071 
5072   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5073   // becuase the immediate function pointer points to a descriptor instead of
5074   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5075   // pointer immediate points to the global entry point, while the BLA would
5076   // need to jump to the local entry point (see rL211174).
5077   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5078       isBLACompatibleAddress(Callee, DAG))
5079     return false;
5080 
5081   return true;
5082 }
5083 
5084 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5085 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5086   return Subtarget.isAIXABI() ||
5087          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5088 }
5089 
5090 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5091                               const Function &Caller,
5092                               const SDValue &Callee,
5093                               const PPCSubtarget &Subtarget,
5094                               const TargetMachine &TM) {
5095   if (CFlags.IsTailCall)
5096     return PPCISD::TC_RETURN;
5097 
5098   // This is a call through a function pointer.
5099   if (CFlags.IsIndirect) {
5100     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5101     // indirect calls. The save of the caller's TOC pointer to the stack will be
5102     // inserted into the DAG as part of call lowering. The restore of the TOC
5103     // pointer is modeled by using a pseudo instruction for the call opcode that
5104     // represents the 2 instruction sequence of an indirect branch and link,
5105     // immediately followed by a load of the TOC pointer from the the stack save
5106     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5107     // as it is not saved or used.
5108     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5109                                                : PPCISD::BCTRL;
5110   }
5111 
5112   if (Subtarget.isUsingPCRelativeCalls()) {
5113     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5114     return PPCISD::CALL_NOTOC;
5115   }
5116 
5117   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5118   // immediately following the call instruction if the caller and callee may
5119   // have different TOC bases. At link time if the linker determines the calls
5120   // may not share a TOC base, the call is redirected to a trampoline inserted
5121   // by the linker. The trampoline will (among other things) save the callers
5122   // TOC pointer at an ABI designated offset in the linkage area and the linker
5123   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5124   // into gpr2.
5125   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5126     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5127                                                   : PPCISD::CALL_NOP;
5128 
5129   return PPCISD::CALL;
5130 }
5131 
5132 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5133                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5134   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5135     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5136       return SDValue(Dest, 0);
5137 
5138   // Returns true if the callee is local, and false otherwise.
5139   auto isLocalCallee = [&]() {
5140     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5141     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5142     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5143 
5144     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5145            !dyn_cast_or_null<GlobalIFunc>(GV);
5146   };
5147 
5148   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5149   // a static relocation model causes some versions of GNU LD (2.17.50, at
5150   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5151   // built with secure-PLT.
5152   bool UsePlt =
5153       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5154       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5155 
5156   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5157     const TargetMachine &TM = Subtarget.getTargetMachine();
5158     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5159     MCSymbolXCOFF *S =
5160         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5161 
5162     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5163     return DAG.getMCSymbol(S, PtrVT);
5164   };
5165 
5166   if (isFunctionGlobalAddress(Callee)) {
5167     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5168 
5169     if (Subtarget.isAIXABI()) {
5170       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5171       return getAIXFuncEntryPointSymbolSDNode(GV);
5172     }
5173     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5174                                       UsePlt ? PPCII::MO_PLT : 0);
5175   }
5176 
5177   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5178     const char *SymName = S->getSymbol();
5179     if (Subtarget.isAIXABI()) {
5180       // If there exists a user-declared function whose name is the same as the
5181       // ExternalSymbol's, then we pick up the user-declared version.
5182       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5183       if (const Function *F =
5184               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5185         return getAIXFuncEntryPointSymbolSDNode(F);
5186 
5187       // On AIX, direct function calls reference the symbol for the function's
5188       // entry point, which is named by prepending a "." before the function's
5189       // C-linkage name. A Qualname is returned here because an external
5190       // function entry point is a csect with XTY_ER property.
5191       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5192         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5193         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5194             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5195             SectionKind::getMetadata());
5196         return Sec->getQualNameSymbol();
5197       };
5198 
5199       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5200     }
5201     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5202                                        UsePlt ? PPCII::MO_PLT : 0);
5203   }
5204 
5205   // No transformation needed.
5206   assert(Callee.getNode() && "What no callee?");
5207   return Callee;
5208 }
5209 
5210 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5211   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5212          "Expected a CALLSEQ_STARTSDNode.");
5213 
5214   // The last operand is the chain, except when the node has glue. If the node
5215   // has glue, then the last operand is the glue, and the chain is the second
5216   // last operand.
5217   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5218   if (LastValue.getValueType() != MVT::Glue)
5219     return LastValue;
5220 
5221   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5222 }
5223 
5224 // Creates the node that moves a functions address into the count register
5225 // to prepare for an indirect call instruction.
5226 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5227                                 SDValue &Glue, SDValue &Chain,
5228                                 const SDLoc &dl) {
5229   SDValue MTCTROps[] = {Chain, Callee, Glue};
5230   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5231   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5232                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5233   // The glue is the second value produced.
5234   Glue = Chain.getValue(1);
5235 }
5236 
5237 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5238                                           SDValue &Glue, SDValue &Chain,
5239                                           SDValue CallSeqStart,
5240                                           const CallBase *CB, const SDLoc &dl,
5241                                           bool hasNest,
5242                                           const PPCSubtarget &Subtarget) {
5243   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5244   // entry point, but to the function descriptor (the function entry point
5245   // address is part of the function descriptor though).
5246   // The function descriptor is a three doubleword structure with the
5247   // following fields: function entry point, TOC base address and
5248   // environment pointer.
5249   // Thus for a call through a function pointer, the following actions need
5250   // to be performed:
5251   //   1. Save the TOC of the caller in the TOC save area of its stack
5252   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5253   //   2. Load the address of the function entry point from the function
5254   //      descriptor.
5255   //   3. Load the TOC of the callee from the function descriptor into r2.
5256   //   4. Load the environment pointer from the function descriptor into
5257   //      r11.
5258   //   5. Branch to the function entry point address.
5259   //   6. On return of the callee, the TOC of the caller needs to be
5260   //      restored (this is done in FinishCall()).
5261   //
5262   // The loads are scheduled at the beginning of the call sequence, and the
5263   // register copies are flagged together to ensure that no other
5264   // operations can be scheduled in between. E.g. without flagging the
5265   // copies together, a TOC access in the caller could be scheduled between
5266   // the assignment of the callee TOC and the branch to the callee, which leads
5267   // to incorrect code.
5268 
5269   // Start by loading the function address from the descriptor.
5270   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5271   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5272                       ? (MachineMemOperand::MODereferenceable |
5273                          MachineMemOperand::MOInvariant)
5274                       : MachineMemOperand::MONone;
5275 
5276   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5277 
5278   // Registers used in building the DAG.
5279   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5280   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5281 
5282   // Offsets of descriptor members.
5283   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5284   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5285 
5286   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5287   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5288 
5289   // One load for the functions entry point address.
5290   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5291                                     Alignment, MMOFlags);
5292 
5293   // One for loading the TOC anchor for the module that contains the called
5294   // function.
5295   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5296   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5297   SDValue TOCPtr =
5298       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5299                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5300 
5301   // One for loading the environment pointer.
5302   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5303   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5304   SDValue LoadEnvPtr =
5305       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5306                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5307 
5308 
5309   // Then copy the newly loaded TOC anchor to the TOC pointer.
5310   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5311   Chain = TOCVal.getValue(0);
5312   Glue = TOCVal.getValue(1);
5313 
5314   // If the function call has an explicit 'nest' parameter, it takes the
5315   // place of the environment pointer.
5316   assert((!hasNest || !Subtarget.isAIXABI()) &&
5317          "Nest parameter is not supported on AIX.");
5318   if (!hasNest) {
5319     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5320     Chain = EnvVal.getValue(0);
5321     Glue = EnvVal.getValue(1);
5322   }
5323 
5324   // The rest of the indirect call sequence is the same as the non-descriptor
5325   // DAG.
5326   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5327 }
5328 
5329 static void
5330 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5331                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5332                   SelectionDAG &DAG,
5333                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5334                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5335                   const PPCSubtarget &Subtarget) {
5336   const bool IsPPC64 = Subtarget.isPPC64();
5337   // MVT for a general purpose register.
5338   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5339 
5340   // First operand is always the chain.
5341   Ops.push_back(Chain);
5342 
5343   // If it's a direct call pass the callee as the second operand.
5344   if (!CFlags.IsIndirect)
5345     Ops.push_back(Callee);
5346   else {
5347     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5348 
5349     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5350     // on the stack (this would have been done in `LowerCall_64SVR4` or
5351     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5352     // represents both the indirect branch and a load that restores the TOC
5353     // pointer from the linkage area. The operand for the TOC restore is an add
5354     // of the TOC save offset to the stack pointer. This must be the second
5355     // operand: after the chain input but before any other variadic arguments.
5356     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5357     // saved or used.
5358     if (isTOCSaveRestoreRequired(Subtarget)) {
5359       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5360 
5361       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5362       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5363       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5364       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5365       Ops.push_back(AddTOC);
5366     }
5367 
5368     // Add the register used for the environment pointer.
5369     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5370       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5371                                     RegVT));
5372 
5373 
5374     // Add CTR register as callee so a bctr can be emitted later.
5375     if (CFlags.IsTailCall)
5376       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5377   }
5378 
5379   // If this is a tail call add stack pointer delta.
5380   if (CFlags.IsTailCall)
5381     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5382 
5383   // Add argument registers to the end of the list so that they are known live
5384   // into the call.
5385   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5386     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5387                                   RegsToPass[i].second.getValueType()));
5388 
5389   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5390   // no way to mark dependencies as implicit here.
5391   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5392   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5393        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5394     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5395 
5396   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5397   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5398     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5399 
5400   // Add a register mask operand representing the call-preserved registers.
5401   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5402   const uint32_t *Mask =
5403       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5404   assert(Mask && "Missing call preserved mask for calling convention");
5405   Ops.push_back(DAG.getRegisterMask(Mask));
5406 
5407   // If the glue is valid, it is the last operand.
5408   if (Glue.getNode())
5409     Ops.push_back(Glue);
5410 }
5411 
5412 SDValue PPCTargetLowering::FinishCall(
5413     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5414     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5415     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5416     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5417     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5418 
5419   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5420       Subtarget.isAIXABI())
5421     setUsesTOCBasePtr(DAG);
5422 
5423   unsigned CallOpc =
5424       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5425                     Subtarget, DAG.getTarget());
5426 
5427   if (!CFlags.IsIndirect)
5428     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5429   else if (Subtarget.usesFunctionDescriptors())
5430     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5431                                   dl, CFlags.HasNest, Subtarget);
5432   else
5433     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5434 
5435   // Build the operand list for the call instruction.
5436   SmallVector<SDValue, 8> Ops;
5437   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5438                     SPDiff, Subtarget);
5439 
5440   // Emit tail call.
5441   if (CFlags.IsTailCall) {
5442     // Indirect tail call when using PC Relative calls do not have the same
5443     // constraints.
5444     assert(((Callee.getOpcode() == ISD::Register &&
5445              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5446             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5447             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5448             isa<ConstantSDNode>(Callee) ||
5449             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5450            "Expecting a global address, external symbol, absolute value, "
5451            "register or an indirect tail call when PC Relative calls are "
5452            "used.");
5453     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5454     assert(CallOpc == PPCISD::TC_RETURN &&
5455            "Unexpected call opcode for a tail call.");
5456     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5457     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5458   }
5459 
5460   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5461   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5462   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5463   Glue = Chain.getValue(1);
5464 
5465   // When performing tail call optimization the callee pops its arguments off
5466   // the stack. Account for this here so these bytes can be pushed back on in
5467   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5468   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5469                          getTargetMachine().Options.GuaranteedTailCallOpt)
5470                             ? NumBytes
5471                             : 0;
5472 
5473   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5474                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5475                              Glue, dl);
5476   Glue = Chain.getValue(1);
5477 
5478   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5479                          DAG, InVals);
5480 }
5481 
5482 SDValue
5483 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5484                              SmallVectorImpl<SDValue> &InVals) const {
5485   SelectionDAG &DAG                     = CLI.DAG;
5486   SDLoc &dl                             = CLI.DL;
5487   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5488   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5489   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5490   SDValue Chain                         = CLI.Chain;
5491   SDValue Callee                        = CLI.Callee;
5492   bool &isTailCall                      = CLI.IsTailCall;
5493   CallingConv::ID CallConv              = CLI.CallConv;
5494   bool isVarArg                         = CLI.IsVarArg;
5495   bool isPatchPoint                     = CLI.IsPatchPoint;
5496   const CallBase *CB                    = CLI.CB;
5497 
5498   if (isTailCall) {
5499     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5500       isTailCall = false;
5501     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5502       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5503           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5504     else
5505       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5506                                                      Ins, DAG);
5507     if (isTailCall) {
5508       ++NumTailCalls;
5509       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5510         ++NumSiblingCalls;
5511 
5512       // PC Relative calls no longer guarantee that the callee is a Global
5513       // Address Node. The callee could be an indirect tail call in which
5514       // case the SDValue for the callee could be a load (to load the address
5515       // of a function pointer) or it may be a register copy (to move the
5516       // address of the callee from a function parameter into a virtual
5517       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5518       assert((Subtarget.isUsingPCRelativeCalls() ||
5519               isa<GlobalAddressSDNode>(Callee)) &&
5520              "Callee should be an llvm::Function object.");
5521 
5522       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5523                         << "\nTCO callee: ");
5524       LLVM_DEBUG(Callee.dump());
5525     }
5526   }
5527 
5528   if (!isTailCall && CB && CB->isMustTailCall())
5529     report_fatal_error("failed to perform tail call elimination on a call "
5530                        "site marked musttail");
5531 
5532   // When long calls (i.e. indirect calls) are always used, calls are always
5533   // made via function pointer. If we have a function name, first translate it
5534   // into a pointer.
5535   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5536       !isTailCall)
5537     Callee = LowerGlobalAddress(Callee, DAG);
5538 
5539   CallFlags CFlags(
5540       CallConv, isTailCall, isVarArg, isPatchPoint,
5541       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5542       // hasNest
5543       Subtarget.is64BitELFABI() &&
5544           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5545       CLI.NoMerge);
5546 
5547   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5548     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5549                             InVals, CB);
5550 
5551   if (Subtarget.isSVR4ABI())
5552     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5553                             InVals, CB);
5554 
5555   if (Subtarget.isAIXABI())
5556     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5557                          InVals, CB);
5558 
5559   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5560                           InVals, CB);
5561 }
5562 
5563 SDValue PPCTargetLowering::LowerCall_32SVR4(
5564     SDValue Chain, SDValue Callee, CallFlags CFlags,
5565     const SmallVectorImpl<ISD::OutputArg> &Outs,
5566     const SmallVectorImpl<SDValue> &OutVals,
5567     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5568     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5569     const CallBase *CB) const {
5570   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5571   // of the 32-bit SVR4 ABI stack frame layout.
5572 
5573   const CallingConv::ID CallConv = CFlags.CallConv;
5574   const bool IsVarArg = CFlags.IsVarArg;
5575   const bool IsTailCall = CFlags.IsTailCall;
5576 
5577   assert((CallConv == CallingConv::C ||
5578           CallConv == CallingConv::Cold ||
5579           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5580 
5581   const Align PtrAlign(4);
5582 
5583   MachineFunction &MF = DAG.getMachineFunction();
5584 
5585   // Mark this function as potentially containing a function that contains a
5586   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5587   // and restoring the callers stack pointer in this functions epilog. This is
5588   // done because by tail calling the called function might overwrite the value
5589   // in this function's (MF) stack pointer stack slot 0(SP).
5590   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5591       CallConv == CallingConv::Fast)
5592     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5593 
5594   // Count how many bytes are to be pushed on the stack, including the linkage
5595   // area, parameter list area and the part of the local variable space which
5596   // contains copies of aggregates which are passed by value.
5597 
5598   // Assign locations to all of the outgoing arguments.
5599   SmallVector<CCValAssign, 16> ArgLocs;
5600   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5601 
5602   // Reserve space for the linkage area on the stack.
5603   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5604                        PtrAlign);
5605   if (useSoftFloat())
5606     CCInfo.PreAnalyzeCallOperands(Outs);
5607 
5608   if (IsVarArg) {
5609     // Handle fixed and variable vector arguments differently.
5610     // Fixed vector arguments go into registers as long as registers are
5611     // available. Variable vector arguments always go into memory.
5612     unsigned NumArgs = Outs.size();
5613 
5614     for (unsigned i = 0; i != NumArgs; ++i) {
5615       MVT ArgVT = Outs[i].VT;
5616       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5617       bool Result;
5618 
5619       if (Outs[i].IsFixed) {
5620         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5621                                CCInfo);
5622       } else {
5623         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5624                                       ArgFlags, CCInfo);
5625       }
5626 
5627       if (Result) {
5628 #ifndef NDEBUG
5629         errs() << "Call operand #" << i << " has unhandled type "
5630              << EVT(ArgVT).getEVTString() << "\n";
5631 #endif
5632         llvm_unreachable(nullptr);
5633       }
5634     }
5635   } else {
5636     // All arguments are treated the same.
5637     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5638   }
5639   CCInfo.clearWasPPCF128();
5640 
5641   // Assign locations to all of the outgoing aggregate by value arguments.
5642   SmallVector<CCValAssign, 16> ByValArgLocs;
5643   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5644 
5645   // Reserve stack space for the allocations in CCInfo.
5646   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5647 
5648   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5649 
5650   // Size of the linkage area, parameter list area and the part of the local
5651   // space variable where copies of aggregates which are passed by value are
5652   // stored.
5653   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5654 
5655   // Calculate by how many bytes the stack has to be adjusted in case of tail
5656   // call optimization.
5657   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5658 
5659   // Adjust the stack pointer for the new arguments...
5660   // These operations are automatically eliminated by the prolog/epilog pass
5661   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5662   SDValue CallSeqStart = Chain;
5663 
5664   // Load the return address and frame pointer so it can be moved somewhere else
5665   // later.
5666   SDValue LROp, FPOp;
5667   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5668 
5669   // Set up a copy of the stack pointer for use loading and storing any
5670   // arguments that may not fit in the registers available for argument
5671   // passing.
5672   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5673 
5674   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5675   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5676   SmallVector<SDValue, 8> MemOpChains;
5677 
5678   bool seenFloatArg = false;
5679   // Walk the register/memloc assignments, inserting copies/loads.
5680   // i - Tracks the index into the list of registers allocated for the call
5681   // RealArgIdx - Tracks the index into the list of actual function arguments
5682   // j - Tracks the index into the list of byval arguments
5683   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5684        i != e;
5685        ++i, ++RealArgIdx) {
5686     CCValAssign &VA = ArgLocs[i];
5687     SDValue Arg = OutVals[RealArgIdx];
5688     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5689 
5690     if (Flags.isByVal()) {
5691       // Argument is an aggregate which is passed by value, thus we need to
5692       // create a copy of it in the local variable space of the current stack
5693       // frame (which is the stack frame of the caller) and pass the address of
5694       // this copy to the callee.
5695       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5696       CCValAssign &ByValVA = ByValArgLocs[j++];
5697       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5698 
5699       // Memory reserved in the local variable space of the callers stack frame.
5700       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5701 
5702       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5703       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5704                            StackPtr, PtrOff);
5705 
5706       // Create a copy of the argument in the local area of the current
5707       // stack frame.
5708       SDValue MemcpyCall =
5709         CreateCopyOfByValArgument(Arg, PtrOff,
5710                                   CallSeqStart.getNode()->getOperand(0),
5711                                   Flags, DAG, dl);
5712 
5713       // This must go outside the CALLSEQ_START..END.
5714       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5715                                                      SDLoc(MemcpyCall));
5716       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5717                              NewCallSeqStart.getNode());
5718       Chain = CallSeqStart = NewCallSeqStart;
5719 
5720       // Pass the address of the aggregate copy on the stack either in a
5721       // physical register or in the parameter list area of the current stack
5722       // frame to the callee.
5723       Arg = PtrOff;
5724     }
5725 
5726     // When useCRBits() is true, there can be i1 arguments.
5727     // It is because getRegisterType(MVT::i1) => MVT::i1,
5728     // and for other integer types getRegisterType() => MVT::i32.
5729     // Extend i1 and ensure callee will get i32.
5730     if (Arg.getValueType() == MVT::i1)
5731       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5732                         dl, MVT::i32, Arg);
5733 
5734     if (VA.isRegLoc()) {
5735       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5736       // Put argument in a physical register.
5737       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5738         bool IsLE = Subtarget.isLittleEndian();
5739         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5740                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5741         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5742         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5743                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5744         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5745                              SVal.getValue(0)));
5746       } else
5747         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5748     } else {
5749       // Put argument in the parameter list area of the current stack frame.
5750       assert(VA.isMemLoc());
5751       unsigned LocMemOffset = VA.getLocMemOffset();
5752 
5753       if (!IsTailCall) {
5754         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5755         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5756                              StackPtr, PtrOff);
5757 
5758         MemOpChains.push_back(
5759             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5760       } else {
5761         // Calculate and remember argument location.
5762         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5763                                  TailCallArguments);
5764       }
5765     }
5766   }
5767 
5768   if (!MemOpChains.empty())
5769     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5770 
5771   // Build a sequence of copy-to-reg nodes chained together with token chain
5772   // and flag operands which copy the outgoing args into the appropriate regs.
5773   SDValue InFlag;
5774   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5775     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5776                              RegsToPass[i].second, InFlag);
5777     InFlag = Chain.getValue(1);
5778   }
5779 
5780   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5781   // registers.
5782   if (IsVarArg) {
5783     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5784     SDValue Ops[] = { Chain, InFlag };
5785 
5786     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5787                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5788 
5789     InFlag = Chain.getValue(1);
5790   }
5791 
5792   if (IsTailCall)
5793     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5794                     TailCallArguments);
5795 
5796   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5797                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5798 }
5799 
5800 // Copy an argument into memory, being careful to do this outside the
5801 // call sequence for the call to which the argument belongs.
5802 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5803     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5804     SelectionDAG &DAG, const SDLoc &dl) const {
5805   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5806                         CallSeqStart.getNode()->getOperand(0),
5807                         Flags, DAG, dl);
5808   // The MEMCPY must go outside the CALLSEQ_START..END.
5809   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5810   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5811                                                  SDLoc(MemcpyCall));
5812   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5813                          NewCallSeqStart.getNode());
5814   return NewCallSeqStart;
5815 }
5816 
5817 SDValue PPCTargetLowering::LowerCall_64SVR4(
5818     SDValue Chain, SDValue Callee, CallFlags CFlags,
5819     const SmallVectorImpl<ISD::OutputArg> &Outs,
5820     const SmallVectorImpl<SDValue> &OutVals,
5821     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5822     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5823     const CallBase *CB) const {
5824   bool isELFv2ABI = Subtarget.isELFv2ABI();
5825   bool isLittleEndian = Subtarget.isLittleEndian();
5826   unsigned NumOps = Outs.size();
5827   bool IsSibCall = false;
5828   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5829 
5830   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5831   unsigned PtrByteSize = 8;
5832 
5833   MachineFunction &MF = DAG.getMachineFunction();
5834 
5835   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5836     IsSibCall = true;
5837 
5838   // Mark this function as potentially containing a function that contains a
5839   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5840   // and restoring the callers stack pointer in this functions epilog. This is
5841   // done because by tail calling the called function might overwrite the value
5842   // in this function's (MF) stack pointer stack slot 0(SP).
5843   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5844     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5845 
5846   assert(!(IsFastCall && CFlags.IsVarArg) &&
5847          "fastcc not supported on varargs functions");
5848 
5849   // Count how many bytes are to be pushed on the stack, including the linkage
5850   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5851   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5852   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5853   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5854   unsigned NumBytes = LinkageSize;
5855   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5856 
5857   static const MCPhysReg GPR[] = {
5858     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5859     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5860   };
5861   static const MCPhysReg VR[] = {
5862     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5863     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5864   };
5865 
5866   const unsigned NumGPRs = array_lengthof(GPR);
5867   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5868   const unsigned NumVRs  = array_lengthof(VR);
5869 
5870   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5871   // can be passed to the callee in registers.
5872   // For the fast calling convention, there is another check below.
5873   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5874   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5875   if (!HasParameterArea) {
5876     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5877     unsigned AvailableFPRs = NumFPRs;
5878     unsigned AvailableVRs = NumVRs;
5879     unsigned NumBytesTmp = NumBytes;
5880     for (unsigned i = 0; i != NumOps; ++i) {
5881       if (Outs[i].Flags.isNest()) continue;
5882       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5883                                  PtrByteSize, LinkageSize, ParamAreaSize,
5884                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5885         HasParameterArea = true;
5886     }
5887   }
5888 
5889   // When using the fast calling convention, we don't provide backing for
5890   // arguments that will be in registers.
5891   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5892 
5893   // Avoid allocating parameter area for fastcc functions if all the arguments
5894   // can be passed in the registers.
5895   if (IsFastCall)
5896     HasParameterArea = false;
5897 
5898   // Add up all the space actually used.
5899   for (unsigned i = 0; i != NumOps; ++i) {
5900     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5901     EVT ArgVT = Outs[i].VT;
5902     EVT OrigVT = Outs[i].ArgVT;
5903 
5904     if (Flags.isNest())
5905       continue;
5906 
5907     if (IsFastCall) {
5908       if (Flags.isByVal()) {
5909         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5910         if (NumGPRsUsed > NumGPRs)
5911           HasParameterArea = true;
5912       } else {
5913         switch (ArgVT.getSimpleVT().SimpleTy) {
5914         default: llvm_unreachable("Unexpected ValueType for argument!");
5915         case MVT::i1:
5916         case MVT::i32:
5917         case MVT::i64:
5918           if (++NumGPRsUsed <= NumGPRs)
5919             continue;
5920           break;
5921         case MVT::v4i32:
5922         case MVT::v8i16:
5923         case MVT::v16i8:
5924         case MVT::v2f64:
5925         case MVT::v2i64:
5926         case MVT::v1i128:
5927         case MVT::f128:
5928           if (++NumVRsUsed <= NumVRs)
5929             continue;
5930           break;
5931         case MVT::v4f32:
5932           if (++NumVRsUsed <= NumVRs)
5933             continue;
5934           break;
5935         case MVT::f32:
5936         case MVT::f64:
5937           if (++NumFPRsUsed <= NumFPRs)
5938             continue;
5939           break;
5940         }
5941         HasParameterArea = true;
5942       }
5943     }
5944 
5945     /* Respect alignment of argument on the stack.  */
5946     auto Alignement =
5947         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5948     NumBytes = alignTo(NumBytes, Alignement);
5949 
5950     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5951     if (Flags.isInConsecutiveRegsLast())
5952       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5953   }
5954 
5955   unsigned NumBytesActuallyUsed = NumBytes;
5956 
5957   // In the old ELFv1 ABI,
5958   // the prolog code of the callee may store up to 8 GPR argument registers to
5959   // the stack, allowing va_start to index over them in memory if its varargs.
5960   // Because we cannot tell if this is needed on the caller side, we have to
5961   // conservatively assume that it is needed.  As such, make sure we have at
5962   // least enough stack space for the caller to store the 8 GPRs.
5963   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5964   // really requires memory operands, e.g. a vararg function.
5965   if (HasParameterArea)
5966     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5967   else
5968     NumBytes = LinkageSize;
5969 
5970   // Tail call needs the stack to be aligned.
5971   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5972     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5973 
5974   int SPDiff = 0;
5975 
5976   // Calculate by how many bytes the stack has to be adjusted in case of tail
5977   // call optimization.
5978   if (!IsSibCall)
5979     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5980 
5981   // To protect arguments on the stack from being clobbered in a tail call,
5982   // force all the loads to happen before doing any other lowering.
5983   if (CFlags.IsTailCall)
5984     Chain = DAG.getStackArgumentTokenFactor(Chain);
5985 
5986   // Adjust the stack pointer for the new arguments...
5987   // These operations are automatically eliminated by the prolog/epilog pass
5988   if (!IsSibCall)
5989     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5990   SDValue CallSeqStart = Chain;
5991 
5992   // Load the return address and frame pointer so it can be move somewhere else
5993   // later.
5994   SDValue LROp, FPOp;
5995   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5996 
5997   // Set up a copy of the stack pointer for use loading and storing any
5998   // arguments that may not fit in the registers available for argument
5999   // passing.
6000   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6001 
6002   // Figure out which arguments are going to go in registers, and which in
6003   // memory.  Also, if this is a vararg function, floating point operations
6004   // must be stored to our stack, and loaded into integer regs as well, if
6005   // any integer regs are available for argument passing.
6006   unsigned ArgOffset = LinkageSize;
6007 
6008   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6009   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6010 
6011   SmallVector<SDValue, 8> MemOpChains;
6012   for (unsigned i = 0; i != NumOps; ++i) {
6013     SDValue Arg = OutVals[i];
6014     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6015     EVT ArgVT = Outs[i].VT;
6016     EVT OrigVT = Outs[i].ArgVT;
6017 
6018     // PtrOff will be used to store the current argument to the stack if a
6019     // register cannot be found for it.
6020     SDValue PtrOff;
6021 
6022     // We re-align the argument offset for each argument, except when using the
6023     // fast calling convention, when we need to make sure we do that only when
6024     // we'll actually use a stack slot.
6025     auto ComputePtrOff = [&]() {
6026       /* Respect alignment of argument on the stack.  */
6027       auto Alignment =
6028           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6029       ArgOffset = alignTo(ArgOffset, Alignment);
6030 
6031       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6032 
6033       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6034     };
6035 
6036     if (!IsFastCall) {
6037       ComputePtrOff();
6038 
6039       /* Compute GPR index associated with argument offset.  */
6040       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6041       GPR_idx = std::min(GPR_idx, NumGPRs);
6042     }
6043 
6044     // Promote integers to 64-bit values.
6045     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6046       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6047       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6048       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6049     }
6050 
6051     // FIXME memcpy is used way more than necessary.  Correctness first.
6052     // Note: "by value" is code for passing a structure by value, not
6053     // basic types.
6054     if (Flags.isByVal()) {
6055       // Note: Size includes alignment padding, so
6056       //   struct x { short a; char b; }
6057       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6058       // These are the proper values we need for right-justifying the
6059       // aggregate in a parameter register.
6060       unsigned Size = Flags.getByValSize();
6061 
6062       // An empty aggregate parameter takes up no storage and no
6063       // registers.
6064       if (Size == 0)
6065         continue;
6066 
6067       if (IsFastCall)
6068         ComputePtrOff();
6069 
6070       // All aggregates smaller than 8 bytes must be passed right-justified.
6071       if (Size==1 || Size==2 || Size==4) {
6072         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6073         if (GPR_idx != NumGPRs) {
6074           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6075                                         MachinePointerInfo(), VT);
6076           MemOpChains.push_back(Load.getValue(1));
6077           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6078 
6079           ArgOffset += PtrByteSize;
6080           continue;
6081         }
6082       }
6083 
6084       if (GPR_idx == NumGPRs && Size < 8) {
6085         SDValue AddPtr = PtrOff;
6086         if (!isLittleEndian) {
6087           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6088                                           PtrOff.getValueType());
6089           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6090         }
6091         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6092                                                           CallSeqStart,
6093                                                           Flags, DAG, dl);
6094         ArgOffset += PtrByteSize;
6095         continue;
6096       }
6097       // Copy entire object into memory.  There are cases where gcc-generated
6098       // code assumes it is there, even if it could be put entirely into
6099       // registers.  (This is not what the doc says.)
6100 
6101       // FIXME: The above statement is likely due to a misunderstanding of the
6102       // documents.  All arguments must be copied into the parameter area BY
6103       // THE CALLEE in the event that the callee takes the address of any
6104       // formal argument.  That has not yet been implemented.  However, it is
6105       // reasonable to use the stack area as a staging area for the register
6106       // load.
6107 
6108       // Skip this for small aggregates, as we will use the same slot for a
6109       // right-justified copy, below.
6110       if (Size >= 8)
6111         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6112                                                           CallSeqStart,
6113                                                           Flags, DAG, dl);
6114 
6115       // When a register is available, pass a small aggregate right-justified.
6116       if (Size < 8 && GPR_idx != NumGPRs) {
6117         // The easiest way to get this right-justified in a register
6118         // is to copy the structure into the rightmost portion of a
6119         // local variable slot, then load the whole slot into the
6120         // register.
6121         // FIXME: The memcpy seems to produce pretty awful code for
6122         // small aggregates, particularly for packed ones.
6123         // FIXME: It would be preferable to use the slot in the
6124         // parameter save area instead of a new local variable.
6125         SDValue AddPtr = PtrOff;
6126         if (!isLittleEndian) {
6127           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6128           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6129         }
6130         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6131                                                           CallSeqStart,
6132                                                           Flags, DAG, dl);
6133 
6134         // Load the slot into the register.
6135         SDValue Load =
6136             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6137         MemOpChains.push_back(Load.getValue(1));
6138         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6139 
6140         // Done with this argument.
6141         ArgOffset += PtrByteSize;
6142         continue;
6143       }
6144 
6145       // For aggregates larger than PtrByteSize, copy the pieces of the
6146       // object that fit into registers from the parameter save area.
6147       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6148         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6149         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6150         if (GPR_idx != NumGPRs) {
6151           SDValue Load =
6152               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6153           MemOpChains.push_back(Load.getValue(1));
6154           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6155           ArgOffset += PtrByteSize;
6156         } else {
6157           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6158           break;
6159         }
6160       }
6161       continue;
6162     }
6163 
6164     switch (Arg.getSimpleValueType().SimpleTy) {
6165     default: llvm_unreachable("Unexpected ValueType for argument!");
6166     case MVT::i1:
6167     case MVT::i32:
6168     case MVT::i64:
6169       if (Flags.isNest()) {
6170         // The 'nest' parameter, if any, is passed in R11.
6171         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6172         break;
6173       }
6174 
6175       // These can be scalar arguments or elements of an integer array type
6176       // passed directly.  Clang may use those instead of "byval" aggregate
6177       // types to avoid forcing arguments to memory unnecessarily.
6178       if (GPR_idx != NumGPRs) {
6179         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6180       } else {
6181         if (IsFastCall)
6182           ComputePtrOff();
6183 
6184         assert(HasParameterArea &&
6185                "Parameter area must exist to pass an argument in memory.");
6186         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6187                          true, CFlags.IsTailCall, false, MemOpChains,
6188                          TailCallArguments, dl);
6189         if (IsFastCall)
6190           ArgOffset += PtrByteSize;
6191       }
6192       if (!IsFastCall)
6193         ArgOffset += PtrByteSize;
6194       break;
6195     case MVT::f32:
6196     case MVT::f64: {
6197       // These can be scalar arguments or elements of a float array type
6198       // passed directly.  The latter are used to implement ELFv2 homogenous
6199       // float aggregates.
6200 
6201       // Named arguments go into FPRs first, and once they overflow, the
6202       // remaining arguments go into GPRs and then the parameter save area.
6203       // Unnamed arguments for vararg functions always go to GPRs and
6204       // then the parameter save area.  For now, put all arguments to vararg
6205       // routines always in both locations (FPR *and* GPR or stack slot).
6206       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6207       bool NeededLoad = false;
6208 
6209       // First load the argument into the next available FPR.
6210       if (FPR_idx != NumFPRs)
6211         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6212 
6213       // Next, load the argument into GPR or stack slot if needed.
6214       if (!NeedGPROrStack)
6215         ;
6216       else if (GPR_idx != NumGPRs && !IsFastCall) {
6217         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6218         // once we support fp <-> gpr moves.
6219 
6220         // In the non-vararg case, this can only ever happen in the
6221         // presence of f32 array types, since otherwise we never run
6222         // out of FPRs before running out of GPRs.
6223         SDValue ArgVal;
6224 
6225         // Double values are always passed in a single GPR.
6226         if (Arg.getValueType() != MVT::f32) {
6227           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6228 
6229         // Non-array float values are extended and passed in a GPR.
6230         } else if (!Flags.isInConsecutiveRegs()) {
6231           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6232           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6233 
6234         // If we have an array of floats, we collect every odd element
6235         // together with its predecessor into one GPR.
6236         } else if (ArgOffset % PtrByteSize != 0) {
6237           SDValue Lo, Hi;
6238           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6239           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6240           if (!isLittleEndian)
6241             std::swap(Lo, Hi);
6242           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6243 
6244         // The final element, if even, goes into the first half of a GPR.
6245         } else if (Flags.isInConsecutiveRegsLast()) {
6246           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6247           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6248           if (!isLittleEndian)
6249             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6250                                  DAG.getConstant(32, dl, MVT::i32));
6251 
6252         // Non-final even elements are skipped; they will be handled
6253         // together the with subsequent argument on the next go-around.
6254         } else
6255           ArgVal = SDValue();
6256 
6257         if (ArgVal.getNode())
6258           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6259       } else {
6260         if (IsFastCall)
6261           ComputePtrOff();
6262 
6263         // Single-precision floating-point values are mapped to the
6264         // second (rightmost) word of the stack doubleword.
6265         if (Arg.getValueType() == MVT::f32 &&
6266             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6267           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6268           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6269         }
6270 
6271         assert(HasParameterArea &&
6272                "Parameter area must exist to pass an argument in memory.");
6273         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6274                          true, CFlags.IsTailCall, false, MemOpChains,
6275                          TailCallArguments, dl);
6276 
6277         NeededLoad = true;
6278       }
6279       // When passing an array of floats, the array occupies consecutive
6280       // space in the argument area; only round up to the next doubleword
6281       // at the end of the array.  Otherwise, each float takes 8 bytes.
6282       if (!IsFastCall || NeededLoad) {
6283         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6284                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6285         if (Flags.isInConsecutiveRegsLast())
6286           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6287       }
6288       break;
6289     }
6290     case MVT::v4f32:
6291     case MVT::v4i32:
6292     case MVT::v8i16:
6293     case MVT::v16i8:
6294     case MVT::v2f64:
6295     case MVT::v2i64:
6296     case MVT::v1i128:
6297     case MVT::f128:
6298       // These can be scalar arguments or elements of a vector array type
6299       // passed directly.  The latter are used to implement ELFv2 homogenous
6300       // vector aggregates.
6301 
6302       // For a varargs call, named arguments go into VRs or on the stack as
6303       // usual; unnamed arguments always go to the stack or the corresponding
6304       // GPRs when within range.  For now, we always put the value in both
6305       // locations (or even all three).
6306       if (CFlags.IsVarArg) {
6307         assert(HasParameterArea &&
6308                "Parameter area must exist if we have a varargs call.");
6309         // We could elide this store in the case where the object fits
6310         // entirely in R registers.  Maybe later.
6311         SDValue Store =
6312             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6313         MemOpChains.push_back(Store);
6314         if (VR_idx != NumVRs) {
6315           SDValue Load =
6316               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6317           MemOpChains.push_back(Load.getValue(1));
6318           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6319         }
6320         ArgOffset += 16;
6321         for (unsigned i=0; i<16; i+=PtrByteSize) {
6322           if (GPR_idx == NumGPRs)
6323             break;
6324           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6325                                    DAG.getConstant(i, dl, PtrVT));
6326           SDValue Load =
6327               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6328           MemOpChains.push_back(Load.getValue(1));
6329           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6330         }
6331         break;
6332       }
6333 
6334       // Non-varargs Altivec params go into VRs or on the stack.
6335       if (VR_idx != NumVRs) {
6336         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6337       } else {
6338         if (IsFastCall)
6339           ComputePtrOff();
6340 
6341         assert(HasParameterArea &&
6342                "Parameter area must exist to pass an argument in memory.");
6343         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6344                          true, CFlags.IsTailCall, true, MemOpChains,
6345                          TailCallArguments, dl);
6346         if (IsFastCall)
6347           ArgOffset += 16;
6348       }
6349 
6350       if (!IsFastCall)
6351         ArgOffset += 16;
6352       break;
6353     }
6354   }
6355 
6356   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6357          "mismatch in size of parameter area");
6358   (void)NumBytesActuallyUsed;
6359 
6360   if (!MemOpChains.empty())
6361     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6362 
6363   // Check if this is an indirect call (MTCTR/BCTRL).
6364   // See prepareDescriptorIndirectCall and buildCallOperands for more
6365   // information about calls through function pointers in the 64-bit SVR4 ABI.
6366   if (CFlags.IsIndirect) {
6367     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6368     // caller in the TOC save area.
6369     if (isTOCSaveRestoreRequired(Subtarget)) {
6370       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6371       // Load r2 into a virtual register and store it to the TOC save area.
6372       setUsesTOCBasePtr(DAG);
6373       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6374       // TOC save area offset.
6375       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6376       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6377       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6378       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6379                            MachinePointerInfo::getStack(
6380                                DAG.getMachineFunction(), TOCSaveOffset));
6381     }
6382     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6383     // This does not mean the MTCTR instruction must use R12; it's easier
6384     // to model this as an extra parameter, so do that.
6385     if (isELFv2ABI && !CFlags.IsPatchPoint)
6386       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6387   }
6388 
6389   // Build a sequence of copy-to-reg nodes chained together with token chain
6390   // and flag operands which copy the outgoing args into the appropriate regs.
6391   SDValue InFlag;
6392   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6393     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6394                              RegsToPass[i].second, InFlag);
6395     InFlag = Chain.getValue(1);
6396   }
6397 
6398   if (CFlags.IsTailCall && !IsSibCall)
6399     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6400                     TailCallArguments);
6401 
6402   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6403                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6404 }
6405 
6406 SDValue PPCTargetLowering::LowerCall_Darwin(
6407     SDValue Chain, SDValue Callee, CallFlags CFlags,
6408     const SmallVectorImpl<ISD::OutputArg> &Outs,
6409     const SmallVectorImpl<SDValue> &OutVals,
6410     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6411     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6412     const CallBase *CB) const {
6413   unsigned NumOps = Outs.size();
6414 
6415   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6416   bool isPPC64 = PtrVT == MVT::i64;
6417   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6418 
6419   MachineFunction &MF = DAG.getMachineFunction();
6420 
6421   // Mark this function as potentially containing a function that contains a
6422   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6423   // and restoring the callers stack pointer in this functions epilog. This is
6424   // done because by tail calling the called function might overwrite the value
6425   // in this function's (MF) stack pointer stack slot 0(SP).
6426   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6427       CFlags.CallConv == CallingConv::Fast)
6428     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6429 
6430   // Count how many bytes are to be pushed on the stack, including the linkage
6431   // area, and parameter passing area.  We start with 24/48 bytes, which is
6432   // prereserved space for [SP][CR][LR][3 x unused].
6433   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6434   unsigned NumBytes = LinkageSize;
6435 
6436   // Add up all the space actually used.
6437   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6438   // they all go in registers, but we must reserve stack space for them for
6439   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6440   // assigned stack space in order, with padding so Altivec parameters are
6441   // 16-byte aligned.
6442   unsigned nAltivecParamsAtEnd = 0;
6443   for (unsigned i = 0; i != NumOps; ++i) {
6444     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6445     EVT ArgVT = Outs[i].VT;
6446     // Varargs Altivec parameters are padded to a 16 byte boundary.
6447     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6448         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6449         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6450       if (!CFlags.IsVarArg && !isPPC64) {
6451         // Non-varargs Altivec parameters go after all the non-Altivec
6452         // parameters; handle those later so we know how much padding we need.
6453         nAltivecParamsAtEnd++;
6454         continue;
6455       }
6456       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6457       NumBytes = ((NumBytes+15)/16)*16;
6458     }
6459     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6460   }
6461 
6462   // Allow for Altivec parameters at the end, if needed.
6463   if (nAltivecParamsAtEnd) {
6464     NumBytes = ((NumBytes+15)/16)*16;
6465     NumBytes += 16*nAltivecParamsAtEnd;
6466   }
6467 
6468   // The prolog code of the callee may store up to 8 GPR argument registers to
6469   // the stack, allowing va_start to index over them in memory if its varargs.
6470   // Because we cannot tell if this is needed on the caller side, we have to
6471   // conservatively assume that it is needed.  As such, make sure we have at
6472   // least enough stack space for the caller to store the 8 GPRs.
6473   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6474 
6475   // Tail call needs the stack to be aligned.
6476   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6477       CFlags.CallConv == CallingConv::Fast)
6478     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6479 
6480   // Calculate by how many bytes the stack has to be adjusted in case of tail
6481   // call optimization.
6482   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6483 
6484   // To protect arguments on the stack from being clobbered in a tail call,
6485   // force all the loads to happen before doing any other lowering.
6486   if (CFlags.IsTailCall)
6487     Chain = DAG.getStackArgumentTokenFactor(Chain);
6488 
6489   // Adjust the stack pointer for the new arguments...
6490   // These operations are automatically eliminated by the prolog/epilog pass
6491   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6492   SDValue CallSeqStart = Chain;
6493 
6494   // Load the return address and frame pointer so it can be move somewhere else
6495   // later.
6496   SDValue LROp, FPOp;
6497   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6498 
6499   // Set up a copy of the stack pointer for use loading and storing any
6500   // arguments that may not fit in the registers available for argument
6501   // passing.
6502   SDValue StackPtr;
6503   if (isPPC64)
6504     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6505   else
6506     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6507 
6508   // Figure out which arguments are going to go in registers, and which in
6509   // memory.  Also, if this is a vararg function, floating point operations
6510   // must be stored to our stack, and loaded into integer regs as well, if
6511   // any integer regs are available for argument passing.
6512   unsigned ArgOffset = LinkageSize;
6513   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6514 
6515   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6516     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6517     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6518   };
6519   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6520     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6521     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6522   };
6523   static const MCPhysReg VR[] = {
6524     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6525     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6526   };
6527   const unsigned NumGPRs = array_lengthof(GPR_32);
6528   const unsigned NumFPRs = 13;
6529   const unsigned NumVRs  = array_lengthof(VR);
6530 
6531   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6532 
6533   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6534   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6535 
6536   SmallVector<SDValue, 8> MemOpChains;
6537   for (unsigned i = 0; i != NumOps; ++i) {
6538     SDValue Arg = OutVals[i];
6539     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6540 
6541     // PtrOff will be used to store the current argument to the stack if a
6542     // register cannot be found for it.
6543     SDValue PtrOff;
6544 
6545     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6546 
6547     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6548 
6549     // On PPC64, promote integers to 64-bit values.
6550     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6551       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6552       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6553       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6554     }
6555 
6556     // FIXME memcpy is used way more than necessary.  Correctness first.
6557     // Note: "by value" is code for passing a structure by value, not
6558     // basic types.
6559     if (Flags.isByVal()) {
6560       unsigned Size = Flags.getByValSize();
6561       // Very small objects are passed right-justified.  Everything else is
6562       // passed left-justified.
6563       if (Size==1 || Size==2) {
6564         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6565         if (GPR_idx != NumGPRs) {
6566           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6567                                         MachinePointerInfo(), VT);
6568           MemOpChains.push_back(Load.getValue(1));
6569           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6570 
6571           ArgOffset += PtrByteSize;
6572         } else {
6573           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6574                                           PtrOff.getValueType());
6575           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6576           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6577                                                             CallSeqStart,
6578                                                             Flags, DAG, dl);
6579           ArgOffset += PtrByteSize;
6580         }
6581         continue;
6582       }
6583       // Copy entire object into memory.  There are cases where gcc-generated
6584       // code assumes it is there, even if it could be put entirely into
6585       // registers.  (This is not what the doc says.)
6586       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6587                                                         CallSeqStart,
6588                                                         Flags, DAG, dl);
6589 
6590       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6591       // copy the pieces of the object that fit into registers from the
6592       // parameter save area.
6593       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6594         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6595         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6596         if (GPR_idx != NumGPRs) {
6597           SDValue Load =
6598               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6599           MemOpChains.push_back(Load.getValue(1));
6600           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6601           ArgOffset += PtrByteSize;
6602         } else {
6603           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6604           break;
6605         }
6606       }
6607       continue;
6608     }
6609 
6610     switch (Arg.getSimpleValueType().SimpleTy) {
6611     default: llvm_unreachable("Unexpected ValueType for argument!");
6612     case MVT::i1:
6613     case MVT::i32:
6614     case MVT::i64:
6615       if (GPR_idx != NumGPRs) {
6616         if (Arg.getValueType() == MVT::i1)
6617           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6618 
6619         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6620       } else {
6621         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6622                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6623                          TailCallArguments, dl);
6624       }
6625       ArgOffset += PtrByteSize;
6626       break;
6627     case MVT::f32:
6628     case MVT::f64:
6629       if (FPR_idx != NumFPRs) {
6630         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6631 
6632         if (CFlags.IsVarArg) {
6633           SDValue Store =
6634               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6635           MemOpChains.push_back(Store);
6636 
6637           // Float varargs are always shadowed in available integer registers
6638           if (GPR_idx != NumGPRs) {
6639             SDValue Load =
6640                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6641             MemOpChains.push_back(Load.getValue(1));
6642             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6643           }
6644           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6645             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6646             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6647             SDValue Load =
6648                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6649             MemOpChains.push_back(Load.getValue(1));
6650             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6651           }
6652         } else {
6653           // If we have any FPRs remaining, we may also have GPRs remaining.
6654           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6655           // GPRs.
6656           if (GPR_idx != NumGPRs)
6657             ++GPR_idx;
6658           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6659               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6660             ++GPR_idx;
6661         }
6662       } else
6663         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6664                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6665                          TailCallArguments, dl);
6666       if (isPPC64)
6667         ArgOffset += 8;
6668       else
6669         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6670       break;
6671     case MVT::v4f32:
6672     case MVT::v4i32:
6673     case MVT::v8i16:
6674     case MVT::v16i8:
6675       if (CFlags.IsVarArg) {
6676         // These go aligned on the stack, or in the corresponding R registers
6677         // when within range.  The Darwin PPC ABI doc claims they also go in
6678         // V registers; in fact gcc does this only for arguments that are
6679         // prototyped, not for those that match the ...  We do it for all
6680         // arguments, seems to work.
6681         while (ArgOffset % 16 !=0) {
6682           ArgOffset += PtrByteSize;
6683           if (GPR_idx != NumGPRs)
6684             GPR_idx++;
6685         }
6686         // We could elide this store in the case where the object fits
6687         // entirely in R registers.  Maybe later.
6688         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6689                              DAG.getConstant(ArgOffset, dl, PtrVT));
6690         SDValue Store =
6691             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6692         MemOpChains.push_back(Store);
6693         if (VR_idx != NumVRs) {
6694           SDValue Load =
6695               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6696           MemOpChains.push_back(Load.getValue(1));
6697           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6698         }
6699         ArgOffset += 16;
6700         for (unsigned i=0; i<16; i+=PtrByteSize) {
6701           if (GPR_idx == NumGPRs)
6702             break;
6703           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6704                                    DAG.getConstant(i, dl, PtrVT));
6705           SDValue Load =
6706               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6707           MemOpChains.push_back(Load.getValue(1));
6708           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6709         }
6710         break;
6711       }
6712 
6713       // Non-varargs Altivec params generally go in registers, but have
6714       // stack space allocated at the end.
6715       if (VR_idx != NumVRs) {
6716         // Doesn't have GPR space allocated.
6717         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6718       } else if (nAltivecParamsAtEnd==0) {
6719         // We are emitting Altivec params in order.
6720         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6721                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6722                          TailCallArguments, dl);
6723         ArgOffset += 16;
6724       }
6725       break;
6726     }
6727   }
6728   // If all Altivec parameters fit in registers, as they usually do,
6729   // they get stack space following the non-Altivec parameters.  We
6730   // don't track this here because nobody below needs it.
6731   // If there are more Altivec parameters than fit in registers emit
6732   // the stores here.
6733   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6734     unsigned j = 0;
6735     // Offset is aligned; skip 1st 12 params which go in V registers.
6736     ArgOffset = ((ArgOffset+15)/16)*16;
6737     ArgOffset += 12*16;
6738     for (unsigned i = 0; i != NumOps; ++i) {
6739       SDValue Arg = OutVals[i];
6740       EVT ArgType = Outs[i].VT;
6741       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6742           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6743         if (++j > NumVRs) {
6744           SDValue PtrOff;
6745           // We are emitting Altivec params in order.
6746           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6747                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6748                            TailCallArguments, dl);
6749           ArgOffset += 16;
6750         }
6751       }
6752     }
6753   }
6754 
6755   if (!MemOpChains.empty())
6756     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6757 
6758   // On Darwin, R12 must contain the address of an indirect callee.  This does
6759   // not mean the MTCTR instruction must use R12; it's easier to model this as
6760   // an extra parameter, so do that.
6761   if (CFlags.IsIndirect) {
6762     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6763     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6764                                                    PPC::R12), Callee));
6765   }
6766 
6767   // Build a sequence of copy-to-reg nodes chained together with token chain
6768   // and flag operands which copy the outgoing args into the appropriate regs.
6769   SDValue InFlag;
6770   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6771     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6772                              RegsToPass[i].second, InFlag);
6773     InFlag = Chain.getValue(1);
6774   }
6775 
6776   if (CFlags.IsTailCall)
6777     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6778                     TailCallArguments);
6779 
6780   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6781                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6782 }
6783 
6784 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6785                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6786                    CCState &State) {
6787 
6788   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6789       State.getMachineFunction().getSubtarget());
6790   const bool IsPPC64 = Subtarget.isPPC64();
6791   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6792   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6793 
6794   assert((!ValVT.isInteger() ||
6795           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6796          "Integer argument exceeds register size: should have been legalized");
6797 
6798   if (ValVT == MVT::f128)
6799     report_fatal_error("f128 is unimplemented on AIX.");
6800 
6801   if (ArgFlags.isNest())
6802     report_fatal_error("Nest arguments are unimplemented.");
6803 
6804   if (ValVT.isVector() || LocVT.isVector())
6805     report_fatal_error("Vector arguments are unimplemented on AIX.");
6806 
6807   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6808                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6809                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6810   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6811                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6812                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6813 
6814   if (ArgFlags.isByVal()) {
6815     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6816       report_fatal_error("Pass-by-value arguments with alignment greater than "
6817                          "register width are not supported.");
6818 
6819     const unsigned ByValSize = ArgFlags.getByValSize();
6820 
6821     // An empty aggregate parameter takes up no storage and no registers,
6822     // but needs a MemLoc for a stack slot for the formal arguments side.
6823     if (ByValSize == 0) {
6824       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6825                                        State.getNextStackOffset(), RegVT,
6826                                        LocInfo));
6827       return false;
6828     }
6829 
6830     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6831     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6832     for (const unsigned E = Offset + StackSize; Offset < E;
6833          Offset += PtrAlign.value()) {
6834       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6835         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6836       else {
6837         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6838                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6839                                          LocInfo));
6840         break;
6841       }
6842     }
6843     return false;
6844   }
6845 
6846   // Arguments always reserve parameter save area.
6847   switch (ValVT.SimpleTy) {
6848   default:
6849     report_fatal_error("Unhandled value type for argument.");
6850   case MVT::i64:
6851     // i64 arguments should have been split to i32 for PPC32.
6852     assert(IsPPC64 && "PPC32 should have split i64 values.");
6853     LLVM_FALLTHROUGH;
6854   case MVT::i1:
6855   case MVT::i32: {
6856     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6857     // AIX integer arguments are always passed in register width.
6858     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6859       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6860                                   : CCValAssign::LocInfo::ZExt;
6861     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6862       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6863     else
6864       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6865 
6866     return false;
6867   }
6868   case MVT::f32:
6869   case MVT::f64: {
6870     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6871     const unsigned StoreSize = LocVT.getStoreSize();
6872     // Floats are always 4-byte aligned in the PSA on AIX.
6873     // This includes f64 in 64-bit mode for ABI compatibility.
6874     const unsigned Offset =
6875         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6876     unsigned FReg = State.AllocateReg(FPR);
6877     if (FReg)
6878       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6879 
6880     // Reserve and initialize GPRs or initialize the PSA as required.
6881     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6882       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6883         assert(FReg && "An FPR should be available when a GPR is reserved.");
6884         if (State.isVarArg()) {
6885           // Successfully reserved GPRs are only initialized for vararg calls.
6886           // Custom handling is required for:
6887           //   f64 in PPC32 needs to be split into 2 GPRs.
6888           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6889           State.addLoc(
6890               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6891         }
6892       } else {
6893         // If there are insufficient GPRs, the PSA needs to be initialized.
6894         // Initialization occurs even if an FPR was initialized for
6895         // compatibility with the AIX XL compiler. The full memory for the
6896         // argument will be initialized even if a prior word is saved in GPR.
6897         // A custom memLoc is used when the argument also passes in FPR so
6898         // that the callee handling can skip over it easily.
6899         State.addLoc(
6900             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6901                                              LocInfo)
6902                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6903         break;
6904       }
6905     }
6906 
6907     return false;
6908   }
6909   }
6910   return true;
6911 }
6912 
6913 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6914                                                     bool IsPPC64) {
6915   assert((IsPPC64 || SVT != MVT::i64) &&
6916          "i64 should have been split for 32-bit codegen.");
6917 
6918   switch (SVT) {
6919   default:
6920     report_fatal_error("Unexpected value type for formal argument");
6921   case MVT::i1:
6922   case MVT::i32:
6923   case MVT::i64:
6924     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6925   case MVT::f32:
6926     return &PPC::F4RCRegClass;
6927   case MVT::f64:
6928     return &PPC::F8RCRegClass;
6929   }
6930 }
6931 
6932 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6933                                         SelectionDAG &DAG, SDValue ArgValue,
6934                                         MVT LocVT, const SDLoc &dl) {
6935   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6936   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6937 
6938   if (Flags.isSExt())
6939     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6940                            DAG.getValueType(ValVT));
6941   else if (Flags.isZExt())
6942     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6943                            DAG.getValueType(ValVT));
6944 
6945   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6946 }
6947 
6948 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6949   const unsigned LASize = FL->getLinkageSize();
6950 
6951   if (PPC::GPRCRegClass.contains(Reg)) {
6952     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6953            "Reg must be a valid argument register!");
6954     return LASize + 4 * (Reg - PPC::R3);
6955   }
6956 
6957   if (PPC::G8RCRegClass.contains(Reg)) {
6958     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6959            "Reg must be a valid argument register!");
6960     return LASize + 8 * (Reg - PPC::X3);
6961   }
6962 
6963   llvm_unreachable("Only general purpose registers expected.");
6964 }
6965 
6966 //   AIX ABI Stack Frame Layout:
6967 //
6968 //   Low Memory +--------------------------------------------+
6969 //   SP   +---> | Back chain                                 | ---+
6970 //        |     +--------------------------------------------+    |
6971 //        |     | Saved Condition Register                   |    |
6972 //        |     +--------------------------------------------+    |
6973 //        |     | Saved Linkage Register                     |    |
6974 //        |     +--------------------------------------------+    | Linkage Area
6975 //        |     | Reserved for compilers                     |    |
6976 //        |     +--------------------------------------------+    |
6977 //        |     | Reserved for binders                       |    |
6978 //        |     +--------------------------------------------+    |
6979 //        |     | Saved TOC pointer                          | ---+
6980 //        |     +--------------------------------------------+
6981 //        |     | Parameter save area                        |
6982 //        |     +--------------------------------------------+
6983 //        |     | Alloca space                               |
6984 //        |     +--------------------------------------------+
6985 //        |     | Local variable space                       |
6986 //        |     +--------------------------------------------+
6987 //        |     | Float/int conversion temporary             |
6988 //        |     +--------------------------------------------+
6989 //        |     | Save area for AltiVec registers            |
6990 //        |     +--------------------------------------------+
6991 //        |     | AltiVec alignment padding                  |
6992 //        |     +--------------------------------------------+
6993 //        |     | Save area for VRSAVE register              |
6994 //        |     +--------------------------------------------+
6995 //        |     | Save area for General Purpose registers    |
6996 //        |     +--------------------------------------------+
6997 //        |     | Save area for Floating Point registers     |
6998 //        |     +--------------------------------------------+
6999 //        +---- | Back chain                                 |
7000 // High Memory  +--------------------------------------------+
7001 //
7002 //  Specifications:
7003 //  AIX 7.2 Assembler Language Reference
7004 //  Subroutine linkage convention
7005 
7006 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7007     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7008     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7009     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7010 
7011   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7012           CallConv == CallingConv::Fast) &&
7013          "Unexpected calling convention!");
7014 
7015   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7016     report_fatal_error("Tail call support is unimplemented on AIX.");
7017 
7018   if (useSoftFloat())
7019     report_fatal_error("Soft float support is unimplemented on AIX.");
7020 
7021   const PPCSubtarget &Subtarget =
7022       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7023 
7024   const bool IsPPC64 = Subtarget.isPPC64();
7025   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7026 
7027   // Assign locations to all of the incoming arguments.
7028   SmallVector<CCValAssign, 16> ArgLocs;
7029   MachineFunction &MF = DAG.getMachineFunction();
7030   MachineFrameInfo &MFI = MF.getFrameInfo();
7031   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7032 
7033   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7034   // Reserve space for the linkage area on the stack.
7035   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7036   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7037   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7038 
7039   SmallVector<SDValue, 8> MemOps;
7040 
7041   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7042     CCValAssign &VA = ArgLocs[I++];
7043     MVT LocVT = VA.getLocVT();
7044     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7045 
7046     // For compatibility with the AIX XL compiler, the float args in the
7047     // parameter save area are initialized even if the argument is available
7048     // in register.  The caller is required to initialize both the register
7049     // and memory, however, the callee can choose to expect it in either.
7050     // The memloc is dismissed here because the argument is retrieved from
7051     // the register.
7052     if (VA.isMemLoc() && VA.needsCustom())
7053       continue;
7054 
7055     if (Flags.isByVal() && VA.isMemLoc()) {
7056       const unsigned Size =
7057           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7058                   PtrByteSize);
7059       const int FI = MF.getFrameInfo().CreateFixedObject(
7060           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7061           /* IsAliased */ true);
7062       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7063       InVals.push_back(FIN);
7064 
7065       continue;
7066     }
7067 
7068     if (Flags.isByVal()) {
7069       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7070 
7071       const MCPhysReg ArgReg = VA.getLocReg();
7072       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7073 
7074       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7075         report_fatal_error("Over aligned byvals not supported yet.");
7076 
7077       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7078       const int FI = MF.getFrameInfo().CreateFixedObject(
7079           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7080           /* IsAliased */ true);
7081       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7082       InVals.push_back(FIN);
7083 
7084       // Add live ins for all the RegLocs for the same ByVal.
7085       const TargetRegisterClass *RegClass =
7086           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7087 
7088       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7089                                                unsigned Offset) {
7090         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7091         // Since the callers side has left justified the aggregate in the
7092         // register, we can simply store the entire register into the stack
7093         // slot.
7094         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7095         // The store to the fixedstack object is needed becuase accessing a
7096         // field of the ByVal will use a gep and load. Ideally we will optimize
7097         // to extracting the value from the register directly, and elide the
7098         // stores when the arguments address is not taken, but that will need to
7099         // be future work.
7100         SDValue Store = DAG.getStore(
7101             CopyFrom.getValue(1), dl, CopyFrom,
7102             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7103             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7104 
7105         MemOps.push_back(Store);
7106       };
7107 
7108       unsigned Offset = 0;
7109       HandleRegLoc(VA.getLocReg(), Offset);
7110       Offset += PtrByteSize;
7111       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7112            Offset += PtrByteSize) {
7113         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7114                "RegLocs should be for ByVal argument.");
7115 
7116         const CCValAssign RL = ArgLocs[I++];
7117         HandleRegLoc(RL.getLocReg(), Offset);
7118       }
7119 
7120       if (Offset != StackSize) {
7121         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7122                "Expected MemLoc for remaining bytes.");
7123         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7124         // Consume the MemLoc.The InVal has already been emitted, so nothing
7125         // more needs to be done.
7126         ++I;
7127       }
7128 
7129       continue;
7130     }
7131 
7132     EVT ValVT = VA.getValVT();
7133     if (VA.isRegLoc() && !VA.needsCustom()) {
7134       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7135       unsigned VReg =
7136           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7137       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7138       if (ValVT.isScalarInteger() &&
7139           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7140         ArgValue =
7141             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7142       }
7143       InVals.push_back(ArgValue);
7144       continue;
7145     }
7146     if (VA.isMemLoc()) {
7147       const unsigned LocSize = LocVT.getStoreSize();
7148       const unsigned ValSize = ValVT.getStoreSize();
7149       assert((ValSize <= LocSize) &&
7150              "Object size is larger than size of MemLoc");
7151       int CurArgOffset = VA.getLocMemOffset();
7152       // Objects are right-justified because AIX is big-endian.
7153       if (LocSize > ValSize)
7154         CurArgOffset += LocSize - ValSize;
7155       // Potential tail calls could cause overwriting of argument stack slots.
7156       const bool IsImmutable =
7157           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7158             (CallConv == CallingConv::Fast));
7159       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7160       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7161       SDValue ArgValue =
7162           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7163       InVals.push_back(ArgValue);
7164       continue;
7165     }
7166   }
7167 
7168   // On AIX a minimum of 8 words is saved to the parameter save area.
7169   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7170   // Area that is at least reserved in the caller of this function.
7171   unsigned CallerReservedArea =
7172       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7173 
7174   // Set the size that is at least reserved in caller of this function. Tail
7175   // call optimized function's reserved stack space needs to be aligned so
7176   // that taking the difference between two stack areas will result in an
7177   // aligned stack.
7178   CallerReservedArea =
7179       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7180   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7181   FuncInfo->setMinReservedArea(CallerReservedArea);
7182 
7183   if (isVarArg) {
7184     FuncInfo->setVarArgsFrameIndex(
7185         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7186     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7187 
7188     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7189                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7190 
7191     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7192                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7193     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7194 
7195     // The fixed integer arguments of a variadic function are stored to the
7196     // VarArgsFrameIndex on the stack so that they may be loaded by
7197     // dereferencing the result of va_next.
7198     for (unsigned GPRIndex =
7199              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7200          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7201 
7202       const unsigned VReg =
7203           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7204                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7205 
7206       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7207       SDValue Store =
7208           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7209       MemOps.push_back(Store);
7210       // Increment the address for the next argument to store.
7211       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7212       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7213     }
7214   }
7215 
7216   if (!MemOps.empty())
7217     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7218 
7219   return Chain;
7220 }
7221 
7222 SDValue PPCTargetLowering::LowerCall_AIX(
7223     SDValue Chain, SDValue Callee, CallFlags CFlags,
7224     const SmallVectorImpl<ISD::OutputArg> &Outs,
7225     const SmallVectorImpl<SDValue> &OutVals,
7226     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7227     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7228     const CallBase *CB) const {
7229   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7230   // AIX ABI stack frame layout.
7231 
7232   assert((CFlags.CallConv == CallingConv::C ||
7233           CFlags.CallConv == CallingConv::Cold ||
7234           CFlags.CallConv == CallingConv::Fast) &&
7235          "Unexpected calling convention!");
7236 
7237   if (CFlags.IsPatchPoint)
7238     report_fatal_error("This call type is unimplemented on AIX.");
7239 
7240   const PPCSubtarget& Subtarget =
7241       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7242   if (Subtarget.hasAltivec())
7243     report_fatal_error("Altivec support is unimplemented on AIX.");
7244 
7245   MachineFunction &MF = DAG.getMachineFunction();
7246   SmallVector<CCValAssign, 16> ArgLocs;
7247   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7248                  *DAG.getContext());
7249 
7250   // Reserve space for the linkage save area (LSA) on the stack.
7251   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7252   //   [SP][CR][LR][2 x reserved][TOC].
7253   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7254   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7255   const bool IsPPC64 = Subtarget.isPPC64();
7256   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7257   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7258   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7259   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7260 
7261   // The prolog code of the callee may store up to 8 GPR argument registers to
7262   // the stack, allowing va_start to index over them in memory if the callee
7263   // is variadic.
7264   // Because we cannot tell if this is needed on the caller side, we have to
7265   // conservatively assume that it is needed.  As such, make sure we have at
7266   // least enough stack space for the caller to store the 8 GPRs.
7267   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7268   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7269                                      CCInfo.getNextStackOffset());
7270 
7271   // Adjust the stack pointer for the new arguments...
7272   // These operations are automatically eliminated by the prolog/epilog pass.
7273   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7274   SDValue CallSeqStart = Chain;
7275 
7276   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7277   SmallVector<SDValue, 8> MemOpChains;
7278 
7279   // Set up a copy of the stack pointer for loading and storing any
7280   // arguments that may not fit in the registers available for argument
7281   // passing.
7282   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7283                                    : DAG.getRegister(PPC::R1, MVT::i32);
7284 
7285   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7286     const unsigned ValNo = ArgLocs[I].getValNo();
7287     SDValue Arg = OutVals[ValNo];
7288     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7289 
7290     if (Flags.isByVal()) {
7291       const unsigned ByValSize = Flags.getByValSize();
7292 
7293       // Nothing to do for zero-sized ByVals on the caller side.
7294       if (!ByValSize) {
7295         ++I;
7296         continue;
7297       }
7298 
7299       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7300         return DAG.getExtLoad(
7301             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7302             (LoadOffset != 0)
7303                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7304                 : Arg,
7305             MachinePointerInfo(), VT);
7306       };
7307 
7308       unsigned LoadOffset = 0;
7309 
7310       // Initialize registers, which are fully occupied by the by-val argument.
7311       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7312         SDValue Load = GetLoad(PtrVT, LoadOffset);
7313         MemOpChains.push_back(Load.getValue(1));
7314         LoadOffset += PtrByteSize;
7315         const CCValAssign &ByValVA = ArgLocs[I++];
7316         assert(ByValVA.getValNo() == ValNo &&
7317                "Unexpected location for pass-by-value argument.");
7318         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7319       }
7320 
7321       if (LoadOffset == ByValSize)
7322         continue;
7323 
7324       // There must be one more loc to handle the remainder.
7325       assert(ArgLocs[I].getValNo() == ValNo &&
7326              "Expected additional location for by-value argument.");
7327 
7328       if (ArgLocs[I].isMemLoc()) {
7329         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7330         const CCValAssign &ByValVA = ArgLocs[I++];
7331         ISD::ArgFlagsTy MemcpyFlags = Flags;
7332         // Only memcpy the bytes that don't pass in register.
7333         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7334         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7335             (LoadOffset != 0)
7336                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7337                 : Arg,
7338             DAG.getObjectPtrOffset(dl, StackPtr,
7339                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7340             CallSeqStart, MemcpyFlags, DAG, dl);
7341         continue;
7342       }
7343 
7344       // Initialize the final register residue.
7345       // Any residue that occupies the final by-val arg register must be
7346       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7347       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7348       // 2 and 1 byte loads.
7349       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7350       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7351              "Unexpected register residue for by-value argument.");
7352       SDValue ResidueVal;
7353       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7354         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7355         const MVT VT =
7356             N == 1 ? MVT::i8
7357                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7358         SDValue Load = GetLoad(VT, LoadOffset);
7359         MemOpChains.push_back(Load.getValue(1));
7360         LoadOffset += N;
7361         Bytes += N;
7362 
7363         // By-val arguments are passed left-justfied in register.
7364         // Every load here needs to be shifted, otherwise a full register load
7365         // should have been used.
7366         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7367                "Unexpected load emitted during handling of pass-by-value "
7368                "argument.");
7369         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7370         EVT ShiftAmountTy =
7371             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7372         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7373         SDValue ShiftedLoad =
7374             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7375         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7376                                               ShiftedLoad)
7377                                 : ShiftedLoad;
7378       }
7379 
7380       const CCValAssign &ByValVA = ArgLocs[I++];
7381       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7382       continue;
7383     }
7384 
7385     CCValAssign &VA = ArgLocs[I++];
7386     const MVT LocVT = VA.getLocVT();
7387     const MVT ValVT = VA.getValVT();
7388 
7389     switch (VA.getLocInfo()) {
7390     default:
7391       report_fatal_error("Unexpected argument extension type.");
7392     case CCValAssign::Full:
7393       break;
7394     case CCValAssign::ZExt:
7395       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7396       break;
7397     case CCValAssign::SExt:
7398       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7399       break;
7400     }
7401 
7402     if (VA.isRegLoc() && !VA.needsCustom()) {
7403       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7404       continue;
7405     }
7406 
7407     if (VA.isMemLoc()) {
7408       SDValue PtrOff =
7409           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7410       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7411       MemOpChains.push_back(
7412           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7413 
7414       continue;
7415     }
7416 
7417     // Custom handling is used for GPR initializations for vararg float
7418     // arguments.
7419     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7420            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7421            "Unexpected register handling for calling convention.");
7422 
7423     SDValue ArgAsInt =
7424         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7425 
7426     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7427       // f32 in 32-bit GPR
7428       // f64 in 64-bit GPR
7429       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7430     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7431       // f32 in 64-bit GPR.
7432       RegsToPass.push_back(std::make_pair(
7433           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7434     else {
7435       // f64 in two 32-bit GPRs
7436       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7437       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7438              "Unexpected custom register for argument!");
7439       CCValAssign &GPR1 = VA;
7440       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7441                                      DAG.getConstant(32, dl, MVT::i8));
7442       RegsToPass.push_back(std::make_pair(
7443           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7444 
7445       if (I != E) {
7446         // If only 1 GPR was available, there will only be one custom GPR and
7447         // the argument will also pass in memory.
7448         CCValAssign &PeekArg = ArgLocs[I];
7449         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7450           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7451           CCValAssign &GPR2 = ArgLocs[I++];
7452           RegsToPass.push_back(std::make_pair(
7453               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7454         }
7455       }
7456     }
7457   }
7458 
7459   if (!MemOpChains.empty())
7460     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7461 
7462   // For indirect calls, we need to save the TOC base to the stack for
7463   // restoration after the call.
7464   if (CFlags.IsIndirect) {
7465     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7466     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7467     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7468     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7469     const unsigned TOCSaveOffset =
7470         Subtarget.getFrameLowering()->getTOCSaveOffset();
7471 
7472     setUsesTOCBasePtr(DAG);
7473     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7474     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7475     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7476     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7477     Chain = DAG.getStore(
7478         Val.getValue(1), dl, Val, AddPtr,
7479         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7480   }
7481 
7482   // Build a sequence of copy-to-reg nodes chained together with token chain
7483   // and flag operands which copy the outgoing args into the appropriate regs.
7484   SDValue InFlag;
7485   for (auto Reg : RegsToPass) {
7486     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7487     InFlag = Chain.getValue(1);
7488   }
7489 
7490   const int SPDiff = 0;
7491   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7492                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7493 }
7494 
7495 bool
7496 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7497                                   MachineFunction &MF, bool isVarArg,
7498                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7499                                   LLVMContext &Context) const {
7500   SmallVector<CCValAssign, 16> RVLocs;
7501   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7502   return CCInfo.CheckReturn(
7503       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7504                 ? RetCC_PPC_Cold
7505                 : RetCC_PPC);
7506 }
7507 
7508 SDValue
7509 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7510                                bool isVarArg,
7511                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7512                                const SmallVectorImpl<SDValue> &OutVals,
7513                                const SDLoc &dl, SelectionDAG &DAG) const {
7514   SmallVector<CCValAssign, 16> RVLocs;
7515   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7516                  *DAG.getContext());
7517   CCInfo.AnalyzeReturn(Outs,
7518                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7519                            ? RetCC_PPC_Cold
7520                            : RetCC_PPC);
7521 
7522   SDValue Flag;
7523   SmallVector<SDValue, 4> RetOps(1, Chain);
7524 
7525   // Copy the result values into the output registers.
7526   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7527     CCValAssign &VA = RVLocs[i];
7528     assert(VA.isRegLoc() && "Can only return in registers!");
7529 
7530     SDValue Arg = OutVals[RealResIdx];
7531 
7532     switch (VA.getLocInfo()) {
7533     default: llvm_unreachable("Unknown loc info!");
7534     case CCValAssign::Full: break;
7535     case CCValAssign::AExt:
7536       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7537       break;
7538     case CCValAssign::ZExt:
7539       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7540       break;
7541     case CCValAssign::SExt:
7542       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7543       break;
7544     }
7545     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7546       bool isLittleEndian = Subtarget.isLittleEndian();
7547       // Legalize ret f64 -> ret 2 x i32.
7548       SDValue SVal =
7549           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7550                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7551       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7552       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7553       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7554                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7555       Flag = Chain.getValue(1);
7556       VA = RVLocs[++i]; // skip ahead to next loc
7557       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7558     } else
7559       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7560     Flag = Chain.getValue(1);
7561     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7562   }
7563 
7564   RetOps[0] = Chain;  // Update chain.
7565 
7566   // Add the flag if we have it.
7567   if (Flag.getNode())
7568     RetOps.push_back(Flag);
7569 
7570   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7571 }
7572 
7573 SDValue
7574 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7575                                                 SelectionDAG &DAG) const {
7576   SDLoc dl(Op);
7577 
7578   // Get the correct type for integers.
7579   EVT IntVT = Op.getValueType();
7580 
7581   // Get the inputs.
7582   SDValue Chain = Op.getOperand(0);
7583   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7584   // Build a DYNAREAOFFSET node.
7585   SDValue Ops[2] = {Chain, FPSIdx};
7586   SDVTList VTs = DAG.getVTList(IntVT);
7587   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7588 }
7589 
7590 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7591                                              SelectionDAG &DAG) const {
7592   // When we pop the dynamic allocation we need to restore the SP link.
7593   SDLoc dl(Op);
7594 
7595   // Get the correct type for pointers.
7596   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7597 
7598   // Construct the stack pointer operand.
7599   bool isPPC64 = Subtarget.isPPC64();
7600   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7601   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7602 
7603   // Get the operands for the STACKRESTORE.
7604   SDValue Chain = Op.getOperand(0);
7605   SDValue SaveSP = Op.getOperand(1);
7606 
7607   // Load the old link SP.
7608   SDValue LoadLinkSP =
7609       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7610 
7611   // Restore the stack pointer.
7612   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7613 
7614   // Store the old link SP.
7615   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7616 }
7617 
7618 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7619   MachineFunction &MF = DAG.getMachineFunction();
7620   bool isPPC64 = Subtarget.isPPC64();
7621   EVT PtrVT = getPointerTy(MF.getDataLayout());
7622 
7623   // Get current frame pointer save index.  The users of this index will be
7624   // primarily DYNALLOC instructions.
7625   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7626   int RASI = FI->getReturnAddrSaveIndex();
7627 
7628   // If the frame pointer save index hasn't been defined yet.
7629   if (!RASI) {
7630     // Find out what the fix offset of the frame pointer save area.
7631     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7632     // Allocate the frame index for frame pointer save area.
7633     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7634     // Save the result.
7635     FI->setReturnAddrSaveIndex(RASI);
7636   }
7637   return DAG.getFrameIndex(RASI, PtrVT);
7638 }
7639 
7640 SDValue
7641 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7642   MachineFunction &MF = DAG.getMachineFunction();
7643   bool isPPC64 = Subtarget.isPPC64();
7644   EVT PtrVT = getPointerTy(MF.getDataLayout());
7645 
7646   // Get current frame pointer save index.  The users of this index will be
7647   // primarily DYNALLOC instructions.
7648   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7649   int FPSI = FI->getFramePointerSaveIndex();
7650 
7651   // If the frame pointer save index hasn't been defined yet.
7652   if (!FPSI) {
7653     // Find out what the fix offset of the frame pointer save area.
7654     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7655     // Allocate the frame index for frame pointer save area.
7656     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7657     // Save the result.
7658     FI->setFramePointerSaveIndex(FPSI);
7659   }
7660   return DAG.getFrameIndex(FPSI, PtrVT);
7661 }
7662 
7663 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7664                                                    SelectionDAG &DAG) const {
7665   MachineFunction &MF = DAG.getMachineFunction();
7666   // Get the inputs.
7667   SDValue Chain = Op.getOperand(0);
7668   SDValue Size  = Op.getOperand(1);
7669   SDLoc dl(Op);
7670 
7671   // Get the correct type for pointers.
7672   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7673   // Negate the size.
7674   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7675                                 DAG.getConstant(0, dl, PtrVT), Size);
7676   // Construct a node for the frame pointer save index.
7677   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7678   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7679   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7680   if (hasInlineStackProbe(MF))
7681     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7682   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7683 }
7684 
7685 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7686                                                      SelectionDAG &DAG) const {
7687   MachineFunction &MF = DAG.getMachineFunction();
7688 
7689   bool isPPC64 = Subtarget.isPPC64();
7690   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7691 
7692   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7693   return DAG.getFrameIndex(FI, PtrVT);
7694 }
7695 
7696 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7697                                                SelectionDAG &DAG) const {
7698   SDLoc DL(Op);
7699   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7700                      DAG.getVTList(MVT::i32, MVT::Other),
7701                      Op.getOperand(0), Op.getOperand(1));
7702 }
7703 
7704 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7705                                                 SelectionDAG &DAG) const {
7706   SDLoc DL(Op);
7707   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7708                      Op.getOperand(0), Op.getOperand(1));
7709 }
7710 
7711 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7712 
7713   assert(Op.getValueType() == MVT::i1 &&
7714          "Custom lowering only for i1 loads");
7715 
7716   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7717 
7718   SDLoc dl(Op);
7719   LoadSDNode *LD = cast<LoadSDNode>(Op);
7720 
7721   SDValue Chain = LD->getChain();
7722   SDValue BasePtr = LD->getBasePtr();
7723   MachineMemOperand *MMO = LD->getMemOperand();
7724 
7725   SDValue NewLD =
7726       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7727                      BasePtr, MVT::i8, MMO);
7728   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7729 
7730   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7731   return DAG.getMergeValues(Ops, dl);
7732 }
7733 
7734 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7735   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7736          "Custom lowering only for i1 stores");
7737 
7738   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7739 
7740   SDLoc dl(Op);
7741   StoreSDNode *ST = cast<StoreSDNode>(Op);
7742 
7743   SDValue Chain = ST->getChain();
7744   SDValue BasePtr = ST->getBasePtr();
7745   SDValue Value = ST->getValue();
7746   MachineMemOperand *MMO = ST->getMemOperand();
7747 
7748   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7749                       Value);
7750   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7751 }
7752 
7753 // FIXME: Remove this once the ANDI glue bug is fixed:
7754 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7755   assert(Op.getValueType() == MVT::i1 &&
7756          "Custom lowering only for i1 results");
7757 
7758   SDLoc DL(Op);
7759   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7760 }
7761 
7762 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7763                                                SelectionDAG &DAG) const {
7764 
7765   // Implements a vector truncate that fits in a vector register as a shuffle.
7766   // We want to legalize vector truncates down to where the source fits in
7767   // a vector register (and target is therefore smaller than vector register
7768   // size).  At that point legalization will try to custom lower the sub-legal
7769   // result and get here - where we can contain the truncate as a single target
7770   // operation.
7771 
7772   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7773   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7774   //
7775   // We will implement it for big-endian ordering as this (where x denotes
7776   // undefined):
7777   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7778   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7779   //
7780   // The same operation in little-endian ordering will be:
7781   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7782   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7783 
7784   assert(Op.getValueType().isVector() && "Vector type expected.");
7785 
7786   SDLoc DL(Op);
7787   SDValue N1 = Op.getOperand(0);
7788   unsigned SrcSize = N1.getValueType().getSizeInBits();
7789   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7790   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7791 
7792   EVT TrgVT = Op.getValueType();
7793   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7794   EVT EltVT = TrgVT.getVectorElementType();
7795   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7796   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7797 
7798   // First list the elements we want to keep.
7799   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7800   SmallVector<int, 16> ShuffV;
7801   if (Subtarget.isLittleEndian())
7802     for (unsigned i = 0; i < TrgNumElts; ++i)
7803       ShuffV.push_back(i * SizeMult);
7804   else
7805     for (unsigned i = 1; i <= TrgNumElts; ++i)
7806       ShuffV.push_back(i * SizeMult - 1);
7807 
7808   // Populate the remaining elements with undefs.
7809   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7810     // ShuffV.push_back(i + WideNumElts);
7811     ShuffV.push_back(WideNumElts + 1);
7812 
7813   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7814   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7815 }
7816 
7817 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7818 /// possible.
7819 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7820   // Not FP, or using SPE? Not a fsel.
7821   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7822       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7823     return Op;
7824 
7825   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7826 
7827   EVT ResVT = Op.getValueType();
7828   EVT CmpVT = Op.getOperand(0).getValueType();
7829   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7830   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7831   SDLoc dl(Op);
7832   SDNodeFlags Flags = Op.getNode()->getFlags();
7833 
7834   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7835   // presence of infinities.
7836   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7837     switch (CC) {
7838     default:
7839       break;
7840     case ISD::SETOGT:
7841     case ISD::SETGT:
7842       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7843     case ISD::SETOLT:
7844     case ISD::SETLT:
7845       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7846     }
7847   }
7848 
7849   // We might be able to do better than this under some circumstances, but in
7850   // general, fsel-based lowering of select is a finite-math-only optimization.
7851   // For more information, see section F.3 of the 2.06 ISA specification.
7852   // With ISA 3.0
7853   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7854       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7855     return Op;
7856 
7857   // If the RHS of the comparison is a 0.0, we don't need to do the
7858   // subtraction at all.
7859   SDValue Sel1;
7860   if (isFloatingPointZero(RHS))
7861     switch (CC) {
7862     default: break;       // SETUO etc aren't handled by fsel.
7863     case ISD::SETNE:
7864       std::swap(TV, FV);
7865       LLVM_FALLTHROUGH;
7866     case ISD::SETEQ:
7867       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7868         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7869       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7870       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7871         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7872       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7873                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7874     case ISD::SETULT:
7875     case ISD::SETLT:
7876       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7877       LLVM_FALLTHROUGH;
7878     case ISD::SETOGE:
7879     case ISD::SETGE:
7880       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7881         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7882       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7883     case ISD::SETUGT:
7884     case ISD::SETGT:
7885       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7886       LLVM_FALLTHROUGH;
7887     case ISD::SETOLE:
7888     case ISD::SETLE:
7889       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7890         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7891       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7892                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7893     }
7894 
7895   SDValue Cmp;
7896   switch (CC) {
7897   default: break;       // SETUO etc aren't handled by fsel.
7898   case ISD::SETNE:
7899     std::swap(TV, FV);
7900     LLVM_FALLTHROUGH;
7901   case ISD::SETEQ:
7902     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7903     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7904       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7905     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7906     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7907       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7908     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7909                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7910   case ISD::SETULT:
7911   case ISD::SETLT:
7912     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7913     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7914       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7915     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7916   case ISD::SETOGE:
7917   case ISD::SETGE:
7918     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7919     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7920       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7921     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7922   case ISD::SETUGT:
7923   case ISD::SETGT:
7924     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7925     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7926       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7927     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7928   case ISD::SETOLE:
7929   case ISD::SETLE:
7930     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7931     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7932       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7933     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7934   }
7935   return Op;
7936 }
7937 
7938 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7939                               const PPCSubtarget &Subtarget) {
7940   SDLoc dl(Op);
7941   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7942   SDValue Src = Op.getOperand(0);
7943   assert(Src.getValueType().isFloatingPoint());
7944   if (Src.getValueType() == MVT::f32)
7945     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7946   SDValue Conv;
7947   switch (Op.getSimpleValueType().SimpleTy) {
7948   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7949   case MVT::i32:
7950     Conv = DAG.getNode(
7951         IsSigned ? PPCISD::FCTIWZ
7952                  : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7953         dl, MVT::f64, Src);
7954     break;
7955   case MVT::i64:
7956     assert((IsSigned || Subtarget.hasFPCVT()) &&
7957            "i64 FP_TO_UINT is supported only with FPCVT");
7958     Conv = DAG.getNode(IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl,
7959                        MVT::f64, Src);
7960   }
7961   return Conv;
7962 }
7963 
7964 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7965                                                SelectionDAG &DAG,
7966                                                const SDLoc &dl) const {
7967   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7968   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7969 
7970   // Convert the FP value to an int value through memory.
7971   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7972                   (IsSigned || Subtarget.hasFPCVT());
7973   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7974   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7975   MachinePointerInfo MPI =
7976       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7977 
7978   // Emit a store to the stack slot.
7979   SDValue Chain;
7980   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7981   if (i32Stack) {
7982     MachineFunction &MF = DAG.getMachineFunction();
7983     Alignment = Align(4);
7984     MachineMemOperand *MMO =
7985         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7986     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7987     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7988               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7989   } else
7990     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
7991 
7992   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7993   // add in a bias on big endian.
7994   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7995     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7996                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7997     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7998   }
7999 
8000   RLI.Chain = Chain;
8001   RLI.Ptr = FIPtr;
8002   RLI.MPI = MPI;
8003   RLI.Alignment = Alignment;
8004 }
8005 
8006 /// Custom lowers floating point to integer conversions to use
8007 /// the direct move instructions available in ISA 2.07 to avoid the
8008 /// need for load/store combinations.
8009 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8010                                                     SelectionDAG &DAG,
8011                                                     const SDLoc &dl) const {
8012   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8013   return DAG.getNode(PPCISD::MFVSR, dl, Op.getSimpleValueType().SimpleTy,
8014                      convertFPToInt(Op, DAG, Subtarget));
8015 }
8016 
8017 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8018                                           const SDLoc &dl) const {
8019   SDValue Src = Op.getOperand(0);
8020   // FP to INT conversions are legal for f128.
8021   if (Src.getValueType() == MVT::f128)
8022     return Op;
8023 
8024   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8025   // PPC (the libcall is not available).
8026   if (Src.getValueType() == MVT::ppcf128) {
8027     if (Op.getValueType() == MVT::i32) {
8028       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8029         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8030                                  DAG.getIntPtrConstant(0, dl));
8031         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8032                                  DAG.getIntPtrConstant(1, dl));
8033 
8034         // Add the two halves of the long double in round-to-zero mode.
8035         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8036 
8037         // Now use a smaller FP_TO_SINT.
8038         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8039       }
8040       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8041         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8042         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8043         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8044         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8045         // FIXME: generated code sucks.
8046         // TODO: Are there fast-math-flags to propagate to this FSUB?
8047         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8048         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8049         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8050                            DAG.getConstant(0x80000000, dl, MVT::i32));
8051         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8052         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8053       }
8054     }
8055 
8056     return SDValue();
8057   }
8058 
8059   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8060     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8061 
8062   ReuseLoadInfo RLI;
8063   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8064 
8065   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8066                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8067 }
8068 
8069 // We're trying to insert a regular store, S, and then a load, L. If the
8070 // incoming value, O, is a load, we might just be able to have our load use the
8071 // address used by O. However, we don't know if anything else will store to
8072 // that address before we can load from it. To prevent this situation, we need
8073 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8074 // the same chain operand as O, we create a token factor from the chain results
8075 // of O and L, and we replace all uses of O's chain result with that token
8076 // factor (see spliceIntoChain below for this last part).
8077 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8078                                             ReuseLoadInfo &RLI,
8079                                             SelectionDAG &DAG,
8080                                             ISD::LoadExtType ET) const {
8081   SDLoc dl(Op);
8082   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8083                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8084   if (ET == ISD::NON_EXTLOAD &&
8085       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8086       isOperationLegalOrCustom(Op.getOpcode(),
8087                                Op.getOperand(0).getValueType())) {
8088 
8089     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8090     return true;
8091   }
8092 
8093   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8094   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8095       LD->isNonTemporal())
8096     return false;
8097   if (LD->getMemoryVT() != MemVT)
8098     return false;
8099 
8100   RLI.Ptr = LD->getBasePtr();
8101   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8102     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8103            "Non-pre-inc AM on PPC?");
8104     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8105                           LD->getOffset());
8106   }
8107 
8108   RLI.Chain = LD->getChain();
8109   RLI.MPI = LD->getPointerInfo();
8110   RLI.IsDereferenceable = LD->isDereferenceable();
8111   RLI.IsInvariant = LD->isInvariant();
8112   RLI.Alignment = LD->getAlign();
8113   RLI.AAInfo = LD->getAAInfo();
8114   RLI.Ranges = LD->getRanges();
8115 
8116   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8117   return true;
8118 }
8119 
8120 // Given the head of the old chain, ResChain, insert a token factor containing
8121 // it and NewResChain, and make users of ResChain now be users of that token
8122 // factor.
8123 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8124 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8125                                         SDValue NewResChain,
8126                                         SelectionDAG &DAG) const {
8127   if (!ResChain)
8128     return;
8129 
8130   SDLoc dl(NewResChain);
8131 
8132   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8133                            NewResChain, DAG.getUNDEF(MVT::Other));
8134   assert(TF.getNode() != NewResChain.getNode() &&
8135          "A new TF really is required here");
8136 
8137   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8138   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8139 }
8140 
8141 /// Analyze profitability of direct move
8142 /// prefer float load to int load plus direct move
8143 /// when there is no integer use of int load
8144 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8145   SDNode *Origin = Op.getOperand(0).getNode();
8146   if (Origin->getOpcode() != ISD::LOAD)
8147     return true;
8148 
8149   // If there is no LXSIBZX/LXSIHZX, like Power8,
8150   // prefer direct move if the memory size is 1 or 2 bytes.
8151   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8152   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8153     return true;
8154 
8155   for (SDNode::use_iterator UI = Origin->use_begin(),
8156                             UE = Origin->use_end();
8157        UI != UE; ++UI) {
8158 
8159     // Only look at the users of the loaded value.
8160     if (UI.getUse().get().getResNo() != 0)
8161       continue;
8162 
8163     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8164         UI->getOpcode() != ISD::UINT_TO_FP)
8165       return true;
8166   }
8167 
8168   return false;
8169 }
8170 
8171 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8172                               const PPCSubtarget &Subtarget) {
8173   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8174   SDLoc dl(Op);
8175   // If we have FCFIDS, then use it when converting to single-precision.
8176   // Otherwise, convert to double-precision and then round.
8177   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8178   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8179                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8180   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8181   return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8182 }
8183 
8184 /// Custom lowers integer to floating point conversions to use
8185 /// the direct move instructions available in ISA 2.07 to avoid the
8186 /// need for load/store combinations.
8187 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8188                                                     SelectionDAG &DAG,
8189                                                     const SDLoc &dl) const {
8190   assert((Op.getValueType() == MVT::f32 ||
8191           Op.getValueType() == MVT::f64) &&
8192          "Invalid floating point type as target of conversion");
8193   assert(Subtarget.hasFPCVT() &&
8194          "Int to FP conversions with direct moves require FPCVT");
8195   SDValue Src = Op.getOperand(0);
8196   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8197   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8198   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8199   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8200   return convertIntToFP(Op, Mov, DAG, Subtarget);
8201 }
8202 
8203 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8204 
8205   EVT VecVT = Vec.getValueType();
8206   assert(VecVT.isVector() && "Expected a vector type.");
8207   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8208 
8209   EVT EltVT = VecVT.getVectorElementType();
8210   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8211   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8212 
8213   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8214   SmallVector<SDValue, 16> Ops(NumConcat);
8215   Ops[0] = Vec;
8216   SDValue UndefVec = DAG.getUNDEF(VecVT);
8217   for (unsigned i = 1; i < NumConcat; ++i)
8218     Ops[i] = UndefVec;
8219 
8220   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8221 }
8222 
8223 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8224                                                 const SDLoc &dl) const {
8225 
8226   unsigned Opc = Op.getOpcode();
8227   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8228          "Unexpected conversion type");
8229   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8230          "Supports conversions to v2f64/v4f32 only.");
8231 
8232   bool SignedConv = Opc == ISD::SINT_TO_FP;
8233   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8234 
8235   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8236   EVT WideVT = Wide.getValueType();
8237   unsigned WideNumElts = WideVT.getVectorNumElements();
8238   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8239 
8240   SmallVector<int, 16> ShuffV;
8241   for (unsigned i = 0; i < WideNumElts; ++i)
8242     ShuffV.push_back(i + WideNumElts);
8243 
8244   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8245   int SaveElts = FourEltRes ? 4 : 2;
8246   if (Subtarget.isLittleEndian())
8247     for (int i = 0; i < SaveElts; i++)
8248       ShuffV[i * Stride] = i;
8249   else
8250     for (int i = 1; i <= SaveElts; i++)
8251       ShuffV[i * Stride - 1] = i - 1;
8252 
8253   SDValue ShuffleSrc2 =
8254       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8255   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8256 
8257   SDValue Extend;
8258   if (SignedConv) {
8259     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8260     EVT ExtVT = Op.getOperand(0).getValueType();
8261     if (Subtarget.hasP9Altivec())
8262       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8263                                IntermediateVT.getVectorNumElements());
8264 
8265     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8266                          DAG.getValueType(ExtVT));
8267   } else
8268     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8269 
8270   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8271 }
8272 
8273 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8274                                           SelectionDAG &DAG) const {
8275   SDLoc dl(Op);
8276   SDValue Src = Op.getOperand(0);
8277   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8278 
8279   EVT InVT = Src.getValueType();
8280   EVT OutVT = Op.getValueType();
8281   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8282       isOperationCustom(Op.getOpcode(), InVT))
8283     return LowerINT_TO_FPVector(Op, DAG, dl);
8284 
8285   // Conversions to f128 are legal.
8286   if (Op.getValueType() == MVT::f128)
8287     return Op;
8288 
8289   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8290   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8291     return SDValue();
8292 
8293   if (Src.getValueType() == MVT::i1)
8294     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8295                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8296                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8297 
8298   // If we have direct moves, we can do all the conversion, skip the store/load
8299   // however, without FPCVT we can't do most conversions.
8300   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8301       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8302     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8303 
8304   assert((IsSigned || Subtarget.hasFPCVT()) &&
8305          "UINT_TO_FP is supported only with FPCVT");
8306 
8307   if (Src.getValueType() == MVT::i64) {
8308     SDValue SINT = Src;
8309     // When converting to single-precision, we actually need to convert
8310     // to double-precision first and then round to single-precision.
8311     // To avoid double-rounding effects during that operation, we have
8312     // to prepare the input operand.  Bits that might be truncated when
8313     // converting to double-precision are replaced by a bit that won't
8314     // be lost at this stage, but is below the single-precision rounding
8315     // position.
8316     //
8317     // However, if -enable-unsafe-fp-math is in effect, accept double
8318     // rounding to avoid the extra overhead.
8319     if (Op.getValueType() == MVT::f32 &&
8320         !Subtarget.hasFPCVT() &&
8321         !DAG.getTarget().Options.UnsafeFPMath) {
8322 
8323       // Twiddle input to make sure the low 11 bits are zero.  (If this
8324       // is the case, we are guaranteed the value will fit into the 53 bit
8325       // mantissa of an IEEE double-precision value without rounding.)
8326       // If any of those low 11 bits were not zero originally, make sure
8327       // bit 12 (value 2048) is set instead, so that the final rounding
8328       // to single-precision gets the correct result.
8329       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8330                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8331       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8332                           Round, DAG.getConstant(2047, dl, MVT::i64));
8333       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8334       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8335                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8336 
8337       // However, we cannot use that value unconditionally: if the magnitude
8338       // of the input value is small, the bit-twiddling we did above might
8339       // end up visibly changing the output.  Fortunately, in that case, we
8340       // don't need to twiddle bits since the original input will convert
8341       // exactly to double-precision floating-point already.  Therefore,
8342       // construct a conditional to use the original value if the top 11
8343       // bits are all sign-bit copies, and use the rounded value computed
8344       // above otherwise.
8345       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8346                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8347       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8348                          Cond, DAG.getConstant(1, dl, MVT::i64));
8349       Cond = DAG.getSetCC(
8350           dl,
8351           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8352           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8353 
8354       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8355     }
8356 
8357     ReuseLoadInfo RLI;
8358     SDValue Bits;
8359 
8360     MachineFunction &MF = DAG.getMachineFunction();
8361     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8362       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8363                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8364       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8365     } else if (Subtarget.hasLFIWAX() &&
8366                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8367       MachineMemOperand *MMO =
8368         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8369                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8370       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8371       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8372                                      DAG.getVTList(MVT::f64, MVT::Other),
8373                                      Ops, MVT::i32, MMO);
8374       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8375     } else if (Subtarget.hasFPCVT() &&
8376                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8377       MachineMemOperand *MMO =
8378         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8379                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8380       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8381       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8382                                      DAG.getVTList(MVT::f64, MVT::Other),
8383                                      Ops, MVT::i32, MMO);
8384       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8385     } else if (((Subtarget.hasLFIWAX() &&
8386                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8387                 (Subtarget.hasFPCVT() &&
8388                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8389                SINT.getOperand(0).getValueType() == MVT::i32) {
8390       MachineFrameInfo &MFI = MF.getFrameInfo();
8391       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8392 
8393       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8394       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8395 
8396       SDValue Store =
8397           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8398                        MachinePointerInfo::getFixedStack(
8399                            DAG.getMachineFunction(), FrameIdx));
8400 
8401       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8402              "Expected an i32 store");
8403 
8404       RLI.Ptr = FIdx;
8405       RLI.Chain = Store;
8406       RLI.MPI =
8407           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8408       RLI.Alignment = Align(4);
8409 
8410       MachineMemOperand *MMO =
8411         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8412                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8413       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8414       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8415                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8416                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8417                                      Ops, MVT::i32, MMO);
8418     } else
8419       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8420 
8421     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget);
8422 
8423     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8424       FP = DAG.getNode(ISD::FP_ROUND, dl,
8425                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8426     return FP;
8427   }
8428 
8429   assert(Src.getValueType() == MVT::i32 &&
8430          "Unhandled INT_TO_FP type in custom expander!");
8431   // Since we only generate this in 64-bit mode, we can take advantage of
8432   // 64-bit registers.  In particular, sign extend the input value into the
8433   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8434   // then lfd it and fcfid it.
8435   MachineFunction &MF = DAG.getMachineFunction();
8436   MachineFrameInfo &MFI = MF.getFrameInfo();
8437   EVT PtrVT = getPointerTy(MF.getDataLayout());
8438 
8439   SDValue Ld;
8440   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8441     ReuseLoadInfo RLI;
8442     bool ReusingLoad;
8443     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8444       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8445       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8446 
8447       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx,
8448                                    MachinePointerInfo::getFixedStack(
8449                                        DAG.getMachineFunction(), FrameIdx));
8450 
8451       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8452              "Expected an i32 store");
8453 
8454       RLI.Ptr = FIdx;
8455       RLI.Chain = Store;
8456       RLI.MPI =
8457           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8458       RLI.Alignment = Align(4);
8459     }
8460 
8461     MachineMemOperand *MMO =
8462       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8463                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8464     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8465     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8466                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8467                                  MVT::i32, MMO);
8468     if (ReusingLoad)
8469       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8470   } else {
8471     assert(Subtarget.isPPC64() &&
8472            "i32->FP without LFIWAX supported only on PPC64");
8473 
8474     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8475     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8476 
8477     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8478 
8479     // STD the extended value into the stack slot.
8480     SDValue Store = DAG.getStore(
8481         DAG.getEntryNode(), dl, Ext64, FIdx,
8482         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8483 
8484     // Load the value as a double.
8485     Ld = DAG.getLoad(
8486         MVT::f64, dl, Store, FIdx,
8487         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8488   }
8489 
8490   // FCFID it and return it.
8491   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget);
8492   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8493     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8494                      DAG.getIntPtrConstant(0, dl));
8495   return FP;
8496 }
8497 
8498 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8499                                             SelectionDAG &DAG) const {
8500   SDLoc dl(Op);
8501   /*
8502    The rounding mode is in bits 30:31 of FPSR, and has the following
8503    settings:
8504      00 Round to nearest
8505      01 Round to 0
8506      10 Round to +inf
8507      11 Round to -inf
8508 
8509   FLT_ROUNDS, on the other hand, expects the following:
8510     -1 Undefined
8511      0 Round to 0
8512      1 Round to nearest
8513      2 Round to +inf
8514      3 Round to -inf
8515 
8516   To perform the conversion, we do:
8517     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8518   */
8519 
8520   MachineFunction &MF = DAG.getMachineFunction();
8521   EVT VT = Op.getValueType();
8522   EVT PtrVT = getPointerTy(MF.getDataLayout());
8523 
8524   // Save FP Control Word to register
8525   SDValue Chain = Op.getOperand(0);
8526   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8527   Chain = MFFS.getValue(1);
8528 
8529   // Save FP register to stack slot
8530   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8531   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8532   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8533 
8534   // Load FP Control Word from low 32 bits of stack slot.
8535   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8536   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8537   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8538   Chain = CWD.getValue(1);
8539 
8540   // Transform as necessary
8541   SDValue CWD1 =
8542     DAG.getNode(ISD::AND, dl, MVT::i32,
8543                 CWD, DAG.getConstant(3, dl, MVT::i32));
8544   SDValue CWD2 =
8545     DAG.getNode(ISD::SRL, dl, MVT::i32,
8546                 DAG.getNode(ISD::AND, dl, MVT::i32,
8547                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8548                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8549                             DAG.getConstant(3, dl, MVT::i32)),
8550                 DAG.getConstant(1, dl, MVT::i32));
8551 
8552   SDValue RetVal =
8553     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8554 
8555   RetVal =
8556       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8557                   dl, VT, RetVal);
8558 
8559   return DAG.getMergeValues({RetVal, Chain}, dl);
8560 }
8561 
8562 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8563   EVT VT = Op.getValueType();
8564   unsigned BitWidth = VT.getSizeInBits();
8565   SDLoc dl(Op);
8566   assert(Op.getNumOperands() == 3 &&
8567          VT == Op.getOperand(1).getValueType() &&
8568          "Unexpected SHL!");
8569 
8570   // Expand into a bunch of logical ops.  Note that these ops
8571   // depend on the PPC behavior for oversized shift amounts.
8572   SDValue Lo = Op.getOperand(0);
8573   SDValue Hi = Op.getOperand(1);
8574   SDValue Amt = Op.getOperand(2);
8575   EVT AmtVT = Amt.getValueType();
8576 
8577   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8578                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8579   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8580   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8581   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8582   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8583                              DAG.getConstant(-BitWidth, dl, AmtVT));
8584   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8585   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8586   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8587   SDValue OutOps[] = { OutLo, OutHi };
8588   return DAG.getMergeValues(OutOps, dl);
8589 }
8590 
8591 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8592   EVT VT = Op.getValueType();
8593   SDLoc dl(Op);
8594   unsigned BitWidth = VT.getSizeInBits();
8595   assert(Op.getNumOperands() == 3 &&
8596          VT == Op.getOperand(1).getValueType() &&
8597          "Unexpected SRL!");
8598 
8599   // Expand into a bunch of logical ops.  Note that these ops
8600   // depend on the PPC behavior for oversized shift amounts.
8601   SDValue Lo = Op.getOperand(0);
8602   SDValue Hi = Op.getOperand(1);
8603   SDValue Amt = Op.getOperand(2);
8604   EVT AmtVT = Amt.getValueType();
8605 
8606   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8607                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8608   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8609   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8610   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8611   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8612                              DAG.getConstant(-BitWidth, dl, AmtVT));
8613   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8614   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8615   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8616   SDValue OutOps[] = { OutLo, OutHi };
8617   return DAG.getMergeValues(OutOps, dl);
8618 }
8619 
8620 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8621   SDLoc dl(Op);
8622   EVT VT = Op.getValueType();
8623   unsigned BitWidth = VT.getSizeInBits();
8624   assert(Op.getNumOperands() == 3 &&
8625          VT == Op.getOperand(1).getValueType() &&
8626          "Unexpected SRA!");
8627 
8628   // Expand into a bunch of logical ops, followed by a select_cc.
8629   SDValue Lo = Op.getOperand(0);
8630   SDValue Hi = Op.getOperand(1);
8631   SDValue Amt = Op.getOperand(2);
8632   EVT AmtVT = Amt.getValueType();
8633 
8634   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8635                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8636   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8637   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8638   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8639   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8640                              DAG.getConstant(-BitWidth, dl, AmtVT));
8641   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8642   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8643   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8644                                   Tmp4, Tmp6, ISD::SETLE);
8645   SDValue OutOps[] = { OutLo, OutHi };
8646   return DAG.getMergeValues(OutOps, dl);
8647 }
8648 
8649 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8650                                             SelectionDAG &DAG) const {
8651   SDLoc dl(Op);
8652   EVT VT = Op.getValueType();
8653   unsigned BitWidth = VT.getSizeInBits();
8654 
8655   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8656   SDValue X = Op.getOperand(0);
8657   SDValue Y = Op.getOperand(1);
8658   SDValue Z = Op.getOperand(2);
8659   EVT AmtVT = Z.getValueType();
8660 
8661   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8662   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8663   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8664   // on PowerPC shift by BW being well defined.
8665   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8666                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8667   SDValue SubZ =
8668       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8669   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8670   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8671   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8672 }
8673 
8674 //===----------------------------------------------------------------------===//
8675 // Vector related lowering.
8676 //
8677 
8678 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8679 /// element size of SplatSize. Cast the result to VT.
8680 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8681                                       SelectionDAG &DAG, const SDLoc &dl) {
8682   static const MVT VTys[] = { // canonical VT to use for each size.
8683     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8684   };
8685 
8686   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8687 
8688   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8689   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8690     SplatSize = 1;
8691     Val = 0xFF;
8692   }
8693 
8694   EVT CanonicalVT = VTys[SplatSize-1];
8695 
8696   // Build a canonical splat for this value.
8697   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8698 }
8699 
8700 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8701 /// specified intrinsic ID.
8702 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8703                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8704   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8705   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8706                      DAG.getConstant(IID, dl, MVT::i32), Op);
8707 }
8708 
8709 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8710 /// specified intrinsic ID.
8711 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8712                                 SelectionDAG &DAG, const SDLoc &dl,
8713                                 EVT DestVT = MVT::Other) {
8714   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8715   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8716                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8717 }
8718 
8719 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8720 /// specified intrinsic ID.
8721 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8722                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8723                                 EVT DestVT = MVT::Other) {
8724   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8725   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8726                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8727 }
8728 
8729 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8730 /// amount.  The result has the specified value type.
8731 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8732                            SelectionDAG &DAG, const SDLoc &dl) {
8733   // Force LHS/RHS to be the right type.
8734   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8735   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8736 
8737   int Ops[16];
8738   for (unsigned i = 0; i != 16; ++i)
8739     Ops[i] = i + Amt;
8740   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8741   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8742 }
8743 
8744 /// Do we have an efficient pattern in a .td file for this node?
8745 ///
8746 /// \param V - pointer to the BuildVectorSDNode being matched
8747 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8748 ///
8749 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8750 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8751 /// the opposite is true (expansion is beneficial) are:
8752 /// - The node builds a vector out of integers that are not 32 or 64-bits
8753 /// - The node builds a vector out of constants
8754 /// - The node is a "load-and-splat"
8755 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8756 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8757                                             bool HasDirectMove,
8758                                             bool HasP8Vector) {
8759   EVT VecVT = V->getValueType(0);
8760   bool RightType = VecVT == MVT::v2f64 ||
8761     (HasP8Vector && VecVT == MVT::v4f32) ||
8762     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8763   if (!RightType)
8764     return false;
8765 
8766   bool IsSplat = true;
8767   bool IsLoad = false;
8768   SDValue Op0 = V->getOperand(0);
8769 
8770   // This function is called in a block that confirms the node is not a constant
8771   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8772   // different constants.
8773   if (V->isConstant())
8774     return false;
8775   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8776     if (V->getOperand(i).isUndef())
8777       return false;
8778     // We want to expand nodes that represent load-and-splat even if the
8779     // loaded value is a floating point truncation or conversion to int.
8780     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8781         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8782          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8783         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8784          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8785         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8786          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8787       IsLoad = true;
8788     // If the operands are different or the input is not a load and has more
8789     // uses than just this BV node, then it isn't a splat.
8790     if (V->getOperand(i) != Op0 ||
8791         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8792       IsSplat = false;
8793   }
8794   return !(IsSplat && IsLoad);
8795 }
8796 
8797 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8798 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8799 
8800   SDLoc dl(Op);
8801   SDValue Op0 = Op->getOperand(0);
8802 
8803   if ((Op.getValueType() != MVT::f128) ||
8804       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8805       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8806       (Op0.getOperand(1).getValueType() != MVT::i64))
8807     return SDValue();
8808 
8809   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8810                      Op0.getOperand(1));
8811 }
8812 
8813 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8814   const SDValue *InputLoad = &Op;
8815   if (InputLoad->getOpcode() == ISD::BITCAST)
8816     InputLoad = &InputLoad->getOperand(0);
8817   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8818       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8819     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8820     InputLoad = &InputLoad->getOperand(0);
8821   }
8822   if (InputLoad->getOpcode() != ISD::LOAD)
8823     return nullptr;
8824   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8825   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8826 }
8827 
8828 // Convert the argument APFloat to a single precision APFloat if there is no
8829 // loss in information during the conversion to single precision APFloat and the
8830 // resulting number is not a denormal number. Return true if successful.
8831 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8832   APFloat APFloatToConvert = ArgAPFloat;
8833   bool LosesInfo = true;
8834   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8835                            &LosesInfo);
8836   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8837   if (Success)
8838     ArgAPFloat = APFloatToConvert;
8839   return Success;
8840 }
8841 
8842 // Bitcast the argument APInt to a double and convert it to a single precision
8843 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8844 // argument if there is no loss in information during the conversion from
8845 // double to single precision APFloat and the resulting number is not a denormal
8846 // number. Return true if successful.
8847 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8848   double DpValue = ArgAPInt.bitsToDouble();
8849   APFloat APFloatDp(DpValue);
8850   bool Success = convertToNonDenormSingle(APFloatDp);
8851   if (Success)
8852     ArgAPInt = APFloatDp.bitcastToAPInt();
8853   return Success;
8854 }
8855 
8856 // If this is a case we can't handle, return null and let the default
8857 // expansion code take care of it.  If we CAN select this case, and if it
8858 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8859 // this case more efficiently than a constant pool load, lower it to the
8860 // sequence of ops that should be used.
8861 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8862                                              SelectionDAG &DAG) const {
8863   SDLoc dl(Op);
8864   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8865   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8866 
8867   // Check if this is a splat of a constant value.
8868   APInt APSplatBits, APSplatUndef;
8869   unsigned SplatBitSize;
8870   bool HasAnyUndefs;
8871   bool BVNIsConstantSplat =
8872       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8873                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8874 
8875   // If it is a splat of a double, check if we can shrink it to a 32 bit
8876   // non-denormal float which when converted back to double gives us the same
8877   // double. This is to exploit the XXSPLTIDP instruction.
8878   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
8879       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
8880       convertToNonDenormSingle(APSplatBits)) {
8881     SDValue SplatNode = DAG.getNode(
8882         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8883         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8884     return DAG.getBitcast(Op.getValueType(), SplatNode);
8885   }
8886 
8887   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8888 
8889     bool IsPermutedLoad = false;
8890     const SDValue *InputLoad =
8891         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8892     // Handle load-and-splat patterns as we have instructions that will do this
8893     // in one go.
8894     if (InputLoad && DAG.isSplatValue(Op, true)) {
8895       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8896 
8897       // We have handling for 4 and 8 byte elements.
8898       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8899 
8900       // Checking for a single use of this load, we have to check for vector
8901       // width (128 bits) / ElementSize uses (since each operand of the
8902       // BUILD_VECTOR is a separate use of the value.
8903       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8904           ((Subtarget.hasVSX() && ElementSize == 64) ||
8905            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8906         SDValue Ops[] = {
8907           LD->getChain(),    // Chain
8908           LD->getBasePtr(),  // Ptr
8909           DAG.getValueType(Op.getValueType()) // VT
8910         };
8911         return
8912           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8913                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8914                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8915       }
8916     }
8917 
8918     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8919     // lowered to VSX instructions under certain conditions.
8920     // Without VSX, there is no pattern more efficient than expanding the node.
8921     if (Subtarget.hasVSX() &&
8922         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8923                                         Subtarget.hasP8Vector()))
8924       return Op;
8925     return SDValue();
8926   }
8927 
8928   uint64_t SplatBits = APSplatBits.getZExtValue();
8929   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8930   unsigned SplatSize = SplatBitSize / 8;
8931 
8932   // First, handle single instruction cases.
8933 
8934   // All zeros?
8935   if (SplatBits == 0) {
8936     // Canonicalize all zero vectors to be v4i32.
8937     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8938       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8939       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8940     }
8941     return Op;
8942   }
8943 
8944   // We have XXSPLTIW for constant splats four bytes wide.
8945   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8946   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8947   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8948   // turned into a 4-byte splat of 0xABABABAB.
8949   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8950     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
8951                                   Op.getValueType(), DAG, dl);
8952 
8953   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
8954     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8955                                   dl);
8956 
8957   // We have XXSPLTIB for constant splats one byte wide.
8958   if (Subtarget.hasP9Vector() && SplatSize == 1)
8959     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8960                                   dl);
8961 
8962   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8963   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8964                     (32-SplatBitSize));
8965   if (SextVal >= -16 && SextVal <= 15)
8966     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
8967                                   dl);
8968 
8969   // Two instruction sequences.
8970 
8971   // If this value is in the range [-32,30] and is even, use:
8972   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8973   // If this value is in the range [17,31] and is odd, use:
8974   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8975   // If this value is in the range [-31,-17] and is odd, use:
8976   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8977   // Note the last two are three-instruction sequences.
8978   if (SextVal >= -32 && SextVal <= 31) {
8979     // To avoid having these optimizations undone by constant folding,
8980     // we convert to a pseudo that will be expanded later into one of
8981     // the above forms.
8982     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8983     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8984               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8985     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8986     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8987     if (VT == Op.getValueType())
8988       return RetVal;
8989     else
8990       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8991   }
8992 
8993   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8994   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8995   // for fneg/fabs.
8996   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8997     // Make -1 and vspltisw -1:
8998     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
8999 
9000     // Make the VSLW intrinsic, computing 0x8000_0000.
9001     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9002                                    OnesV, DAG, dl);
9003 
9004     // xor by OnesV to invert it.
9005     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9006     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9007   }
9008 
9009   // Check to see if this is a wide variety of vsplti*, binop self cases.
9010   static const signed char SplatCsts[] = {
9011     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9012     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9013   };
9014 
9015   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9016     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9017     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9018     int i = SplatCsts[idx];
9019 
9020     // Figure out what shift amount will be used by altivec if shifted by i in
9021     // this splat size.
9022     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9023 
9024     // vsplti + shl self.
9025     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9026       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9027       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9028         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9029         Intrinsic::ppc_altivec_vslw
9030       };
9031       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9032       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9033     }
9034 
9035     // vsplti + srl self.
9036     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9037       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9038       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9039         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9040         Intrinsic::ppc_altivec_vsrw
9041       };
9042       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9043       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9044     }
9045 
9046     // vsplti + sra self.
9047     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9048       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9049       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9050         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9051         Intrinsic::ppc_altivec_vsraw
9052       };
9053       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9054       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9055     }
9056 
9057     // vsplti + rol self.
9058     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9059                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9060       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9061       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9062         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9063         Intrinsic::ppc_altivec_vrlw
9064       };
9065       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9066       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9067     }
9068 
9069     // t = vsplti c, result = vsldoi t, t, 1
9070     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9071       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9072       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9073       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9074     }
9075     // t = vsplti c, result = vsldoi t, t, 2
9076     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9077       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9078       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9079       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9080     }
9081     // t = vsplti c, result = vsldoi t, t, 3
9082     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9083       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9084       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9085       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9086     }
9087   }
9088 
9089   return SDValue();
9090 }
9091 
9092 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9093 /// the specified operations to build the shuffle.
9094 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9095                                       SDValue RHS, SelectionDAG &DAG,
9096                                       const SDLoc &dl) {
9097   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9098   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9099   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9100 
9101   enum {
9102     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9103     OP_VMRGHW,
9104     OP_VMRGLW,
9105     OP_VSPLTISW0,
9106     OP_VSPLTISW1,
9107     OP_VSPLTISW2,
9108     OP_VSPLTISW3,
9109     OP_VSLDOI4,
9110     OP_VSLDOI8,
9111     OP_VSLDOI12
9112   };
9113 
9114   if (OpNum == OP_COPY) {
9115     if (LHSID == (1*9+2)*9+3) return LHS;
9116     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9117     return RHS;
9118   }
9119 
9120   SDValue OpLHS, OpRHS;
9121   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9122   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9123 
9124   int ShufIdxs[16];
9125   switch (OpNum) {
9126   default: llvm_unreachable("Unknown i32 permute!");
9127   case OP_VMRGHW:
9128     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9129     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9130     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9131     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9132     break;
9133   case OP_VMRGLW:
9134     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9135     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9136     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9137     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9138     break;
9139   case OP_VSPLTISW0:
9140     for (unsigned i = 0; i != 16; ++i)
9141       ShufIdxs[i] = (i&3)+0;
9142     break;
9143   case OP_VSPLTISW1:
9144     for (unsigned i = 0; i != 16; ++i)
9145       ShufIdxs[i] = (i&3)+4;
9146     break;
9147   case OP_VSPLTISW2:
9148     for (unsigned i = 0; i != 16; ++i)
9149       ShufIdxs[i] = (i&3)+8;
9150     break;
9151   case OP_VSPLTISW3:
9152     for (unsigned i = 0; i != 16; ++i)
9153       ShufIdxs[i] = (i&3)+12;
9154     break;
9155   case OP_VSLDOI4:
9156     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9157   case OP_VSLDOI8:
9158     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9159   case OP_VSLDOI12:
9160     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9161   }
9162   EVT VT = OpLHS.getValueType();
9163   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9164   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9165   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9166   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9167 }
9168 
9169 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9170 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9171 /// SDValue.
9172 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9173                                            SelectionDAG &DAG) const {
9174   const unsigned BytesInVector = 16;
9175   bool IsLE = Subtarget.isLittleEndian();
9176   SDLoc dl(N);
9177   SDValue V1 = N->getOperand(0);
9178   SDValue V2 = N->getOperand(1);
9179   unsigned ShiftElts = 0, InsertAtByte = 0;
9180   bool Swap = false;
9181 
9182   // Shifts required to get the byte we want at element 7.
9183   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9184                                    0, 15, 14, 13, 12, 11, 10, 9};
9185   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9186                                 1, 2,  3,  4,  5,  6,  7,  8};
9187 
9188   ArrayRef<int> Mask = N->getMask();
9189   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9190 
9191   // For each mask element, find out if we're just inserting something
9192   // from V2 into V1 or vice versa.
9193   // Possible permutations inserting an element from V2 into V1:
9194   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9195   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9196   //   ...
9197   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9198   // Inserting from V1 into V2 will be similar, except mask range will be
9199   // [16,31].
9200 
9201   bool FoundCandidate = false;
9202   // If both vector operands for the shuffle are the same vector, the mask
9203   // will contain only elements from the first one and the second one will be
9204   // undef.
9205   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9206   // Go through the mask of half-words to find an element that's being moved
9207   // from one vector to the other.
9208   for (unsigned i = 0; i < BytesInVector; ++i) {
9209     unsigned CurrentElement = Mask[i];
9210     // If 2nd operand is undefined, we should only look for element 7 in the
9211     // Mask.
9212     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9213       continue;
9214 
9215     bool OtherElementsInOrder = true;
9216     // Examine the other elements in the Mask to see if they're in original
9217     // order.
9218     for (unsigned j = 0; j < BytesInVector; ++j) {
9219       if (j == i)
9220         continue;
9221       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9222       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9223       // in which we always assume we're always picking from the 1st operand.
9224       int MaskOffset =
9225           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9226       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9227         OtherElementsInOrder = false;
9228         break;
9229       }
9230     }
9231     // If other elements are in original order, we record the number of shifts
9232     // we need to get the element we want into element 7. Also record which byte
9233     // in the vector we should insert into.
9234     if (OtherElementsInOrder) {
9235       // If 2nd operand is undefined, we assume no shifts and no swapping.
9236       if (V2.isUndef()) {
9237         ShiftElts = 0;
9238         Swap = false;
9239       } else {
9240         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9241         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9242                          : BigEndianShifts[CurrentElement & 0xF];
9243         Swap = CurrentElement < BytesInVector;
9244       }
9245       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9246       FoundCandidate = true;
9247       break;
9248     }
9249   }
9250 
9251   if (!FoundCandidate)
9252     return SDValue();
9253 
9254   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9255   // optionally with VECSHL if shift is required.
9256   if (Swap)
9257     std::swap(V1, V2);
9258   if (V2.isUndef())
9259     V2 = V1;
9260   if (ShiftElts) {
9261     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9262                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9263     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9264                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9265   }
9266   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9267                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9268 }
9269 
9270 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9271 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9272 /// SDValue.
9273 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9274                                            SelectionDAG &DAG) const {
9275   const unsigned NumHalfWords = 8;
9276   const unsigned BytesInVector = NumHalfWords * 2;
9277   // Check that the shuffle is on half-words.
9278   if (!isNByteElemShuffleMask(N, 2, 1))
9279     return SDValue();
9280 
9281   bool IsLE = Subtarget.isLittleEndian();
9282   SDLoc dl(N);
9283   SDValue V1 = N->getOperand(0);
9284   SDValue V2 = N->getOperand(1);
9285   unsigned ShiftElts = 0, InsertAtByte = 0;
9286   bool Swap = false;
9287 
9288   // Shifts required to get the half-word we want at element 3.
9289   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9290   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9291 
9292   uint32_t Mask = 0;
9293   uint32_t OriginalOrderLow = 0x1234567;
9294   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9295   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9296   // 32-bit space, only need 4-bit nibbles per element.
9297   for (unsigned i = 0; i < NumHalfWords; ++i) {
9298     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9299     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9300   }
9301 
9302   // For each mask element, find out if we're just inserting something
9303   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9304   // from V2 into V1:
9305   //   X, 1, 2, 3, 4, 5, 6, 7
9306   //   0, X, 2, 3, 4, 5, 6, 7
9307   //   0, 1, X, 3, 4, 5, 6, 7
9308   //   0, 1, 2, X, 4, 5, 6, 7
9309   //   0, 1, 2, 3, X, 5, 6, 7
9310   //   0, 1, 2, 3, 4, X, 6, 7
9311   //   0, 1, 2, 3, 4, 5, X, 7
9312   //   0, 1, 2, 3, 4, 5, 6, X
9313   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9314 
9315   bool FoundCandidate = false;
9316   // Go through the mask of half-words to find an element that's being moved
9317   // from one vector to the other.
9318   for (unsigned i = 0; i < NumHalfWords; ++i) {
9319     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9320     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9321     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9322     uint32_t TargetOrder = 0x0;
9323 
9324     // If both vector operands for the shuffle are the same vector, the mask
9325     // will contain only elements from the first one and the second one will be
9326     // undef.
9327     if (V2.isUndef()) {
9328       ShiftElts = 0;
9329       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9330       TargetOrder = OriginalOrderLow;
9331       Swap = false;
9332       // Skip if not the correct element or mask of other elements don't equal
9333       // to our expected order.
9334       if (MaskOneElt == VINSERTHSrcElem &&
9335           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9336         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9337         FoundCandidate = true;
9338         break;
9339       }
9340     } else { // If both operands are defined.
9341       // Target order is [8,15] if the current mask is between [0,7].
9342       TargetOrder =
9343           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9344       // Skip if mask of other elements don't equal our expected order.
9345       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9346         // We only need the last 3 bits for the number of shifts.
9347         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9348                          : BigEndianShifts[MaskOneElt & 0x7];
9349         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9350         Swap = MaskOneElt < NumHalfWords;
9351         FoundCandidate = true;
9352         break;
9353       }
9354     }
9355   }
9356 
9357   if (!FoundCandidate)
9358     return SDValue();
9359 
9360   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9361   // optionally with VECSHL if shift is required.
9362   if (Swap)
9363     std::swap(V1, V2);
9364   if (V2.isUndef())
9365     V2 = V1;
9366   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9367   if (ShiftElts) {
9368     // Double ShiftElts because we're left shifting on v16i8 type.
9369     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9370                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9371     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9372     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9373                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9374     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9375   }
9376   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9377   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9378                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9379   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9380 }
9381 
9382 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9383 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9384 /// return the default SDValue.
9385 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9386                                               SelectionDAG &DAG) const {
9387   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9388   // to v16i8. Peek through the bitcasts to get the actual operands.
9389   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9390   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9391 
9392   auto ShuffleMask = SVN->getMask();
9393   SDValue VecShuffle(SVN, 0);
9394   SDLoc DL(SVN);
9395 
9396   // Check that we have a four byte shuffle.
9397   if (!isNByteElemShuffleMask(SVN, 4, 1))
9398     return SDValue();
9399 
9400   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9401   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9402     std::swap(LHS, RHS);
9403     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9404     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9405   }
9406 
9407   // Ensure that the RHS is a vector of constants.
9408   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9409   if (!BVN)
9410     return SDValue();
9411 
9412   // Check if RHS is a splat of 4-bytes (or smaller).
9413   APInt APSplatValue, APSplatUndef;
9414   unsigned SplatBitSize;
9415   bool HasAnyUndefs;
9416   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9417                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9418       SplatBitSize > 32)
9419     return SDValue();
9420 
9421   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9422   // The instruction splats a constant C into two words of the source vector
9423   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9424   // Thus we check that the shuffle mask is the equivalent  of
9425   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9426   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9427   // within each word are consecutive, so we only need to check the first byte.
9428   SDValue Index;
9429   bool IsLE = Subtarget.isLittleEndian();
9430   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9431       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9432        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9433     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9434   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9435            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9436             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9437     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9438   else
9439     return SDValue();
9440 
9441   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9442   // for XXSPLTI32DX.
9443   unsigned SplatVal = APSplatValue.getZExtValue();
9444   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9445     SplatVal |= (SplatVal << SplatBitSize);
9446 
9447   SDValue SplatNode = DAG.getNode(
9448       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9449       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9450   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9451 }
9452 
9453 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9454 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9455 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9456 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9457 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9458   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9459   assert(Op.getValueType() == MVT::v1i128 &&
9460          "Only set v1i128 as custom, other type shouldn't reach here!");
9461   SDLoc dl(Op);
9462   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9463   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9464   unsigned SHLAmt = N1.getConstantOperandVal(0);
9465   if (SHLAmt % 8 == 0) {
9466     SmallVector<int, 16> Mask(16, 0);
9467     std::iota(Mask.begin(), Mask.end(), 0);
9468     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9469     if (SDValue Shuffle =
9470             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9471                                  DAG.getUNDEF(MVT::v16i8), Mask))
9472       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9473   }
9474   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9475   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9476                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9477   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9478                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9479   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9480   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9481 }
9482 
9483 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9484 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9485 /// return the code it can be lowered into.  Worst case, it can always be
9486 /// lowered into a vperm.
9487 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9488                                                SelectionDAG &DAG) const {
9489   SDLoc dl(Op);
9490   SDValue V1 = Op.getOperand(0);
9491   SDValue V2 = Op.getOperand(1);
9492   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9493 
9494   // Any nodes that were combined in the target-independent combiner prior
9495   // to vector legalization will not be sent to the target combine. Try to
9496   // combine it here.
9497   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9498     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9499       return NewShuffle;
9500     Op = NewShuffle;
9501     SVOp = cast<ShuffleVectorSDNode>(Op);
9502     V1 = Op.getOperand(0);
9503     V2 = Op.getOperand(1);
9504   }
9505   EVT VT = Op.getValueType();
9506   bool isLittleEndian = Subtarget.isLittleEndian();
9507 
9508   unsigned ShiftElts, InsertAtByte;
9509   bool Swap = false;
9510 
9511   // If this is a load-and-splat, we can do that with a single instruction
9512   // in some cases. However if the load has multiple uses, we don't want to
9513   // combine it because that will just produce multiple loads.
9514   bool IsPermutedLoad = false;
9515   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9516   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9517       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9518       InputLoad->hasOneUse()) {
9519     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9520     int SplatIdx =
9521       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9522 
9523     // The splat index for permuted loads will be in the left half of the vector
9524     // which is strictly wider than the loaded value by 8 bytes. So we need to
9525     // adjust the splat index to point to the correct address in memory.
9526     if (IsPermutedLoad) {
9527       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9528       SplatIdx += IsFourByte ? 2 : 1;
9529       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9530              "Splat of a value outside of the loaded memory");
9531     }
9532 
9533     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9534     // For 4-byte load-and-splat, we need Power9.
9535     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9536       uint64_t Offset = 0;
9537       if (IsFourByte)
9538         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9539       else
9540         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9541 
9542       SDValue BasePtr = LD->getBasePtr();
9543       if (Offset != 0)
9544         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9545                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9546       SDValue Ops[] = {
9547         LD->getChain(),    // Chain
9548         BasePtr,           // BasePtr
9549         DAG.getValueType(Op.getValueType()) // VT
9550       };
9551       SDVTList VTL =
9552         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9553       SDValue LdSplt =
9554         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9555                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9556       if (LdSplt.getValueType() != SVOp->getValueType(0))
9557         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9558       return LdSplt;
9559     }
9560   }
9561   if (Subtarget.hasP9Vector() &&
9562       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9563                            isLittleEndian)) {
9564     if (Swap)
9565       std::swap(V1, V2);
9566     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9567     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9568     if (ShiftElts) {
9569       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9570                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9571       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9572                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9573       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9574     }
9575     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9576                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9577     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9578   }
9579 
9580   if (Subtarget.hasPrefixInstrs()) {
9581     SDValue SplatInsertNode;
9582     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9583       return SplatInsertNode;
9584   }
9585 
9586   if (Subtarget.hasP9Altivec()) {
9587     SDValue NewISDNode;
9588     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9589       return NewISDNode;
9590 
9591     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9592       return NewISDNode;
9593   }
9594 
9595   if (Subtarget.hasVSX() &&
9596       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9597     if (Swap)
9598       std::swap(V1, V2);
9599     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9600     SDValue Conv2 =
9601         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9602 
9603     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9604                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9605     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9606   }
9607 
9608   if (Subtarget.hasVSX() &&
9609     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9610     if (Swap)
9611       std::swap(V1, V2);
9612     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9613     SDValue Conv2 =
9614         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9615 
9616     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9617                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9618     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9619   }
9620 
9621   if (Subtarget.hasP9Vector()) {
9622      if (PPC::isXXBRHShuffleMask(SVOp)) {
9623       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9624       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9625       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9626     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9627       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9628       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9629       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9630     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9631       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9632       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9633       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9634     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9635       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9636       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9637       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9638     }
9639   }
9640 
9641   if (Subtarget.hasVSX()) {
9642     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9643       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9644 
9645       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9646       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9647                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9648       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9649     }
9650 
9651     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9652     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9653       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9654       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9655       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9656     }
9657   }
9658 
9659   // Cases that are handled by instructions that take permute immediates
9660   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9661   // selected by the instruction selector.
9662   if (V2.isUndef()) {
9663     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9664         PPC::isSplatShuffleMask(SVOp, 2) ||
9665         PPC::isSplatShuffleMask(SVOp, 4) ||
9666         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9667         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9668         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9669         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9670         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9671         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9672         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9673         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9674         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9675         (Subtarget.hasP8Altivec() && (
9676          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9677          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9678          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9679       return Op;
9680     }
9681   }
9682 
9683   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9684   // and produce a fixed permutation.  If any of these match, do not lower to
9685   // VPERM.
9686   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9687   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9688       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9689       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9690       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9691       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9692       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9693       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9694       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9695       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9696       (Subtarget.hasP8Altivec() && (
9697        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9698        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9699        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9700     return Op;
9701 
9702   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9703   // perfect shuffle table to emit an optimal matching sequence.
9704   ArrayRef<int> PermMask = SVOp->getMask();
9705 
9706   unsigned PFIndexes[4];
9707   bool isFourElementShuffle = true;
9708   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9709     unsigned EltNo = 8;   // Start out undef.
9710     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9711       if (PermMask[i*4+j] < 0)
9712         continue;   // Undef, ignore it.
9713 
9714       unsigned ByteSource = PermMask[i*4+j];
9715       if ((ByteSource & 3) != j) {
9716         isFourElementShuffle = false;
9717         break;
9718       }
9719 
9720       if (EltNo == 8) {
9721         EltNo = ByteSource/4;
9722       } else if (EltNo != ByteSource/4) {
9723         isFourElementShuffle = false;
9724         break;
9725       }
9726     }
9727     PFIndexes[i] = EltNo;
9728   }
9729 
9730   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9731   // perfect shuffle vector to determine if it is cost effective to do this as
9732   // discrete instructions, or whether we should use a vperm.
9733   // For now, we skip this for little endian until such time as we have a
9734   // little-endian perfect shuffle table.
9735   if (isFourElementShuffle && !isLittleEndian) {
9736     // Compute the index in the perfect shuffle table.
9737     unsigned PFTableIndex =
9738       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9739 
9740     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9741     unsigned Cost  = (PFEntry >> 30);
9742 
9743     // Determining when to avoid vperm is tricky.  Many things affect the cost
9744     // of vperm, particularly how many times the perm mask needs to be computed.
9745     // For example, if the perm mask can be hoisted out of a loop or is already
9746     // used (perhaps because there are multiple permutes with the same shuffle
9747     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9748     // the loop requires an extra register.
9749     //
9750     // As a compromise, we only emit discrete instructions if the shuffle can be
9751     // generated in 3 or fewer operations.  When we have loop information
9752     // available, if this block is within a loop, we should avoid using vperm
9753     // for 3-operation perms and use a constant pool load instead.
9754     if (Cost < 3)
9755       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9756   }
9757 
9758   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9759   // vector that will get spilled to the constant pool.
9760   if (V2.isUndef()) V2 = V1;
9761 
9762   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9763   // that it is in input element units, not in bytes.  Convert now.
9764 
9765   // For little endian, the order of the input vectors is reversed, and
9766   // the permutation mask is complemented with respect to 31.  This is
9767   // necessary to produce proper semantics with the big-endian-biased vperm
9768   // instruction.
9769   EVT EltVT = V1.getValueType().getVectorElementType();
9770   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9771 
9772   SmallVector<SDValue, 16> ResultMask;
9773   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9774     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9775 
9776     for (unsigned j = 0; j != BytesPerElement; ++j)
9777       if (isLittleEndian)
9778         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9779                                              dl, MVT::i32));
9780       else
9781         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9782                                              MVT::i32));
9783   }
9784 
9785   ShufflesHandledWithVPERM++;
9786   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9787   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9788   LLVM_DEBUG(SVOp->dump());
9789   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9790   LLVM_DEBUG(VPermMask.dump());
9791 
9792   if (isLittleEndian)
9793     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9794                        V2, V1, VPermMask);
9795   else
9796     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9797                        V1, V2, VPermMask);
9798 }
9799 
9800 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9801 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9802 /// information about the intrinsic.
9803 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9804                                  bool &isDot, const PPCSubtarget &Subtarget) {
9805   unsigned IntrinsicID =
9806       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9807   CompareOpc = -1;
9808   isDot = false;
9809   switch (IntrinsicID) {
9810   default:
9811     return false;
9812   // Comparison predicates.
9813   case Intrinsic::ppc_altivec_vcmpbfp_p:
9814     CompareOpc = 966;
9815     isDot = true;
9816     break;
9817   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9818     CompareOpc = 198;
9819     isDot = true;
9820     break;
9821   case Intrinsic::ppc_altivec_vcmpequb_p:
9822     CompareOpc = 6;
9823     isDot = true;
9824     break;
9825   case Intrinsic::ppc_altivec_vcmpequh_p:
9826     CompareOpc = 70;
9827     isDot = true;
9828     break;
9829   case Intrinsic::ppc_altivec_vcmpequw_p:
9830     CompareOpc = 134;
9831     isDot = true;
9832     break;
9833   case Intrinsic::ppc_altivec_vcmpequd_p:
9834     if (Subtarget.hasP8Altivec()) {
9835       CompareOpc = 199;
9836       isDot = true;
9837     } else
9838       return false;
9839     break;
9840   case Intrinsic::ppc_altivec_vcmpneb_p:
9841   case Intrinsic::ppc_altivec_vcmpneh_p:
9842   case Intrinsic::ppc_altivec_vcmpnew_p:
9843   case Intrinsic::ppc_altivec_vcmpnezb_p:
9844   case Intrinsic::ppc_altivec_vcmpnezh_p:
9845   case Intrinsic::ppc_altivec_vcmpnezw_p:
9846     if (Subtarget.hasP9Altivec()) {
9847       switch (IntrinsicID) {
9848       default:
9849         llvm_unreachable("Unknown comparison intrinsic.");
9850       case Intrinsic::ppc_altivec_vcmpneb_p:
9851         CompareOpc = 7;
9852         break;
9853       case Intrinsic::ppc_altivec_vcmpneh_p:
9854         CompareOpc = 71;
9855         break;
9856       case Intrinsic::ppc_altivec_vcmpnew_p:
9857         CompareOpc = 135;
9858         break;
9859       case Intrinsic::ppc_altivec_vcmpnezb_p:
9860         CompareOpc = 263;
9861         break;
9862       case Intrinsic::ppc_altivec_vcmpnezh_p:
9863         CompareOpc = 327;
9864         break;
9865       case Intrinsic::ppc_altivec_vcmpnezw_p:
9866         CompareOpc = 391;
9867         break;
9868       }
9869       isDot = true;
9870     } else
9871       return false;
9872     break;
9873   case Intrinsic::ppc_altivec_vcmpgefp_p:
9874     CompareOpc = 454;
9875     isDot = true;
9876     break;
9877   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9878     CompareOpc = 710;
9879     isDot = true;
9880     break;
9881   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9882     CompareOpc = 774;
9883     isDot = true;
9884     break;
9885   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9886     CompareOpc = 838;
9887     isDot = true;
9888     break;
9889   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9890     CompareOpc = 902;
9891     isDot = true;
9892     break;
9893   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9894     if (Subtarget.hasP8Altivec()) {
9895       CompareOpc = 967;
9896       isDot = true;
9897     } else
9898       return false;
9899     break;
9900   case Intrinsic::ppc_altivec_vcmpgtub_p:
9901     CompareOpc = 518;
9902     isDot = true;
9903     break;
9904   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9905     CompareOpc = 582;
9906     isDot = true;
9907     break;
9908   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9909     CompareOpc = 646;
9910     isDot = true;
9911     break;
9912   case Intrinsic::ppc_altivec_vcmpgtud_p:
9913     if (Subtarget.hasP8Altivec()) {
9914       CompareOpc = 711;
9915       isDot = true;
9916     } else
9917       return false;
9918     break;
9919 
9920   // VSX predicate comparisons use the same infrastructure
9921   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9922   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9923   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9924   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9925   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9926   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9927     if (Subtarget.hasVSX()) {
9928       switch (IntrinsicID) {
9929       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9930         CompareOpc = 99;
9931         break;
9932       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9933         CompareOpc = 115;
9934         break;
9935       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9936         CompareOpc = 107;
9937         break;
9938       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9939         CompareOpc = 67;
9940         break;
9941       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9942         CompareOpc = 83;
9943         break;
9944       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9945         CompareOpc = 75;
9946         break;
9947       }
9948       isDot = true;
9949     } else
9950       return false;
9951     break;
9952 
9953   // Normal Comparisons.
9954   case Intrinsic::ppc_altivec_vcmpbfp:
9955     CompareOpc = 966;
9956     break;
9957   case Intrinsic::ppc_altivec_vcmpeqfp:
9958     CompareOpc = 198;
9959     break;
9960   case Intrinsic::ppc_altivec_vcmpequb:
9961     CompareOpc = 6;
9962     break;
9963   case Intrinsic::ppc_altivec_vcmpequh:
9964     CompareOpc = 70;
9965     break;
9966   case Intrinsic::ppc_altivec_vcmpequw:
9967     CompareOpc = 134;
9968     break;
9969   case Intrinsic::ppc_altivec_vcmpequd:
9970     if (Subtarget.hasP8Altivec())
9971       CompareOpc = 199;
9972     else
9973       return false;
9974     break;
9975   case Intrinsic::ppc_altivec_vcmpneb:
9976   case Intrinsic::ppc_altivec_vcmpneh:
9977   case Intrinsic::ppc_altivec_vcmpnew:
9978   case Intrinsic::ppc_altivec_vcmpnezb:
9979   case Intrinsic::ppc_altivec_vcmpnezh:
9980   case Intrinsic::ppc_altivec_vcmpnezw:
9981     if (Subtarget.hasP9Altivec())
9982       switch (IntrinsicID) {
9983       default:
9984         llvm_unreachable("Unknown comparison intrinsic.");
9985       case Intrinsic::ppc_altivec_vcmpneb:
9986         CompareOpc = 7;
9987         break;
9988       case Intrinsic::ppc_altivec_vcmpneh:
9989         CompareOpc = 71;
9990         break;
9991       case Intrinsic::ppc_altivec_vcmpnew:
9992         CompareOpc = 135;
9993         break;
9994       case Intrinsic::ppc_altivec_vcmpnezb:
9995         CompareOpc = 263;
9996         break;
9997       case Intrinsic::ppc_altivec_vcmpnezh:
9998         CompareOpc = 327;
9999         break;
10000       case Intrinsic::ppc_altivec_vcmpnezw:
10001         CompareOpc = 391;
10002         break;
10003       }
10004     else
10005       return false;
10006     break;
10007   case Intrinsic::ppc_altivec_vcmpgefp:
10008     CompareOpc = 454;
10009     break;
10010   case Intrinsic::ppc_altivec_vcmpgtfp:
10011     CompareOpc = 710;
10012     break;
10013   case Intrinsic::ppc_altivec_vcmpgtsb:
10014     CompareOpc = 774;
10015     break;
10016   case Intrinsic::ppc_altivec_vcmpgtsh:
10017     CompareOpc = 838;
10018     break;
10019   case Intrinsic::ppc_altivec_vcmpgtsw:
10020     CompareOpc = 902;
10021     break;
10022   case Intrinsic::ppc_altivec_vcmpgtsd:
10023     if (Subtarget.hasP8Altivec())
10024       CompareOpc = 967;
10025     else
10026       return false;
10027     break;
10028   case Intrinsic::ppc_altivec_vcmpgtub:
10029     CompareOpc = 518;
10030     break;
10031   case Intrinsic::ppc_altivec_vcmpgtuh:
10032     CompareOpc = 582;
10033     break;
10034   case Intrinsic::ppc_altivec_vcmpgtuw:
10035     CompareOpc = 646;
10036     break;
10037   case Intrinsic::ppc_altivec_vcmpgtud:
10038     if (Subtarget.hasP8Altivec())
10039       CompareOpc = 711;
10040     else
10041       return false;
10042     break;
10043   }
10044   return true;
10045 }
10046 
10047 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10048 /// lower, do it, otherwise return null.
10049 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10050                                                    SelectionDAG &DAG) const {
10051   unsigned IntrinsicID =
10052     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10053 
10054   SDLoc dl(Op);
10055 
10056   if (IntrinsicID == Intrinsic::thread_pointer) {
10057     // Reads the thread pointer register, used for __builtin_thread_pointer.
10058     if (Subtarget.isPPC64())
10059       return DAG.getRegister(PPC::X13, MVT::i64);
10060     return DAG.getRegister(PPC::R2, MVT::i32);
10061   }
10062 
10063   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10064   // opcode number of the comparison.
10065   int CompareOpc;
10066   bool isDot;
10067   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10068     return SDValue();    // Don't custom lower most intrinsics.
10069 
10070   // If this is a non-dot comparison, make the VCMP node and we are done.
10071   if (!isDot) {
10072     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10073                               Op.getOperand(1), Op.getOperand(2),
10074                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10075     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10076   }
10077 
10078   // Create the PPCISD altivec 'dot' comparison node.
10079   SDValue Ops[] = {
10080     Op.getOperand(2),  // LHS
10081     Op.getOperand(3),  // RHS
10082     DAG.getConstant(CompareOpc, dl, MVT::i32)
10083   };
10084   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10085   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10086 
10087   // Now that we have the comparison, emit a copy from the CR to a GPR.
10088   // This is flagged to the above dot comparison.
10089   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10090                                 DAG.getRegister(PPC::CR6, MVT::i32),
10091                                 CompNode.getValue(1));
10092 
10093   // Unpack the result based on how the target uses it.
10094   unsigned BitNo;   // Bit # of CR6.
10095   bool InvertBit;   // Invert result?
10096   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10097   default:  // Can't happen, don't crash on invalid number though.
10098   case 0:   // Return the value of the EQ bit of CR6.
10099     BitNo = 0; InvertBit = false;
10100     break;
10101   case 1:   // Return the inverted value of the EQ bit of CR6.
10102     BitNo = 0; InvertBit = true;
10103     break;
10104   case 2:   // Return the value of the LT bit of CR6.
10105     BitNo = 2; InvertBit = false;
10106     break;
10107   case 3:   // Return the inverted value of the LT bit of CR6.
10108     BitNo = 2; InvertBit = true;
10109     break;
10110   }
10111 
10112   // Shift the bit into the low position.
10113   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10114                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10115   // Isolate the bit.
10116   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10117                       DAG.getConstant(1, dl, MVT::i32));
10118 
10119   // If we are supposed to, toggle the bit.
10120   if (InvertBit)
10121     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10122                         DAG.getConstant(1, dl, MVT::i32));
10123   return Flags;
10124 }
10125 
10126 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10127                                                SelectionDAG &DAG) const {
10128   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10129   // the beginning of the argument list.
10130   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10131   SDLoc DL(Op);
10132   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10133   case Intrinsic::ppc_cfence: {
10134     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10135     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10136     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10137                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10138                                                   Op.getOperand(ArgStart + 1)),
10139                                       Op.getOperand(0)),
10140                    0);
10141   }
10142   default:
10143     break;
10144   }
10145   return SDValue();
10146 }
10147 
10148 // Lower scalar BSWAP64 to xxbrd.
10149 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10150   SDLoc dl(Op);
10151   // MTVSRDD
10152   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10153                    Op.getOperand(0));
10154   // XXBRD
10155   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10156   // MFVSRD
10157   int VectorIndex = 0;
10158   if (Subtarget.isLittleEndian())
10159     VectorIndex = 1;
10160   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10161                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10162   return Op;
10163 }
10164 
10165 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10166 // compared to a value that is atomically loaded (atomic loads zero-extend).
10167 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10168                                                 SelectionDAG &DAG) const {
10169   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10170          "Expecting an atomic compare-and-swap here.");
10171   SDLoc dl(Op);
10172   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10173   EVT MemVT = AtomicNode->getMemoryVT();
10174   if (MemVT.getSizeInBits() >= 32)
10175     return Op;
10176 
10177   SDValue CmpOp = Op.getOperand(2);
10178   // If this is already correctly zero-extended, leave it alone.
10179   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10180   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10181     return Op;
10182 
10183   // Clear the high bits of the compare operand.
10184   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10185   SDValue NewCmpOp =
10186     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10187                 DAG.getConstant(MaskVal, dl, MVT::i32));
10188 
10189   // Replace the existing compare operand with the properly zero-extended one.
10190   SmallVector<SDValue, 4> Ops;
10191   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10192     Ops.push_back(AtomicNode->getOperand(i));
10193   Ops[2] = NewCmpOp;
10194   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10195   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10196   auto NodeTy =
10197     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10198   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10199 }
10200 
10201 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10202                                                  SelectionDAG &DAG) const {
10203   SDLoc dl(Op);
10204   // Create a stack slot that is 16-byte aligned.
10205   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10206   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10207   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10208   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10209 
10210   // Store the input value into Value#0 of the stack slot.
10211   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10212                                MachinePointerInfo());
10213   // Load it out.
10214   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10215 }
10216 
10217 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10218                                                   SelectionDAG &DAG) const {
10219   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10220          "Should only be called for ISD::INSERT_VECTOR_ELT");
10221 
10222   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10223   // We have legal lowering for constant indices but not for variable ones.
10224   if (!C)
10225     return SDValue();
10226 
10227   EVT VT = Op.getValueType();
10228   SDLoc dl(Op);
10229   SDValue V1 = Op.getOperand(0);
10230   SDValue V2 = Op.getOperand(1);
10231   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10232   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10233     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10234     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10235     unsigned InsertAtElement = C->getZExtValue();
10236     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10237     if (Subtarget.isLittleEndian()) {
10238       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10239     }
10240     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10241                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10242   }
10243   return Op;
10244 }
10245 
10246 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10247   SDLoc dl(Op);
10248   if (Op.getValueType() == MVT::v4i32) {
10249     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10250 
10251     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10252     // +16 as shift amt.
10253     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10254     SDValue RHSSwap =   // = vrlw RHS, 16
10255       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10256 
10257     // Shrinkify inputs to v8i16.
10258     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10259     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10260     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10261 
10262     // Low parts multiplied together, generating 32-bit results (we ignore the
10263     // top parts).
10264     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10265                                         LHS, RHS, DAG, dl, MVT::v4i32);
10266 
10267     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10268                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10269     // Shift the high parts up 16 bits.
10270     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10271                               Neg16, DAG, dl);
10272     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10273   } else if (Op.getValueType() == MVT::v16i8) {
10274     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10275     bool isLittleEndian = Subtarget.isLittleEndian();
10276 
10277     // Multiply the even 8-bit parts, producing 16-bit sums.
10278     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10279                                            LHS, RHS, DAG, dl, MVT::v8i16);
10280     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10281 
10282     // Multiply the odd 8-bit parts, producing 16-bit sums.
10283     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10284                                           LHS, RHS, DAG, dl, MVT::v8i16);
10285     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10286 
10287     // Merge the results together.  Because vmuleub and vmuloub are
10288     // instructions with a big-endian bias, we must reverse the
10289     // element numbering and reverse the meaning of "odd" and "even"
10290     // when generating little endian code.
10291     int Ops[16];
10292     for (unsigned i = 0; i != 8; ++i) {
10293       if (isLittleEndian) {
10294         Ops[i*2  ] = 2*i;
10295         Ops[i*2+1] = 2*i+16;
10296       } else {
10297         Ops[i*2  ] = 2*i+1;
10298         Ops[i*2+1] = 2*i+1+16;
10299       }
10300     }
10301     if (isLittleEndian)
10302       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10303     else
10304       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10305   } else {
10306     llvm_unreachable("Unknown mul to lower!");
10307   }
10308 }
10309 
10310 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10311 
10312   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10313 
10314   EVT VT = Op.getValueType();
10315   assert(VT.isVector() &&
10316          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10317   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10318           VT == MVT::v16i8) &&
10319          "Unexpected vector element type!");
10320   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10321          "Current subtarget doesn't support smax v2i64!");
10322 
10323   // For vector abs, it can be lowered to:
10324   // abs x
10325   // ==>
10326   // y = -x
10327   // smax(x, y)
10328 
10329   SDLoc dl(Op);
10330   SDValue X = Op.getOperand(0);
10331   SDValue Zero = DAG.getConstant(0, dl, VT);
10332   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10333 
10334   // SMAX patch https://reviews.llvm.org/D47332
10335   // hasn't landed yet, so use intrinsic first here.
10336   // TODO: Should use SMAX directly once SMAX patch landed
10337   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10338   if (VT == MVT::v2i64)
10339     BifID = Intrinsic::ppc_altivec_vmaxsd;
10340   else if (VT == MVT::v8i16)
10341     BifID = Intrinsic::ppc_altivec_vmaxsh;
10342   else if (VT == MVT::v16i8)
10343     BifID = Intrinsic::ppc_altivec_vmaxsb;
10344 
10345   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10346 }
10347 
10348 // Custom lowering for fpext vf32 to v2f64
10349 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10350 
10351   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10352          "Should only be called for ISD::FP_EXTEND");
10353 
10354   // FIXME: handle extends from half precision float vectors on P9.
10355   // We only want to custom lower an extend from v2f32 to v2f64.
10356   if (Op.getValueType() != MVT::v2f64 ||
10357       Op.getOperand(0).getValueType() != MVT::v2f32)
10358     return SDValue();
10359 
10360   SDLoc dl(Op);
10361   SDValue Op0 = Op.getOperand(0);
10362 
10363   switch (Op0.getOpcode()) {
10364   default:
10365     return SDValue();
10366   case ISD::EXTRACT_SUBVECTOR: {
10367     assert(Op0.getNumOperands() == 2 &&
10368            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10369            "Node should have 2 operands with second one being a constant!");
10370 
10371     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10372       return SDValue();
10373 
10374     // Custom lower is only done for high or low doubleword.
10375     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10376     if (Idx % 2 != 0)
10377       return SDValue();
10378 
10379     // Since input is v4f32, at this point Idx is either 0 or 2.
10380     // Shift to get the doubleword position we want.
10381     int DWord = Idx >> 1;
10382 
10383     // High and low word positions are different on little endian.
10384     if (Subtarget.isLittleEndian())
10385       DWord ^= 0x1;
10386 
10387     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10388                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10389   }
10390   case ISD::FADD:
10391   case ISD::FMUL:
10392   case ISD::FSUB: {
10393     SDValue NewLoad[2];
10394     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10395       // Ensure both input are loads.
10396       SDValue LdOp = Op0.getOperand(i);
10397       if (LdOp.getOpcode() != ISD::LOAD)
10398         return SDValue();
10399       // Generate new load node.
10400       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10401       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10402       NewLoad[i] = DAG.getMemIntrinsicNode(
10403           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10404           LD->getMemoryVT(), LD->getMemOperand());
10405     }
10406     SDValue NewOp =
10407         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10408                     NewLoad[1], Op0.getNode()->getFlags());
10409     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10410                        DAG.getConstant(0, dl, MVT::i32));
10411   }
10412   case ISD::LOAD: {
10413     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10414     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10415     SDValue NewLd = DAG.getMemIntrinsicNode(
10416         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10417         LD->getMemoryVT(), LD->getMemOperand());
10418     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10419                        DAG.getConstant(0, dl, MVT::i32));
10420   }
10421   }
10422   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10423 }
10424 
10425 /// LowerOperation - Provide custom lowering hooks for some operations.
10426 ///
10427 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10428   switch (Op.getOpcode()) {
10429   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10430   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10431   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10432   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10433   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10434   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10435   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10436   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10437   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10438 
10439   // Variable argument lowering.
10440   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10441   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10442   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10443 
10444   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10445   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10446   case ISD::GET_DYNAMIC_AREA_OFFSET:
10447     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10448 
10449   // Exception handling lowering.
10450   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10451   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10452   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10453 
10454   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10455   case ISD::STORE:              return LowerSTORE(Op, DAG);
10456   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10457   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10458   case ISD::FP_TO_UINT:
10459   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10460   case ISD::UINT_TO_FP:
10461   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10462   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10463 
10464   // Lower 64-bit shifts.
10465   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10466   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10467   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10468 
10469   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10470   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10471 
10472   // Vector-related lowering.
10473   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10474   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10475   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10476   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10477   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10478   case ISD::MUL:                return LowerMUL(Op, DAG);
10479   case ISD::ABS:                return LowerABS(Op, DAG);
10480   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10481   case ISD::ROTL:               return LowerROTL(Op, DAG);
10482 
10483   // For counter-based loop handling.
10484   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10485 
10486   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10487 
10488   // Frame & Return address.
10489   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10490   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10491 
10492   case ISD::INTRINSIC_VOID:
10493     return LowerINTRINSIC_VOID(Op, DAG);
10494   case ISD::BSWAP:
10495     return LowerBSWAP(Op, DAG);
10496   case ISD::ATOMIC_CMP_SWAP:
10497     return LowerATOMIC_CMP_SWAP(Op, DAG);
10498   }
10499 }
10500 
10501 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10502                                            SmallVectorImpl<SDValue>&Results,
10503                                            SelectionDAG &DAG) const {
10504   SDLoc dl(N);
10505   switch (N->getOpcode()) {
10506   default:
10507     llvm_unreachable("Do not know how to custom type legalize this operation!");
10508   case ISD::READCYCLECOUNTER: {
10509     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10510     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10511 
10512     Results.push_back(
10513         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10514     Results.push_back(RTB.getValue(2));
10515     break;
10516   }
10517   case ISD::INTRINSIC_W_CHAIN: {
10518     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10519         Intrinsic::loop_decrement)
10520       break;
10521 
10522     assert(N->getValueType(0) == MVT::i1 &&
10523            "Unexpected result type for CTR decrement intrinsic");
10524     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10525                                  N->getValueType(0));
10526     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10527     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10528                                  N->getOperand(1));
10529 
10530     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10531     Results.push_back(NewInt.getValue(1));
10532     break;
10533   }
10534   case ISD::VAARG: {
10535     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10536       return;
10537 
10538     EVT VT = N->getValueType(0);
10539 
10540     if (VT == MVT::i64) {
10541       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10542 
10543       Results.push_back(NewNode);
10544       Results.push_back(NewNode.getValue(1));
10545     }
10546     return;
10547   }
10548   case ISD::FP_TO_SINT:
10549   case ISD::FP_TO_UINT:
10550     // LowerFP_TO_INT() can only handle f32 and f64.
10551     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10552       return;
10553     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10554     return;
10555   case ISD::TRUNCATE: {
10556     EVT TrgVT = N->getValueType(0);
10557     EVT OpVT = N->getOperand(0).getValueType();
10558     if (TrgVT.isVector() &&
10559         isOperationCustom(N->getOpcode(), TrgVT) &&
10560         OpVT.getSizeInBits() <= 128 &&
10561         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10562       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10563     return;
10564   }
10565   case ISD::BITCAST:
10566     // Don't handle bitcast here.
10567     return;
10568   case ISD::FP_EXTEND:
10569     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10570     if (Lowered)
10571       Results.push_back(Lowered);
10572     return;
10573   }
10574 }
10575 
10576 //===----------------------------------------------------------------------===//
10577 //  Other Lowering Code
10578 //===----------------------------------------------------------------------===//
10579 
10580 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10581   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10582   Function *Func = Intrinsic::getDeclaration(M, Id);
10583   return Builder.CreateCall(Func, {});
10584 }
10585 
10586 // The mappings for emitLeading/TrailingFence is taken from
10587 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10588 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10589                                                  Instruction *Inst,
10590                                                  AtomicOrdering Ord) const {
10591   if (Ord == AtomicOrdering::SequentiallyConsistent)
10592     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10593   if (isReleaseOrStronger(Ord))
10594     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10595   return nullptr;
10596 }
10597 
10598 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10599                                                   Instruction *Inst,
10600                                                   AtomicOrdering Ord) const {
10601   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10602     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10603     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10604     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10605     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10606       return Builder.CreateCall(
10607           Intrinsic::getDeclaration(
10608               Builder.GetInsertBlock()->getParent()->getParent(),
10609               Intrinsic::ppc_cfence, {Inst->getType()}),
10610           {Inst});
10611     // FIXME: Can use isync for rmw operation.
10612     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10613   }
10614   return nullptr;
10615 }
10616 
10617 MachineBasicBlock *
10618 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10619                                     unsigned AtomicSize,
10620                                     unsigned BinOpcode,
10621                                     unsigned CmpOpcode,
10622                                     unsigned CmpPred) const {
10623   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10624   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10625 
10626   auto LoadMnemonic = PPC::LDARX;
10627   auto StoreMnemonic = PPC::STDCX;
10628   switch (AtomicSize) {
10629   default:
10630     llvm_unreachable("Unexpected size of atomic entity");
10631   case 1:
10632     LoadMnemonic = PPC::LBARX;
10633     StoreMnemonic = PPC::STBCX;
10634     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10635     break;
10636   case 2:
10637     LoadMnemonic = PPC::LHARX;
10638     StoreMnemonic = PPC::STHCX;
10639     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10640     break;
10641   case 4:
10642     LoadMnemonic = PPC::LWARX;
10643     StoreMnemonic = PPC::STWCX;
10644     break;
10645   case 8:
10646     LoadMnemonic = PPC::LDARX;
10647     StoreMnemonic = PPC::STDCX;
10648     break;
10649   }
10650 
10651   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10652   MachineFunction *F = BB->getParent();
10653   MachineFunction::iterator It = ++BB->getIterator();
10654 
10655   Register dest = MI.getOperand(0).getReg();
10656   Register ptrA = MI.getOperand(1).getReg();
10657   Register ptrB = MI.getOperand(2).getReg();
10658   Register incr = MI.getOperand(3).getReg();
10659   DebugLoc dl = MI.getDebugLoc();
10660 
10661   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10662   MachineBasicBlock *loop2MBB =
10663     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10664   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10665   F->insert(It, loopMBB);
10666   if (CmpOpcode)
10667     F->insert(It, loop2MBB);
10668   F->insert(It, exitMBB);
10669   exitMBB->splice(exitMBB->begin(), BB,
10670                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10671   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10672 
10673   MachineRegisterInfo &RegInfo = F->getRegInfo();
10674   Register TmpReg = (!BinOpcode) ? incr :
10675     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10676                                            : &PPC::GPRCRegClass);
10677 
10678   //  thisMBB:
10679   //   ...
10680   //   fallthrough --> loopMBB
10681   BB->addSuccessor(loopMBB);
10682 
10683   //  loopMBB:
10684   //   l[wd]arx dest, ptr
10685   //   add r0, dest, incr
10686   //   st[wd]cx. r0, ptr
10687   //   bne- loopMBB
10688   //   fallthrough --> exitMBB
10689 
10690   // For max/min...
10691   //  loopMBB:
10692   //   l[wd]arx dest, ptr
10693   //   cmpl?[wd] incr, dest
10694   //   bgt exitMBB
10695   //  loop2MBB:
10696   //   st[wd]cx. dest, ptr
10697   //   bne- loopMBB
10698   //   fallthrough --> exitMBB
10699 
10700   BB = loopMBB;
10701   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10702     .addReg(ptrA).addReg(ptrB);
10703   if (BinOpcode)
10704     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10705   if (CmpOpcode) {
10706     // Signed comparisons of byte or halfword values must be sign-extended.
10707     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10708       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10709       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10710               ExtReg).addReg(dest);
10711       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10712         .addReg(incr).addReg(ExtReg);
10713     } else
10714       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10715         .addReg(incr).addReg(dest);
10716 
10717     BuildMI(BB, dl, TII->get(PPC::BCC))
10718       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10719     BB->addSuccessor(loop2MBB);
10720     BB->addSuccessor(exitMBB);
10721     BB = loop2MBB;
10722   }
10723   BuildMI(BB, dl, TII->get(StoreMnemonic))
10724     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10725   BuildMI(BB, dl, TII->get(PPC::BCC))
10726     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10727   BB->addSuccessor(loopMBB);
10728   BB->addSuccessor(exitMBB);
10729 
10730   //  exitMBB:
10731   //   ...
10732   BB = exitMBB;
10733   return BB;
10734 }
10735 
10736 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10737     MachineInstr &MI, MachineBasicBlock *BB,
10738     bool is8bit, // operation
10739     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10740   // If we support part-word atomic mnemonics, just use them
10741   if (Subtarget.hasPartwordAtomics())
10742     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10743                             CmpPred);
10744 
10745   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10746   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10747   // In 64 bit mode we have to use 64 bits for addresses, even though the
10748   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10749   // registers without caring whether they're 32 or 64, but here we're
10750   // doing actual arithmetic on the addresses.
10751   bool is64bit = Subtarget.isPPC64();
10752   bool isLittleEndian = Subtarget.isLittleEndian();
10753   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10754 
10755   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10756   MachineFunction *F = BB->getParent();
10757   MachineFunction::iterator It = ++BB->getIterator();
10758 
10759   Register dest = MI.getOperand(0).getReg();
10760   Register ptrA = MI.getOperand(1).getReg();
10761   Register ptrB = MI.getOperand(2).getReg();
10762   Register incr = MI.getOperand(3).getReg();
10763   DebugLoc dl = MI.getDebugLoc();
10764 
10765   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10766   MachineBasicBlock *loop2MBB =
10767       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10768   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10769   F->insert(It, loopMBB);
10770   if (CmpOpcode)
10771     F->insert(It, loop2MBB);
10772   F->insert(It, exitMBB);
10773   exitMBB->splice(exitMBB->begin(), BB,
10774                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10775   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10776 
10777   MachineRegisterInfo &RegInfo = F->getRegInfo();
10778   const TargetRegisterClass *RC =
10779       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10780   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10781 
10782   Register PtrReg = RegInfo.createVirtualRegister(RC);
10783   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10784   Register ShiftReg =
10785       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10786   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10787   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10788   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10789   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10790   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10791   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10792   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10793   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10794   Register Ptr1Reg;
10795   Register TmpReg =
10796       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10797 
10798   //  thisMBB:
10799   //   ...
10800   //   fallthrough --> loopMBB
10801   BB->addSuccessor(loopMBB);
10802 
10803   // The 4-byte load must be aligned, while a char or short may be
10804   // anywhere in the word.  Hence all this nasty bookkeeping code.
10805   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10806   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10807   //   xori shift, shift1, 24 [16]
10808   //   rlwinm ptr, ptr1, 0, 0, 29
10809   //   slw incr2, incr, shift
10810   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10811   //   slw mask, mask2, shift
10812   //  loopMBB:
10813   //   lwarx tmpDest, ptr
10814   //   add tmp, tmpDest, incr2
10815   //   andc tmp2, tmpDest, mask
10816   //   and tmp3, tmp, mask
10817   //   or tmp4, tmp3, tmp2
10818   //   stwcx. tmp4, ptr
10819   //   bne- loopMBB
10820   //   fallthrough --> exitMBB
10821   //   srw dest, tmpDest, shift
10822   if (ptrA != ZeroReg) {
10823     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10824     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10825         .addReg(ptrA)
10826         .addReg(ptrB);
10827   } else {
10828     Ptr1Reg = ptrB;
10829   }
10830   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10831   // mode.
10832   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10833       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10834       .addImm(3)
10835       .addImm(27)
10836       .addImm(is8bit ? 28 : 27);
10837   if (!isLittleEndian)
10838     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10839         .addReg(Shift1Reg)
10840         .addImm(is8bit ? 24 : 16);
10841   if (is64bit)
10842     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10843         .addReg(Ptr1Reg)
10844         .addImm(0)
10845         .addImm(61);
10846   else
10847     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10848         .addReg(Ptr1Reg)
10849         .addImm(0)
10850         .addImm(0)
10851         .addImm(29);
10852   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10853   if (is8bit)
10854     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10855   else {
10856     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10857     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10858         .addReg(Mask3Reg)
10859         .addImm(65535);
10860   }
10861   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10862       .addReg(Mask2Reg)
10863       .addReg(ShiftReg);
10864 
10865   BB = loopMBB;
10866   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10867       .addReg(ZeroReg)
10868       .addReg(PtrReg);
10869   if (BinOpcode)
10870     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10871         .addReg(Incr2Reg)
10872         .addReg(TmpDestReg);
10873   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10874       .addReg(TmpDestReg)
10875       .addReg(MaskReg);
10876   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10877   if (CmpOpcode) {
10878     // For unsigned comparisons, we can directly compare the shifted values.
10879     // For signed comparisons we shift and sign extend.
10880     Register SReg = RegInfo.createVirtualRegister(GPRC);
10881     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10882         .addReg(TmpDestReg)
10883         .addReg(MaskReg);
10884     unsigned ValueReg = SReg;
10885     unsigned CmpReg = Incr2Reg;
10886     if (CmpOpcode == PPC::CMPW) {
10887       ValueReg = RegInfo.createVirtualRegister(GPRC);
10888       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10889           .addReg(SReg)
10890           .addReg(ShiftReg);
10891       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10892       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10893           .addReg(ValueReg);
10894       ValueReg = ValueSReg;
10895       CmpReg = incr;
10896     }
10897     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10898         .addReg(CmpReg)
10899         .addReg(ValueReg);
10900     BuildMI(BB, dl, TII->get(PPC::BCC))
10901         .addImm(CmpPred)
10902         .addReg(PPC::CR0)
10903         .addMBB(exitMBB);
10904     BB->addSuccessor(loop2MBB);
10905     BB->addSuccessor(exitMBB);
10906     BB = loop2MBB;
10907   }
10908   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10909   BuildMI(BB, dl, TII->get(PPC::STWCX))
10910       .addReg(Tmp4Reg)
10911       .addReg(ZeroReg)
10912       .addReg(PtrReg);
10913   BuildMI(BB, dl, TII->get(PPC::BCC))
10914       .addImm(PPC::PRED_NE)
10915       .addReg(PPC::CR0)
10916       .addMBB(loopMBB);
10917   BB->addSuccessor(loopMBB);
10918   BB->addSuccessor(exitMBB);
10919 
10920   //  exitMBB:
10921   //   ...
10922   BB = exitMBB;
10923   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10924       .addReg(TmpDestReg)
10925       .addReg(ShiftReg);
10926   return BB;
10927 }
10928 
10929 llvm::MachineBasicBlock *
10930 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10931                                     MachineBasicBlock *MBB) const {
10932   DebugLoc DL = MI.getDebugLoc();
10933   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10934   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10935 
10936   MachineFunction *MF = MBB->getParent();
10937   MachineRegisterInfo &MRI = MF->getRegInfo();
10938 
10939   const BasicBlock *BB = MBB->getBasicBlock();
10940   MachineFunction::iterator I = ++MBB->getIterator();
10941 
10942   Register DstReg = MI.getOperand(0).getReg();
10943   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10944   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10945   Register mainDstReg = MRI.createVirtualRegister(RC);
10946   Register restoreDstReg = MRI.createVirtualRegister(RC);
10947 
10948   MVT PVT = getPointerTy(MF->getDataLayout());
10949   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10950          "Invalid Pointer Size!");
10951   // For v = setjmp(buf), we generate
10952   //
10953   // thisMBB:
10954   //  SjLjSetup mainMBB
10955   //  bl mainMBB
10956   //  v_restore = 1
10957   //  b sinkMBB
10958   //
10959   // mainMBB:
10960   //  buf[LabelOffset] = LR
10961   //  v_main = 0
10962   //
10963   // sinkMBB:
10964   //  v = phi(main, restore)
10965   //
10966 
10967   MachineBasicBlock *thisMBB = MBB;
10968   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10969   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10970   MF->insert(I, mainMBB);
10971   MF->insert(I, sinkMBB);
10972 
10973   MachineInstrBuilder MIB;
10974 
10975   // Transfer the remainder of BB and its successor edges to sinkMBB.
10976   sinkMBB->splice(sinkMBB->begin(), MBB,
10977                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10978   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10979 
10980   // Note that the structure of the jmp_buf used here is not compatible
10981   // with that used by libc, and is not designed to be. Specifically, it
10982   // stores only those 'reserved' registers that LLVM does not otherwise
10983   // understand how to spill. Also, by convention, by the time this
10984   // intrinsic is called, Clang has already stored the frame address in the
10985   // first slot of the buffer and stack address in the third. Following the
10986   // X86 target code, we'll store the jump address in the second slot. We also
10987   // need to save the TOC pointer (R2) to handle jumps between shared
10988   // libraries, and that will be stored in the fourth slot. The thread
10989   // identifier (R13) is not affected.
10990 
10991   // thisMBB:
10992   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10993   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10994   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10995 
10996   // Prepare IP either in reg.
10997   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10998   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10999   Register BufReg = MI.getOperand(1).getReg();
11000 
11001   if (Subtarget.is64BitELFABI()) {
11002     setUsesTOCBasePtr(*MBB->getParent());
11003     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11004               .addReg(PPC::X2)
11005               .addImm(TOCOffset)
11006               .addReg(BufReg)
11007               .cloneMemRefs(MI);
11008   }
11009 
11010   // Naked functions never have a base pointer, and so we use r1. For all
11011   // other functions, this decision must be delayed until during PEI.
11012   unsigned BaseReg;
11013   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11014     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11015   else
11016     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11017 
11018   MIB = BuildMI(*thisMBB, MI, DL,
11019                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11020             .addReg(BaseReg)
11021             .addImm(BPOffset)
11022             .addReg(BufReg)
11023             .cloneMemRefs(MI);
11024 
11025   // Setup
11026   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11027   MIB.addRegMask(TRI->getNoPreservedMask());
11028 
11029   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11030 
11031   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11032           .addMBB(mainMBB);
11033   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11034 
11035   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11036   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11037 
11038   // mainMBB:
11039   //  mainDstReg = 0
11040   MIB =
11041       BuildMI(mainMBB, DL,
11042               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11043 
11044   // Store IP
11045   if (Subtarget.isPPC64()) {
11046     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11047             .addReg(LabelReg)
11048             .addImm(LabelOffset)
11049             .addReg(BufReg);
11050   } else {
11051     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11052             .addReg(LabelReg)
11053             .addImm(LabelOffset)
11054             .addReg(BufReg);
11055   }
11056   MIB.cloneMemRefs(MI);
11057 
11058   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11059   mainMBB->addSuccessor(sinkMBB);
11060 
11061   // sinkMBB:
11062   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11063           TII->get(PPC::PHI), DstReg)
11064     .addReg(mainDstReg).addMBB(mainMBB)
11065     .addReg(restoreDstReg).addMBB(thisMBB);
11066 
11067   MI.eraseFromParent();
11068   return sinkMBB;
11069 }
11070 
11071 MachineBasicBlock *
11072 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11073                                      MachineBasicBlock *MBB) const {
11074   DebugLoc DL = MI.getDebugLoc();
11075   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11076 
11077   MachineFunction *MF = MBB->getParent();
11078   MachineRegisterInfo &MRI = MF->getRegInfo();
11079 
11080   MVT PVT = getPointerTy(MF->getDataLayout());
11081   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11082          "Invalid Pointer Size!");
11083 
11084   const TargetRegisterClass *RC =
11085     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11086   Register Tmp = MRI.createVirtualRegister(RC);
11087   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11088   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11089   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11090   unsigned BP =
11091       (PVT == MVT::i64)
11092           ? PPC::X30
11093           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11094                                                               : PPC::R30);
11095 
11096   MachineInstrBuilder MIB;
11097 
11098   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11099   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11100   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11101   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11102 
11103   Register BufReg = MI.getOperand(0).getReg();
11104 
11105   // Reload FP (the jumped-to function may not have had a
11106   // frame pointer, and if so, then its r31 will be restored
11107   // as necessary).
11108   if (PVT == MVT::i64) {
11109     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11110             .addImm(0)
11111             .addReg(BufReg);
11112   } else {
11113     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11114             .addImm(0)
11115             .addReg(BufReg);
11116   }
11117   MIB.cloneMemRefs(MI);
11118 
11119   // Reload IP
11120   if (PVT == MVT::i64) {
11121     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11122             .addImm(LabelOffset)
11123             .addReg(BufReg);
11124   } else {
11125     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11126             .addImm(LabelOffset)
11127             .addReg(BufReg);
11128   }
11129   MIB.cloneMemRefs(MI);
11130 
11131   // Reload SP
11132   if (PVT == MVT::i64) {
11133     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11134             .addImm(SPOffset)
11135             .addReg(BufReg);
11136   } else {
11137     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11138             .addImm(SPOffset)
11139             .addReg(BufReg);
11140   }
11141   MIB.cloneMemRefs(MI);
11142 
11143   // Reload BP
11144   if (PVT == MVT::i64) {
11145     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11146             .addImm(BPOffset)
11147             .addReg(BufReg);
11148   } else {
11149     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11150             .addImm(BPOffset)
11151             .addReg(BufReg);
11152   }
11153   MIB.cloneMemRefs(MI);
11154 
11155   // Reload TOC
11156   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11157     setUsesTOCBasePtr(*MBB->getParent());
11158     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11159               .addImm(TOCOffset)
11160               .addReg(BufReg)
11161               .cloneMemRefs(MI);
11162   }
11163 
11164   // Jump
11165   BuildMI(*MBB, MI, DL,
11166           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11167   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11168 
11169   MI.eraseFromParent();
11170   return MBB;
11171 }
11172 
11173 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11174   // If the function specifically requests inline stack probes, emit them.
11175   if (MF.getFunction().hasFnAttribute("probe-stack"))
11176     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11177            "inline-asm";
11178   return false;
11179 }
11180 
11181 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11182   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11183   unsigned StackAlign = TFI->getStackAlignment();
11184   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11185          "Unexpected stack alignment");
11186   // The default stack probe size is 4096 if the function has no
11187   // stack-probe-size attribute.
11188   unsigned StackProbeSize = 4096;
11189   const Function &Fn = MF.getFunction();
11190   if (Fn.hasFnAttribute("stack-probe-size"))
11191     Fn.getFnAttribute("stack-probe-size")
11192         .getValueAsString()
11193         .getAsInteger(0, StackProbeSize);
11194   // Round down to the stack alignment.
11195   StackProbeSize &= ~(StackAlign - 1);
11196   return StackProbeSize ? StackProbeSize : StackAlign;
11197 }
11198 
11199 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11200 // into three phases. In the first phase, it uses pseudo instruction
11201 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11202 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11203 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11204 // MaxCallFrameSize so that it can calculate correct data area pointer.
11205 MachineBasicBlock *
11206 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11207                                     MachineBasicBlock *MBB) const {
11208   const bool isPPC64 = Subtarget.isPPC64();
11209   MachineFunction *MF = MBB->getParent();
11210   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11211   DebugLoc DL = MI.getDebugLoc();
11212   const unsigned ProbeSize = getStackProbeSize(*MF);
11213   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11214   MachineRegisterInfo &MRI = MF->getRegInfo();
11215   // The CFG of probing stack looks as
11216   //         +-----+
11217   //         | MBB |
11218   //         +--+--+
11219   //            |
11220   //       +----v----+
11221   //  +--->+ TestMBB +---+
11222   //  |    +----+----+   |
11223   //  |         |        |
11224   //  |   +-----v----+   |
11225   //  +---+ BlockMBB |   |
11226   //      +----------+   |
11227   //                     |
11228   //       +---------+   |
11229   //       | TailMBB +<--+
11230   //       +---------+
11231   // In MBB, calculate previous frame pointer and final stack pointer.
11232   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11233   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11234   // TailMBB is spliced via \p MI.
11235   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11236   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11237   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11238 
11239   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11240   MF->insert(MBBIter, TestMBB);
11241   MF->insert(MBBIter, BlockMBB);
11242   MF->insert(MBBIter, TailMBB);
11243 
11244   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11245   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11246 
11247   Register DstReg = MI.getOperand(0).getReg();
11248   Register NegSizeReg = MI.getOperand(1).getReg();
11249   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11250   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11251   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11252   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11253 
11254   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11255   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11256   // NegSize.
11257   unsigned ProbeOpc;
11258   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11259     ProbeOpc =
11260         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11261   else
11262     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11263     // and NegSizeReg will be allocated in the same phyreg to avoid
11264     // redundant copy when NegSizeReg has only one use which is current MI and
11265     // will be replaced by PREPARE_PROBED_ALLOCA then.
11266     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11267                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11268   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11269       .addDef(ActualNegSizeReg)
11270       .addReg(NegSizeReg)
11271       .add(MI.getOperand(2))
11272       .add(MI.getOperand(3));
11273 
11274   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11275   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11276           FinalStackPtr)
11277       .addReg(SPReg)
11278       .addReg(ActualNegSizeReg);
11279 
11280   // Materialize a scratch register for update.
11281   int64_t NegProbeSize = -(int64_t)ProbeSize;
11282   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11283   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11284   if (!isInt<16>(NegProbeSize)) {
11285     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11286     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11287         .addImm(NegProbeSize >> 16);
11288     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11289             ScratchReg)
11290         .addReg(TempReg)
11291         .addImm(NegProbeSize & 0xFFFF);
11292   } else
11293     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11294         .addImm(NegProbeSize);
11295 
11296   {
11297     // Probing leading residual part.
11298     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11299     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11300         .addReg(ActualNegSizeReg)
11301         .addReg(ScratchReg);
11302     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11303     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11304         .addReg(Div)
11305         .addReg(ScratchReg);
11306     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11307     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11308         .addReg(Mul)
11309         .addReg(ActualNegSizeReg);
11310     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11311         .addReg(FramePointer)
11312         .addReg(SPReg)
11313         .addReg(NegMod);
11314   }
11315 
11316   {
11317     // Remaining part should be multiple of ProbeSize.
11318     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11319     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11320         .addReg(SPReg)
11321         .addReg(FinalStackPtr);
11322     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11323         .addImm(PPC::PRED_EQ)
11324         .addReg(CmpResult)
11325         .addMBB(TailMBB);
11326     TestMBB->addSuccessor(BlockMBB);
11327     TestMBB->addSuccessor(TailMBB);
11328   }
11329 
11330   {
11331     // Touch the block.
11332     // |P...|P...|P...
11333     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11334         .addReg(FramePointer)
11335         .addReg(SPReg)
11336         .addReg(ScratchReg);
11337     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11338     BlockMBB->addSuccessor(TestMBB);
11339   }
11340 
11341   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11342   // DYNAREAOFFSET pseudo instruction to get the future result.
11343   Register MaxCallFrameSizeReg =
11344       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11345   BuildMI(TailMBB, DL,
11346           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11347           MaxCallFrameSizeReg)
11348       .add(MI.getOperand(2))
11349       .add(MI.getOperand(3));
11350   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11351       .addReg(SPReg)
11352       .addReg(MaxCallFrameSizeReg);
11353 
11354   // Splice instructions after MI to TailMBB.
11355   TailMBB->splice(TailMBB->end(), MBB,
11356                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11357   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11358   MBB->addSuccessor(TestMBB);
11359 
11360   // Delete the pseudo instruction.
11361   MI.eraseFromParent();
11362 
11363   ++NumDynamicAllocaProbed;
11364   return TailMBB;
11365 }
11366 
11367 MachineBasicBlock *
11368 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11369                                                MachineBasicBlock *BB) const {
11370   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11371       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11372     if (Subtarget.is64BitELFABI() &&
11373         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11374         !Subtarget.isUsingPCRelativeCalls()) {
11375       // Call lowering should have added an r2 operand to indicate a dependence
11376       // on the TOC base pointer value. It can't however, because there is no
11377       // way to mark the dependence as implicit there, and so the stackmap code
11378       // will confuse it with a regular operand. Instead, add the dependence
11379       // here.
11380       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11381     }
11382 
11383     return emitPatchPoint(MI, BB);
11384   }
11385 
11386   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11387       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11388     return emitEHSjLjSetJmp(MI, BB);
11389   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11390              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11391     return emitEHSjLjLongJmp(MI, BB);
11392   }
11393 
11394   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11395 
11396   // To "insert" these instructions we actually have to insert their
11397   // control-flow patterns.
11398   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11399   MachineFunction::iterator It = ++BB->getIterator();
11400 
11401   MachineFunction *F = BB->getParent();
11402 
11403   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11404       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11405       MI.getOpcode() == PPC::SELECT_I8) {
11406     SmallVector<MachineOperand, 2> Cond;
11407     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11408         MI.getOpcode() == PPC::SELECT_CC_I8)
11409       Cond.push_back(MI.getOperand(4));
11410     else
11411       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11412     Cond.push_back(MI.getOperand(1));
11413 
11414     DebugLoc dl = MI.getDebugLoc();
11415     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11416                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11417   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11418              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11419              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11420              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11421              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11422              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11423              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11424              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11425              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11426              MI.getOpcode() == PPC::SELECT_F4 ||
11427              MI.getOpcode() == PPC::SELECT_F8 ||
11428              MI.getOpcode() == PPC::SELECT_F16 ||
11429              MI.getOpcode() == PPC::SELECT_SPE ||
11430              MI.getOpcode() == PPC::SELECT_SPE4 ||
11431              MI.getOpcode() == PPC::SELECT_VRRC ||
11432              MI.getOpcode() == PPC::SELECT_VSFRC ||
11433              MI.getOpcode() == PPC::SELECT_VSSRC ||
11434              MI.getOpcode() == PPC::SELECT_VSRC) {
11435     // The incoming instruction knows the destination vreg to set, the
11436     // condition code register to branch on, the true/false values to
11437     // select between, and a branch opcode to use.
11438 
11439     //  thisMBB:
11440     //  ...
11441     //   TrueVal = ...
11442     //   cmpTY ccX, r1, r2
11443     //   bCC copy1MBB
11444     //   fallthrough --> copy0MBB
11445     MachineBasicBlock *thisMBB = BB;
11446     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11447     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11448     DebugLoc dl = MI.getDebugLoc();
11449     F->insert(It, copy0MBB);
11450     F->insert(It, sinkMBB);
11451 
11452     // Transfer the remainder of BB and its successor edges to sinkMBB.
11453     sinkMBB->splice(sinkMBB->begin(), BB,
11454                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11455     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11456 
11457     // Next, add the true and fallthrough blocks as its successors.
11458     BB->addSuccessor(copy0MBB);
11459     BB->addSuccessor(sinkMBB);
11460 
11461     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11462         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11463         MI.getOpcode() == PPC::SELECT_F16 ||
11464         MI.getOpcode() == PPC::SELECT_SPE4 ||
11465         MI.getOpcode() == PPC::SELECT_SPE ||
11466         MI.getOpcode() == PPC::SELECT_VRRC ||
11467         MI.getOpcode() == PPC::SELECT_VSFRC ||
11468         MI.getOpcode() == PPC::SELECT_VSSRC ||
11469         MI.getOpcode() == PPC::SELECT_VSRC) {
11470       BuildMI(BB, dl, TII->get(PPC::BC))
11471           .addReg(MI.getOperand(1).getReg())
11472           .addMBB(sinkMBB);
11473     } else {
11474       unsigned SelectPred = MI.getOperand(4).getImm();
11475       BuildMI(BB, dl, TII->get(PPC::BCC))
11476           .addImm(SelectPred)
11477           .addReg(MI.getOperand(1).getReg())
11478           .addMBB(sinkMBB);
11479     }
11480 
11481     //  copy0MBB:
11482     //   %FalseValue = ...
11483     //   # fallthrough to sinkMBB
11484     BB = copy0MBB;
11485 
11486     // Update machine-CFG edges
11487     BB->addSuccessor(sinkMBB);
11488 
11489     //  sinkMBB:
11490     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11491     //  ...
11492     BB = sinkMBB;
11493     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11494         .addReg(MI.getOperand(3).getReg())
11495         .addMBB(copy0MBB)
11496         .addReg(MI.getOperand(2).getReg())
11497         .addMBB(thisMBB);
11498   } else if (MI.getOpcode() == PPC::ReadTB) {
11499     // To read the 64-bit time-base register on a 32-bit target, we read the
11500     // two halves. Should the counter have wrapped while it was being read, we
11501     // need to try again.
11502     // ...
11503     // readLoop:
11504     // mfspr Rx,TBU # load from TBU
11505     // mfspr Ry,TB  # load from TB
11506     // mfspr Rz,TBU # load from TBU
11507     // cmpw crX,Rx,Rz # check if 'old'='new'
11508     // bne readLoop   # branch if they're not equal
11509     // ...
11510 
11511     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11512     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11513     DebugLoc dl = MI.getDebugLoc();
11514     F->insert(It, readMBB);
11515     F->insert(It, sinkMBB);
11516 
11517     // Transfer the remainder of BB and its successor edges to sinkMBB.
11518     sinkMBB->splice(sinkMBB->begin(), BB,
11519                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11520     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11521 
11522     BB->addSuccessor(readMBB);
11523     BB = readMBB;
11524 
11525     MachineRegisterInfo &RegInfo = F->getRegInfo();
11526     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11527     Register LoReg = MI.getOperand(0).getReg();
11528     Register HiReg = MI.getOperand(1).getReg();
11529 
11530     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11531     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11532     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11533 
11534     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11535 
11536     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11537         .addReg(HiReg)
11538         .addReg(ReadAgainReg);
11539     BuildMI(BB, dl, TII->get(PPC::BCC))
11540         .addImm(PPC::PRED_NE)
11541         .addReg(CmpReg)
11542         .addMBB(readMBB);
11543 
11544     BB->addSuccessor(readMBB);
11545     BB->addSuccessor(sinkMBB);
11546   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11547     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11548   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11549     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11550   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11551     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11552   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11553     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11554 
11555   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11556     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11557   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11558     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11559   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11560     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11561   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11562     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11563 
11564   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11565     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11566   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11567     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11568   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11569     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11570   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11571     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11572 
11573   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11574     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11575   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11576     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11577   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11578     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11579   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11580     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11581 
11582   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11583     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11584   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11585     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11586   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11587     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11588   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11589     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11590 
11591   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11592     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11593   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11594     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11595   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11596     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11597   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11598     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11599 
11600   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11601     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11602   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11603     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11604   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11605     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11606   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11607     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11608 
11609   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11610     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11611   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11612     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11613   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11614     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11615   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11616     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11617 
11618   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11619     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11620   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11621     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11622   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11623     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11624   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11625     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11626 
11627   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11628     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11629   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11630     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11631   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11632     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11633   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11634     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11635 
11636   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11637     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11638   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11639     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11640   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11641     BB = EmitAtomicBinary(MI, BB, 4, 0);
11642   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11643     BB = EmitAtomicBinary(MI, BB, 8, 0);
11644   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11645            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11646            (Subtarget.hasPartwordAtomics() &&
11647             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11648            (Subtarget.hasPartwordAtomics() &&
11649             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11650     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11651 
11652     auto LoadMnemonic = PPC::LDARX;
11653     auto StoreMnemonic = PPC::STDCX;
11654     switch (MI.getOpcode()) {
11655     default:
11656       llvm_unreachable("Compare and swap of unknown size");
11657     case PPC::ATOMIC_CMP_SWAP_I8:
11658       LoadMnemonic = PPC::LBARX;
11659       StoreMnemonic = PPC::STBCX;
11660       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11661       break;
11662     case PPC::ATOMIC_CMP_SWAP_I16:
11663       LoadMnemonic = PPC::LHARX;
11664       StoreMnemonic = PPC::STHCX;
11665       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11666       break;
11667     case PPC::ATOMIC_CMP_SWAP_I32:
11668       LoadMnemonic = PPC::LWARX;
11669       StoreMnemonic = PPC::STWCX;
11670       break;
11671     case PPC::ATOMIC_CMP_SWAP_I64:
11672       LoadMnemonic = PPC::LDARX;
11673       StoreMnemonic = PPC::STDCX;
11674       break;
11675     }
11676     Register dest = MI.getOperand(0).getReg();
11677     Register ptrA = MI.getOperand(1).getReg();
11678     Register ptrB = MI.getOperand(2).getReg();
11679     Register oldval = MI.getOperand(3).getReg();
11680     Register newval = MI.getOperand(4).getReg();
11681     DebugLoc dl = MI.getDebugLoc();
11682 
11683     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11684     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11685     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11686     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11687     F->insert(It, loop1MBB);
11688     F->insert(It, loop2MBB);
11689     F->insert(It, midMBB);
11690     F->insert(It, exitMBB);
11691     exitMBB->splice(exitMBB->begin(), BB,
11692                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11693     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11694 
11695     //  thisMBB:
11696     //   ...
11697     //   fallthrough --> loopMBB
11698     BB->addSuccessor(loop1MBB);
11699 
11700     // loop1MBB:
11701     //   l[bhwd]arx dest, ptr
11702     //   cmp[wd] dest, oldval
11703     //   bne- midMBB
11704     // loop2MBB:
11705     //   st[bhwd]cx. newval, ptr
11706     //   bne- loopMBB
11707     //   b exitBB
11708     // midMBB:
11709     //   st[bhwd]cx. dest, ptr
11710     // exitBB:
11711     BB = loop1MBB;
11712     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11713     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11714         .addReg(oldval)
11715         .addReg(dest);
11716     BuildMI(BB, dl, TII->get(PPC::BCC))
11717         .addImm(PPC::PRED_NE)
11718         .addReg(PPC::CR0)
11719         .addMBB(midMBB);
11720     BB->addSuccessor(loop2MBB);
11721     BB->addSuccessor(midMBB);
11722 
11723     BB = loop2MBB;
11724     BuildMI(BB, dl, TII->get(StoreMnemonic))
11725         .addReg(newval)
11726         .addReg(ptrA)
11727         .addReg(ptrB);
11728     BuildMI(BB, dl, TII->get(PPC::BCC))
11729         .addImm(PPC::PRED_NE)
11730         .addReg(PPC::CR0)
11731         .addMBB(loop1MBB);
11732     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11733     BB->addSuccessor(loop1MBB);
11734     BB->addSuccessor(exitMBB);
11735 
11736     BB = midMBB;
11737     BuildMI(BB, dl, TII->get(StoreMnemonic))
11738         .addReg(dest)
11739         .addReg(ptrA)
11740         .addReg(ptrB);
11741     BB->addSuccessor(exitMBB);
11742 
11743     //  exitMBB:
11744     //   ...
11745     BB = exitMBB;
11746   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11747              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11748     // We must use 64-bit registers for addresses when targeting 64-bit,
11749     // since we're actually doing arithmetic on them.  Other registers
11750     // can be 32-bit.
11751     bool is64bit = Subtarget.isPPC64();
11752     bool isLittleEndian = Subtarget.isLittleEndian();
11753     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11754 
11755     Register dest = MI.getOperand(0).getReg();
11756     Register ptrA = MI.getOperand(1).getReg();
11757     Register ptrB = MI.getOperand(2).getReg();
11758     Register oldval = MI.getOperand(3).getReg();
11759     Register newval = MI.getOperand(4).getReg();
11760     DebugLoc dl = MI.getDebugLoc();
11761 
11762     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11763     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11764     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11766     F->insert(It, loop1MBB);
11767     F->insert(It, loop2MBB);
11768     F->insert(It, midMBB);
11769     F->insert(It, exitMBB);
11770     exitMBB->splice(exitMBB->begin(), BB,
11771                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11772     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11773 
11774     MachineRegisterInfo &RegInfo = F->getRegInfo();
11775     const TargetRegisterClass *RC =
11776         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11777     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11778 
11779     Register PtrReg = RegInfo.createVirtualRegister(RC);
11780     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11781     Register ShiftReg =
11782         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11783     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11784     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11785     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11786     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11787     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11788     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11789     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11790     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11791     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11792     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11793     Register Ptr1Reg;
11794     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11795     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11796     //  thisMBB:
11797     //   ...
11798     //   fallthrough --> loopMBB
11799     BB->addSuccessor(loop1MBB);
11800 
11801     // The 4-byte load must be aligned, while a char or short may be
11802     // anywhere in the word.  Hence all this nasty bookkeeping code.
11803     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11804     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11805     //   xori shift, shift1, 24 [16]
11806     //   rlwinm ptr, ptr1, 0, 0, 29
11807     //   slw newval2, newval, shift
11808     //   slw oldval2, oldval,shift
11809     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11810     //   slw mask, mask2, shift
11811     //   and newval3, newval2, mask
11812     //   and oldval3, oldval2, mask
11813     // loop1MBB:
11814     //   lwarx tmpDest, ptr
11815     //   and tmp, tmpDest, mask
11816     //   cmpw tmp, oldval3
11817     //   bne- midMBB
11818     // loop2MBB:
11819     //   andc tmp2, tmpDest, mask
11820     //   or tmp4, tmp2, newval3
11821     //   stwcx. tmp4, ptr
11822     //   bne- loop1MBB
11823     //   b exitBB
11824     // midMBB:
11825     //   stwcx. tmpDest, ptr
11826     // exitBB:
11827     //   srw dest, tmpDest, shift
11828     if (ptrA != ZeroReg) {
11829       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11830       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11831           .addReg(ptrA)
11832           .addReg(ptrB);
11833     } else {
11834       Ptr1Reg = ptrB;
11835     }
11836 
11837     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11838     // mode.
11839     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11840         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11841         .addImm(3)
11842         .addImm(27)
11843         .addImm(is8bit ? 28 : 27);
11844     if (!isLittleEndian)
11845       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11846           .addReg(Shift1Reg)
11847           .addImm(is8bit ? 24 : 16);
11848     if (is64bit)
11849       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11850           .addReg(Ptr1Reg)
11851           .addImm(0)
11852           .addImm(61);
11853     else
11854       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11855           .addReg(Ptr1Reg)
11856           .addImm(0)
11857           .addImm(0)
11858           .addImm(29);
11859     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11860         .addReg(newval)
11861         .addReg(ShiftReg);
11862     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11863         .addReg(oldval)
11864         .addReg(ShiftReg);
11865     if (is8bit)
11866       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11867     else {
11868       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11869       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11870           .addReg(Mask3Reg)
11871           .addImm(65535);
11872     }
11873     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11874         .addReg(Mask2Reg)
11875         .addReg(ShiftReg);
11876     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11877         .addReg(NewVal2Reg)
11878         .addReg(MaskReg);
11879     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11880         .addReg(OldVal2Reg)
11881         .addReg(MaskReg);
11882 
11883     BB = loop1MBB;
11884     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11885         .addReg(ZeroReg)
11886         .addReg(PtrReg);
11887     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11888         .addReg(TmpDestReg)
11889         .addReg(MaskReg);
11890     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11891         .addReg(TmpReg)
11892         .addReg(OldVal3Reg);
11893     BuildMI(BB, dl, TII->get(PPC::BCC))
11894         .addImm(PPC::PRED_NE)
11895         .addReg(PPC::CR0)
11896         .addMBB(midMBB);
11897     BB->addSuccessor(loop2MBB);
11898     BB->addSuccessor(midMBB);
11899 
11900     BB = loop2MBB;
11901     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11902         .addReg(TmpDestReg)
11903         .addReg(MaskReg);
11904     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11905         .addReg(Tmp2Reg)
11906         .addReg(NewVal3Reg);
11907     BuildMI(BB, dl, TII->get(PPC::STWCX))
11908         .addReg(Tmp4Reg)
11909         .addReg(ZeroReg)
11910         .addReg(PtrReg);
11911     BuildMI(BB, dl, TII->get(PPC::BCC))
11912         .addImm(PPC::PRED_NE)
11913         .addReg(PPC::CR0)
11914         .addMBB(loop1MBB);
11915     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11916     BB->addSuccessor(loop1MBB);
11917     BB->addSuccessor(exitMBB);
11918 
11919     BB = midMBB;
11920     BuildMI(BB, dl, TII->get(PPC::STWCX))
11921         .addReg(TmpDestReg)
11922         .addReg(ZeroReg)
11923         .addReg(PtrReg);
11924     BB->addSuccessor(exitMBB);
11925 
11926     //  exitMBB:
11927     //   ...
11928     BB = exitMBB;
11929     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11930         .addReg(TmpReg)
11931         .addReg(ShiftReg);
11932   } else if (MI.getOpcode() == PPC::FADDrtz) {
11933     // This pseudo performs an FADD with rounding mode temporarily forced
11934     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11935     // is not modeled at the SelectionDAG level.
11936     Register Dest = MI.getOperand(0).getReg();
11937     Register Src1 = MI.getOperand(1).getReg();
11938     Register Src2 = MI.getOperand(2).getReg();
11939     DebugLoc dl = MI.getDebugLoc();
11940 
11941     MachineRegisterInfo &RegInfo = F->getRegInfo();
11942     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11943 
11944     // Save FPSCR value.
11945     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11946 
11947     // Set rounding mode to round-to-zero.
11948     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
11949         .addImm(31)
11950         .addReg(PPC::RM, RegState::ImplicitDefine);
11951 
11952     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
11953         .addImm(30)
11954         .addReg(PPC::RM, RegState::ImplicitDefine);
11955 
11956     // Perform addition.
11957     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11958 
11959     // Restore FPSCR value.
11960     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11961   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11962              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11963              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11964              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11965     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11966                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11967                           ? PPC::ANDI8_rec
11968                           : PPC::ANDI_rec;
11969     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11970                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11971 
11972     MachineRegisterInfo &RegInfo = F->getRegInfo();
11973     Register Dest = RegInfo.createVirtualRegister(
11974         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11975 
11976     DebugLoc Dl = MI.getDebugLoc();
11977     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11978         .addReg(MI.getOperand(1).getReg())
11979         .addImm(1);
11980     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11981             MI.getOperand(0).getReg())
11982         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11983   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11984     DebugLoc Dl = MI.getDebugLoc();
11985     MachineRegisterInfo &RegInfo = F->getRegInfo();
11986     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11987     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11988     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11989             MI.getOperand(0).getReg())
11990         .addReg(CRReg);
11991   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11992     DebugLoc Dl = MI.getDebugLoc();
11993     unsigned Imm = MI.getOperand(1).getImm();
11994     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11995     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11996             MI.getOperand(0).getReg())
11997         .addReg(PPC::CR0EQ);
11998   } else if (MI.getOpcode() == PPC::SETRNDi) {
11999     DebugLoc dl = MI.getDebugLoc();
12000     Register OldFPSCRReg = MI.getOperand(0).getReg();
12001 
12002     // Save FPSCR value.
12003     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12004 
12005     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12006     // the following settings:
12007     //   00 Round to nearest
12008     //   01 Round to 0
12009     //   10 Round to +inf
12010     //   11 Round to -inf
12011 
12012     // When the operand is immediate, using the two least significant bits of
12013     // the immediate to set the bits 62:63 of FPSCR.
12014     unsigned Mode = MI.getOperand(1).getImm();
12015     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12016         .addImm(31)
12017         .addReg(PPC::RM, RegState::ImplicitDefine);
12018 
12019     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12020         .addImm(30)
12021         .addReg(PPC::RM, RegState::ImplicitDefine);
12022   } else if (MI.getOpcode() == PPC::SETRND) {
12023     DebugLoc dl = MI.getDebugLoc();
12024 
12025     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12026     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12027     // If the target doesn't have DirectMove, we should use stack to do the
12028     // conversion, because the target doesn't have the instructions like mtvsrd
12029     // or mfvsrd to do this conversion directly.
12030     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12031       if (Subtarget.hasDirectMove()) {
12032         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12033           .addReg(SrcReg);
12034       } else {
12035         // Use stack to do the register copy.
12036         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12037         MachineRegisterInfo &RegInfo = F->getRegInfo();
12038         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12039         if (RC == &PPC::F8RCRegClass) {
12040           // Copy register from F8RCRegClass to G8RCRegclass.
12041           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12042                  "Unsupported RegClass.");
12043 
12044           StoreOp = PPC::STFD;
12045           LoadOp = PPC::LD;
12046         } else {
12047           // Copy register from G8RCRegClass to F8RCRegclass.
12048           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12049                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12050                  "Unsupported RegClass.");
12051         }
12052 
12053         MachineFrameInfo &MFI = F->getFrameInfo();
12054         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12055 
12056         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12057             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12058             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12059             MFI.getObjectAlign(FrameIdx));
12060 
12061         // Store the SrcReg into the stack.
12062         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12063           .addReg(SrcReg)
12064           .addImm(0)
12065           .addFrameIndex(FrameIdx)
12066           .addMemOperand(MMOStore);
12067 
12068         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12069             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12070             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12071             MFI.getObjectAlign(FrameIdx));
12072 
12073         // Load from the stack where SrcReg is stored, and save to DestReg,
12074         // so we have done the RegClass conversion from RegClass::SrcReg to
12075         // RegClass::DestReg.
12076         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12077           .addImm(0)
12078           .addFrameIndex(FrameIdx)
12079           .addMemOperand(MMOLoad);
12080       }
12081     };
12082 
12083     Register OldFPSCRReg = MI.getOperand(0).getReg();
12084 
12085     // Save FPSCR value.
12086     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12087 
12088     // When the operand is gprc register, use two least significant bits of the
12089     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12090     //
12091     // copy OldFPSCRTmpReg, OldFPSCRReg
12092     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12093     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12094     // copy NewFPSCRReg, NewFPSCRTmpReg
12095     // mtfsf 255, NewFPSCRReg
12096     MachineOperand SrcOp = MI.getOperand(1);
12097     MachineRegisterInfo &RegInfo = F->getRegInfo();
12098     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12099 
12100     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12101 
12102     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12103     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12104 
12105     // The first operand of INSERT_SUBREG should be a register which has
12106     // subregisters, we only care about its RegClass, so we should use an
12107     // IMPLICIT_DEF register.
12108     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12109     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12110       .addReg(ImDefReg)
12111       .add(SrcOp)
12112       .addImm(1);
12113 
12114     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12115     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12116       .addReg(OldFPSCRTmpReg)
12117       .addReg(ExtSrcReg)
12118       .addImm(0)
12119       .addImm(62);
12120 
12121     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12122     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12123 
12124     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12125     // bits of FPSCR.
12126     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12127       .addImm(255)
12128       .addReg(NewFPSCRReg)
12129       .addImm(0)
12130       .addImm(0);
12131   } else if (MI.getOpcode() == PPC::SETFLM) {
12132     DebugLoc Dl = MI.getDebugLoc();
12133 
12134     // Result of setflm is previous FPSCR content, so we need to save it first.
12135     Register OldFPSCRReg = MI.getOperand(0).getReg();
12136     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12137 
12138     // Put bits in 32:63 to FPSCR.
12139     Register NewFPSCRReg = MI.getOperand(1).getReg();
12140     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12141         .addImm(255)
12142         .addReg(NewFPSCRReg)
12143         .addImm(0)
12144         .addImm(0);
12145   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12146              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12147     return emitProbedAlloca(MI, BB);
12148   } else {
12149     llvm_unreachable("Unexpected instr type to insert");
12150   }
12151 
12152   MI.eraseFromParent(); // The pseudo instruction is gone now.
12153   return BB;
12154 }
12155 
12156 //===----------------------------------------------------------------------===//
12157 // Target Optimization Hooks
12158 //===----------------------------------------------------------------------===//
12159 
12160 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12161   // For the estimates, convergence is quadratic, so we essentially double the
12162   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12163   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12164   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12165   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12166   if (VT.getScalarType() == MVT::f64)
12167     RefinementSteps++;
12168   return RefinementSteps;
12169 }
12170 
12171 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12172                                            int Enabled, int &RefinementSteps,
12173                                            bool &UseOneConstNR,
12174                                            bool Reciprocal) const {
12175   EVT VT = Operand.getValueType();
12176   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12177       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12178       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12179       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12180     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12181       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12182 
12183     // The Newton-Raphson computation with a single constant does not provide
12184     // enough accuracy on some CPUs.
12185     UseOneConstNR = !Subtarget.needsTwoConstNR();
12186     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12187   }
12188   return SDValue();
12189 }
12190 
12191 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12192                                             int Enabled,
12193                                             int &RefinementSteps) const {
12194   EVT VT = Operand.getValueType();
12195   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12196       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12197       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12198       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12199     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12200       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12201     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12202   }
12203   return SDValue();
12204 }
12205 
12206 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12207   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12208   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12209   // enabled for division), this functionality is redundant with the default
12210   // combiner logic (once the division -> reciprocal/multiply transformation
12211   // has taken place). As a result, this matters more for older cores than for
12212   // newer ones.
12213 
12214   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12215   // reciprocal if there are two or more FDIVs (for embedded cores with only
12216   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12217   switch (Subtarget.getCPUDirective()) {
12218   default:
12219     return 3;
12220   case PPC::DIR_440:
12221   case PPC::DIR_A2:
12222   case PPC::DIR_E500:
12223   case PPC::DIR_E500mc:
12224   case PPC::DIR_E5500:
12225     return 2;
12226   }
12227 }
12228 
12229 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12230 // collapsed, and so we need to look through chains of them.
12231 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12232                                      int64_t& Offset, SelectionDAG &DAG) {
12233   if (DAG.isBaseWithConstantOffset(Loc)) {
12234     Base = Loc.getOperand(0);
12235     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12236 
12237     // The base might itself be a base plus an offset, and if so, accumulate
12238     // that as well.
12239     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12240   }
12241 }
12242 
12243 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12244                             unsigned Bytes, int Dist,
12245                             SelectionDAG &DAG) {
12246   if (VT.getSizeInBits() / 8 != Bytes)
12247     return false;
12248 
12249   SDValue BaseLoc = Base->getBasePtr();
12250   if (Loc.getOpcode() == ISD::FrameIndex) {
12251     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12252       return false;
12253     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12254     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12255     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12256     int FS  = MFI.getObjectSize(FI);
12257     int BFS = MFI.getObjectSize(BFI);
12258     if (FS != BFS || FS != (int)Bytes) return false;
12259     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12260   }
12261 
12262   SDValue Base1 = Loc, Base2 = BaseLoc;
12263   int64_t Offset1 = 0, Offset2 = 0;
12264   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12265   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12266   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12267     return true;
12268 
12269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12270   const GlobalValue *GV1 = nullptr;
12271   const GlobalValue *GV2 = nullptr;
12272   Offset1 = 0;
12273   Offset2 = 0;
12274   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12275   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12276   if (isGA1 && isGA2 && GV1 == GV2)
12277     return Offset1 == (Offset2 + Dist*Bytes);
12278   return false;
12279 }
12280 
12281 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12282 // not enforce equality of the chain operands.
12283 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12284                             unsigned Bytes, int Dist,
12285                             SelectionDAG &DAG) {
12286   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12287     EVT VT = LS->getMemoryVT();
12288     SDValue Loc = LS->getBasePtr();
12289     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12290   }
12291 
12292   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12293     EVT VT;
12294     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12295     default: return false;
12296     case Intrinsic::ppc_altivec_lvx:
12297     case Intrinsic::ppc_altivec_lvxl:
12298     case Intrinsic::ppc_vsx_lxvw4x:
12299     case Intrinsic::ppc_vsx_lxvw4x_be:
12300       VT = MVT::v4i32;
12301       break;
12302     case Intrinsic::ppc_vsx_lxvd2x:
12303     case Intrinsic::ppc_vsx_lxvd2x_be:
12304       VT = MVT::v2f64;
12305       break;
12306     case Intrinsic::ppc_altivec_lvebx:
12307       VT = MVT::i8;
12308       break;
12309     case Intrinsic::ppc_altivec_lvehx:
12310       VT = MVT::i16;
12311       break;
12312     case Intrinsic::ppc_altivec_lvewx:
12313       VT = MVT::i32;
12314       break;
12315     }
12316 
12317     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12318   }
12319 
12320   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12321     EVT VT;
12322     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12323     default: return false;
12324     case Intrinsic::ppc_altivec_stvx:
12325     case Intrinsic::ppc_altivec_stvxl:
12326     case Intrinsic::ppc_vsx_stxvw4x:
12327       VT = MVT::v4i32;
12328       break;
12329     case Intrinsic::ppc_vsx_stxvd2x:
12330       VT = MVT::v2f64;
12331       break;
12332     case Intrinsic::ppc_vsx_stxvw4x_be:
12333       VT = MVT::v4i32;
12334       break;
12335     case Intrinsic::ppc_vsx_stxvd2x_be:
12336       VT = MVT::v2f64;
12337       break;
12338     case Intrinsic::ppc_altivec_stvebx:
12339       VT = MVT::i8;
12340       break;
12341     case Intrinsic::ppc_altivec_stvehx:
12342       VT = MVT::i16;
12343       break;
12344     case Intrinsic::ppc_altivec_stvewx:
12345       VT = MVT::i32;
12346       break;
12347     }
12348 
12349     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12350   }
12351 
12352   return false;
12353 }
12354 
12355 // Return true is there is a nearyby consecutive load to the one provided
12356 // (regardless of alignment). We search up and down the chain, looking though
12357 // token factors and other loads (but nothing else). As a result, a true result
12358 // indicates that it is safe to create a new consecutive load adjacent to the
12359 // load provided.
12360 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12361   SDValue Chain = LD->getChain();
12362   EVT VT = LD->getMemoryVT();
12363 
12364   SmallSet<SDNode *, 16> LoadRoots;
12365   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12366   SmallSet<SDNode *, 16> Visited;
12367 
12368   // First, search up the chain, branching to follow all token-factor operands.
12369   // If we find a consecutive load, then we're done, otherwise, record all
12370   // nodes just above the top-level loads and token factors.
12371   while (!Queue.empty()) {
12372     SDNode *ChainNext = Queue.pop_back_val();
12373     if (!Visited.insert(ChainNext).second)
12374       continue;
12375 
12376     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12377       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12378         return true;
12379 
12380       if (!Visited.count(ChainLD->getChain().getNode()))
12381         Queue.push_back(ChainLD->getChain().getNode());
12382     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12383       for (const SDUse &O : ChainNext->ops())
12384         if (!Visited.count(O.getNode()))
12385           Queue.push_back(O.getNode());
12386     } else
12387       LoadRoots.insert(ChainNext);
12388   }
12389 
12390   // Second, search down the chain, starting from the top-level nodes recorded
12391   // in the first phase. These top-level nodes are the nodes just above all
12392   // loads and token factors. Starting with their uses, recursively look though
12393   // all loads (just the chain uses) and token factors to find a consecutive
12394   // load.
12395   Visited.clear();
12396   Queue.clear();
12397 
12398   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12399        IE = LoadRoots.end(); I != IE; ++I) {
12400     Queue.push_back(*I);
12401 
12402     while (!Queue.empty()) {
12403       SDNode *LoadRoot = Queue.pop_back_val();
12404       if (!Visited.insert(LoadRoot).second)
12405         continue;
12406 
12407       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12408         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12409           return true;
12410 
12411       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12412            UE = LoadRoot->use_end(); UI != UE; ++UI)
12413         if (((isa<MemSDNode>(*UI) &&
12414             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12415             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12416           Queue.push_back(*UI);
12417     }
12418   }
12419 
12420   return false;
12421 }
12422 
12423 /// This function is called when we have proved that a SETCC node can be replaced
12424 /// by subtraction (and other supporting instructions) so that the result of
12425 /// comparison is kept in a GPR instead of CR. This function is purely for
12426 /// codegen purposes and has some flags to guide the codegen process.
12427 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12428                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12429   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12430 
12431   // Zero extend the operands to the largest legal integer. Originally, they
12432   // must be of a strictly smaller size.
12433   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12434                          DAG.getConstant(Size, DL, MVT::i32));
12435   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12436                          DAG.getConstant(Size, DL, MVT::i32));
12437 
12438   // Swap if needed. Depends on the condition code.
12439   if (Swap)
12440     std::swap(Op0, Op1);
12441 
12442   // Subtract extended integers.
12443   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12444 
12445   // Move the sign bit to the least significant position and zero out the rest.
12446   // Now the least significant bit carries the result of original comparison.
12447   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12448                              DAG.getConstant(Size - 1, DL, MVT::i32));
12449   auto Final = Shifted;
12450 
12451   // Complement the result if needed. Based on the condition code.
12452   if (Complement)
12453     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12454                         DAG.getConstant(1, DL, MVT::i64));
12455 
12456   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12457 }
12458 
12459 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12460                                                   DAGCombinerInfo &DCI) const {
12461   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12462 
12463   SelectionDAG &DAG = DCI.DAG;
12464   SDLoc DL(N);
12465 
12466   // Size of integers being compared has a critical role in the following
12467   // analysis, so we prefer to do this when all types are legal.
12468   if (!DCI.isAfterLegalizeDAG())
12469     return SDValue();
12470 
12471   // If all users of SETCC extend its value to a legal integer type
12472   // then we replace SETCC with a subtraction
12473   for (SDNode::use_iterator UI = N->use_begin(),
12474        UE = N->use_end(); UI != UE; ++UI) {
12475     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12476       return SDValue();
12477   }
12478 
12479   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12480   auto OpSize = N->getOperand(0).getValueSizeInBits();
12481 
12482   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12483 
12484   if (OpSize < Size) {
12485     switch (CC) {
12486     default: break;
12487     case ISD::SETULT:
12488       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12489     case ISD::SETULE:
12490       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12491     case ISD::SETUGT:
12492       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12493     case ISD::SETUGE:
12494       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12495     }
12496   }
12497 
12498   return SDValue();
12499 }
12500 
12501 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12502                                                   DAGCombinerInfo &DCI) const {
12503   SelectionDAG &DAG = DCI.DAG;
12504   SDLoc dl(N);
12505 
12506   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12507   // If we're tracking CR bits, we need to be careful that we don't have:
12508   //   trunc(binary-ops(zext(x), zext(y)))
12509   // or
12510   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12511   // such that we're unnecessarily moving things into GPRs when it would be
12512   // better to keep them in CR bits.
12513 
12514   // Note that trunc here can be an actual i1 trunc, or can be the effective
12515   // truncation that comes from a setcc or select_cc.
12516   if (N->getOpcode() == ISD::TRUNCATE &&
12517       N->getValueType(0) != MVT::i1)
12518     return SDValue();
12519 
12520   if (N->getOperand(0).getValueType() != MVT::i32 &&
12521       N->getOperand(0).getValueType() != MVT::i64)
12522     return SDValue();
12523 
12524   if (N->getOpcode() == ISD::SETCC ||
12525       N->getOpcode() == ISD::SELECT_CC) {
12526     // If we're looking at a comparison, then we need to make sure that the
12527     // high bits (all except for the first) don't matter the result.
12528     ISD::CondCode CC =
12529       cast<CondCodeSDNode>(N->getOperand(
12530         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12531     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12532 
12533     if (ISD::isSignedIntSetCC(CC)) {
12534       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12535           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12536         return SDValue();
12537     } else if (ISD::isUnsignedIntSetCC(CC)) {
12538       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12539                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12540           !DAG.MaskedValueIsZero(N->getOperand(1),
12541                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12542         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12543                                              : SDValue());
12544     } else {
12545       // This is neither a signed nor an unsigned comparison, just make sure
12546       // that the high bits are equal.
12547       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12548       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12549 
12550       // We don't really care about what is known about the first bit (if
12551       // anything), so clear it in all masks prior to comparing them.
12552       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12553       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12554 
12555       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12556         return SDValue();
12557     }
12558   }
12559 
12560   // We now know that the higher-order bits are irrelevant, we just need to
12561   // make sure that all of the intermediate operations are bit operations, and
12562   // all inputs are extensions.
12563   if (N->getOperand(0).getOpcode() != ISD::AND &&
12564       N->getOperand(0).getOpcode() != ISD::OR  &&
12565       N->getOperand(0).getOpcode() != ISD::XOR &&
12566       N->getOperand(0).getOpcode() != ISD::SELECT &&
12567       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12568       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12569       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12570       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12571       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12572     return SDValue();
12573 
12574   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12575       N->getOperand(1).getOpcode() != ISD::AND &&
12576       N->getOperand(1).getOpcode() != ISD::OR  &&
12577       N->getOperand(1).getOpcode() != ISD::XOR &&
12578       N->getOperand(1).getOpcode() != ISD::SELECT &&
12579       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12580       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12581       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12582       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12583       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12584     return SDValue();
12585 
12586   SmallVector<SDValue, 4> Inputs;
12587   SmallVector<SDValue, 8> BinOps, PromOps;
12588   SmallPtrSet<SDNode *, 16> Visited;
12589 
12590   for (unsigned i = 0; i < 2; ++i) {
12591     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12592           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12593           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12594           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12595         isa<ConstantSDNode>(N->getOperand(i)))
12596       Inputs.push_back(N->getOperand(i));
12597     else
12598       BinOps.push_back(N->getOperand(i));
12599 
12600     if (N->getOpcode() == ISD::TRUNCATE)
12601       break;
12602   }
12603 
12604   // Visit all inputs, collect all binary operations (and, or, xor and
12605   // select) that are all fed by extensions.
12606   while (!BinOps.empty()) {
12607     SDValue BinOp = BinOps.back();
12608     BinOps.pop_back();
12609 
12610     if (!Visited.insert(BinOp.getNode()).second)
12611       continue;
12612 
12613     PromOps.push_back(BinOp);
12614 
12615     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12616       // The condition of the select is not promoted.
12617       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12618         continue;
12619       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12620         continue;
12621 
12622       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12623             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12624             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12625            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12626           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12627         Inputs.push_back(BinOp.getOperand(i));
12628       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12629                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12630                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12631                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12632                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12633                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12634                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12635                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12636                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12637         BinOps.push_back(BinOp.getOperand(i));
12638       } else {
12639         // We have an input that is not an extension or another binary
12640         // operation; we'll abort this transformation.
12641         return SDValue();
12642       }
12643     }
12644   }
12645 
12646   // Make sure that this is a self-contained cluster of operations (which
12647   // is not quite the same thing as saying that everything has only one
12648   // use).
12649   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12650     if (isa<ConstantSDNode>(Inputs[i]))
12651       continue;
12652 
12653     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12654                               UE = Inputs[i].getNode()->use_end();
12655          UI != UE; ++UI) {
12656       SDNode *User = *UI;
12657       if (User != N && !Visited.count(User))
12658         return SDValue();
12659 
12660       // Make sure that we're not going to promote the non-output-value
12661       // operand(s) or SELECT or SELECT_CC.
12662       // FIXME: Although we could sometimes handle this, and it does occur in
12663       // practice that one of the condition inputs to the select is also one of
12664       // the outputs, we currently can't deal with this.
12665       if (User->getOpcode() == ISD::SELECT) {
12666         if (User->getOperand(0) == Inputs[i])
12667           return SDValue();
12668       } else if (User->getOpcode() == ISD::SELECT_CC) {
12669         if (User->getOperand(0) == Inputs[i] ||
12670             User->getOperand(1) == Inputs[i])
12671           return SDValue();
12672       }
12673     }
12674   }
12675 
12676   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12677     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12678                               UE = PromOps[i].getNode()->use_end();
12679          UI != UE; ++UI) {
12680       SDNode *User = *UI;
12681       if (User != N && !Visited.count(User))
12682         return SDValue();
12683 
12684       // Make sure that we're not going to promote the non-output-value
12685       // operand(s) or SELECT or SELECT_CC.
12686       // FIXME: Although we could sometimes handle this, and it does occur in
12687       // practice that one of the condition inputs to the select is also one of
12688       // the outputs, we currently can't deal with this.
12689       if (User->getOpcode() == ISD::SELECT) {
12690         if (User->getOperand(0) == PromOps[i])
12691           return SDValue();
12692       } else if (User->getOpcode() == ISD::SELECT_CC) {
12693         if (User->getOperand(0) == PromOps[i] ||
12694             User->getOperand(1) == PromOps[i])
12695           return SDValue();
12696       }
12697     }
12698   }
12699 
12700   // Replace all inputs with the extension operand.
12701   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12702     // Constants may have users outside the cluster of to-be-promoted nodes,
12703     // and so we need to replace those as we do the promotions.
12704     if (isa<ConstantSDNode>(Inputs[i]))
12705       continue;
12706     else
12707       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12708   }
12709 
12710   std::list<HandleSDNode> PromOpHandles;
12711   for (auto &PromOp : PromOps)
12712     PromOpHandles.emplace_back(PromOp);
12713 
12714   // Replace all operations (these are all the same, but have a different
12715   // (i1) return type). DAG.getNode will validate that the types of
12716   // a binary operator match, so go through the list in reverse so that
12717   // we've likely promoted both operands first. Any intermediate truncations or
12718   // extensions disappear.
12719   while (!PromOpHandles.empty()) {
12720     SDValue PromOp = PromOpHandles.back().getValue();
12721     PromOpHandles.pop_back();
12722 
12723     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12724         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12725         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12726         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12727       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12728           PromOp.getOperand(0).getValueType() != MVT::i1) {
12729         // The operand is not yet ready (see comment below).
12730         PromOpHandles.emplace_front(PromOp);
12731         continue;
12732       }
12733 
12734       SDValue RepValue = PromOp.getOperand(0);
12735       if (isa<ConstantSDNode>(RepValue))
12736         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12737 
12738       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12739       continue;
12740     }
12741 
12742     unsigned C;
12743     switch (PromOp.getOpcode()) {
12744     default:             C = 0; break;
12745     case ISD::SELECT:    C = 1; break;
12746     case ISD::SELECT_CC: C = 2; break;
12747     }
12748 
12749     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12750          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12751         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12752          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12753       // The to-be-promoted operands of this node have not yet been
12754       // promoted (this should be rare because we're going through the
12755       // list backward, but if one of the operands has several users in
12756       // this cluster of to-be-promoted nodes, it is possible).
12757       PromOpHandles.emplace_front(PromOp);
12758       continue;
12759     }
12760 
12761     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12762                                 PromOp.getNode()->op_end());
12763 
12764     // If there are any constant inputs, make sure they're replaced now.
12765     for (unsigned i = 0; i < 2; ++i)
12766       if (isa<ConstantSDNode>(Ops[C+i]))
12767         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12768 
12769     DAG.ReplaceAllUsesOfValueWith(PromOp,
12770       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12771   }
12772 
12773   // Now we're left with the initial truncation itself.
12774   if (N->getOpcode() == ISD::TRUNCATE)
12775     return N->getOperand(0);
12776 
12777   // Otherwise, this is a comparison. The operands to be compared have just
12778   // changed type (to i1), but everything else is the same.
12779   return SDValue(N, 0);
12780 }
12781 
12782 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12783                                                   DAGCombinerInfo &DCI) const {
12784   SelectionDAG &DAG = DCI.DAG;
12785   SDLoc dl(N);
12786 
12787   // If we're tracking CR bits, we need to be careful that we don't have:
12788   //   zext(binary-ops(trunc(x), trunc(y)))
12789   // or
12790   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12791   // such that we're unnecessarily moving things into CR bits that can more
12792   // efficiently stay in GPRs. Note that if we're not certain that the high
12793   // bits are set as required by the final extension, we still may need to do
12794   // some masking to get the proper behavior.
12795 
12796   // This same functionality is important on PPC64 when dealing with
12797   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12798   // the return values of functions. Because it is so similar, it is handled
12799   // here as well.
12800 
12801   if (N->getValueType(0) != MVT::i32 &&
12802       N->getValueType(0) != MVT::i64)
12803     return SDValue();
12804 
12805   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12806         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12807     return SDValue();
12808 
12809   if (N->getOperand(0).getOpcode() != ISD::AND &&
12810       N->getOperand(0).getOpcode() != ISD::OR  &&
12811       N->getOperand(0).getOpcode() != ISD::XOR &&
12812       N->getOperand(0).getOpcode() != ISD::SELECT &&
12813       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12814     return SDValue();
12815 
12816   SmallVector<SDValue, 4> Inputs;
12817   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12818   SmallPtrSet<SDNode *, 16> Visited;
12819 
12820   // Visit all inputs, collect all binary operations (and, or, xor and
12821   // select) that are all fed by truncations.
12822   while (!BinOps.empty()) {
12823     SDValue BinOp = BinOps.back();
12824     BinOps.pop_back();
12825 
12826     if (!Visited.insert(BinOp.getNode()).second)
12827       continue;
12828 
12829     PromOps.push_back(BinOp);
12830 
12831     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12832       // The condition of the select is not promoted.
12833       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12834         continue;
12835       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12836         continue;
12837 
12838       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12839           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12840         Inputs.push_back(BinOp.getOperand(i));
12841       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12842                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12843                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12844                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12845                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12846         BinOps.push_back(BinOp.getOperand(i));
12847       } else {
12848         // We have an input that is not a truncation or another binary
12849         // operation; we'll abort this transformation.
12850         return SDValue();
12851       }
12852     }
12853   }
12854 
12855   // The operands of a select that must be truncated when the select is
12856   // promoted because the operand is actually part of the to-be-promoted set.
12857   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12858 
12859   // Make sure that this is a self-contained cluster of operations (which
12860   // is not quite the same thing as saying that everything has only one
12861   // use).
12862   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12863     if (isa<ConstantSDNode>(Inputs[i]))
12864       continue;
12865 
12866     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12867                               UE = Inputs[i].getNode()->use_end();
12868          UI != UE; ++UI) {
12869       SDNode *User = *UI;
12870       if (User != N && !Visited.count(User))
12871         return SDValue();
12872 
12873       // If we're going to promote the non-output-value operand(s) or SELECT or
12874       // SELECT_CC, record them for truncation.
12875       if (User->getOpcode() == ISD::SELECT) {
12876         if (User->getOperand(0) == Inputs[i])
12877           SelectTruncOp[0].insert(std::make_pair(User,
12878                                     User->getOperand(0).getValueType()));
12879       } else if (User->getOpcode() == ISD::SELECT_CC) {
12880         if (User->getOperand(0) == Inputs[i])
12881           SelectTruncOp[0].insert(std::make_pair(User,
12882                                     User->getOperand(0).getValueType()));
12883         if (User->getOperand(1) == Inputs[i])
12884           SelectTruncOp[1].insert(std::make_pair(User,
12885                                     User->getOperand(1).getValueType()));
12886       }
12887     }
12888   }
12889 
12890   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12891     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12892                               UE = PromOps[i].getNode()->use_end();
12893          UI != UE; ++UI) {
12894       SDNode *User = *UI;
12895       if (User != N && !Visited.count(User))
12896         return SDValue();
12897 
12898       // If we're going to promote the non-output-value operand(s) or SELECT or
12899       // SELECT_CC, record them for truncation.
12900       if (User->getOpcode() == ISD::SELECT) {
12901         if (User->getOperand(0) == PromOps[i])
12902           SelectTruncOp[0].insert(std::make_pair(User,
12903                                     User->getOperand(0).getValueType()));
12904       } else if (User->getOpcode() == ISD::SELECT_CC) {
12905         if (User->getOperand(0) == PromOps[i])
12906           SelectTruncOp[0].insert(std::make_pair(User,
12907                                     User->getOperand(0).getValueType()));
12908         if (User->getOperand(1) == PromOps[i])
12909           SelectTruncOp[1].insert(std::make_pair(User,
12910                                     User->getOperand(1).getValueType()));
12911       }
12912     }
12913   }
12914 
12915   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12916   bool ReallyNeedsExt = false;
12917   if (N->getOpcode() != ISD::ANY_EXTEND) {
12918     // If all of the inputs are not already sign/zero extended, then
12919     // we'll still need to do that at the end.
12920     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12921       if (isa<ConstantSDNode>(Inputs[i]))
12922         continue;
12923 
12924       unsigned OpBits =
12925         Inputs[i].getOperand(0).getValueSizeInBits();
12926       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12927 
12928       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12929            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12930                                   APInt::getHighBitsSet(OpBits,
12931                                                         OpBits-PromBits))) ||
12932           (N->getOpcode() == ISD::SIGN_EXTEND &&
12933            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12934              (OpBits-(PromBits-1)))) {
12935         ReallyNeedsExt = true;
12936         break;
12937       }
12938     }
12939   }
12940 
12941   // Replace all inputs, either with the truncation operand, or a
12942   // truncation or extension to the final output type.
12943   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12944     // Constant inputs need to be replaced with the to-be-promoted nodes that
12945     // use them because they might have users outside of the cluster of
12946     // promoted nodes.
12947     if (isa<ConstantSDNode>(Inputs[i]))
12948       continue;
12949 
12950     SDValue InSrc = Inputs[i].getOperand(0);
12951     if (Inputs[i].getValueType() == N->getValueType(0))
12952       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12953     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12954       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12955         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12956     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12957       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12958         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12959     else
12960       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12961         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12962   }
12963 
12964   std::list<HandleSDNode> PromOpHandles;
12965   for (auto &PromOp : PromOps)
12966     PromOpHandles.emplace_back(PromOp);
12967 
12968   // Replace all operations (these are all the same, but have a different
12969   // (promoted) return type). DAG.getNode will validate that the types of
12970   // a binary operator match, so go through the list in reverse so that
12971   // we've likely promoted both operands first.
12972   while (!PromOpHandles.empty()) {
12973     SDValue PromOp = PromOpHandles.back().getValue();
12974     PromOpHandles.pop_back();
12975 
12976     unsigned C;
12977     switch (PromOp.getOpcode()) {
12978     default:             C = 0; break;
12979     case ISD::SELECT:    C = 1; break;
12980     case ISD::SELECT_CC: C = 2; break;
12981     }
12982 
12983     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12984          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12985         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12986          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12987       // The to-be-promoted operands of this node have not yet been
12988       // promoted (this should be rare because we're going through the
12989       // list backward, but if one of the operands has several users in
12990       // this cluster of to-be-promoted nodes, it is possible).
12991       PromOpHandles.emplace_front(PromOp);
12992       continue;
12993     }
12994 
12995     // For SELECT and SELECT_CC nodes, we do a similar check for any
12996     // to-be-promoted comparison inputs.
12997     if (PromOp.getOpcode() == ISD::SELECT ||
12998         PromOp.getOpcode() == ISD::SELECT_CC) {
12999       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13000            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13001           (SelectTruncOp[1].count(PromOp.getNode()) &&
13002            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13003         PromOpHandles.emplace_front(PromOp);
13004         continue;
13005       }
13006     }
13007 
13008     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13009                                 PromOp.getNode()->op_end());
13010 
13011     // If this node has constant inputs, then they'll need to be promoted here.
13012     for (unsigned i = 0; i < 2; ++i) {
13013       if (!isa<ConstantSDNode>(Ops[C+i]))
13014         continue;
13015       if (Ops[C+i].getValueType() == N->getValueType(0))
13016         continue;
13017 
13018       if (N->getOpcode() == ISD::SIGN_EXTEND)
13019         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13020       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13021         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13022       else
13023         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13024     }
13025 
13026     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13027     // truncate them again to the original value type.
13028     if (PromOp.getOpcode() == ISD::SELECT ||
13029         PromOp.getOpcode() == ISD::SELECT_CC) {
13030       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13031       if (SI0 != SelectTruncOp[0].end())
13032         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13033       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13034       if (SI1 != SelectTruncOp[1].end())
13035         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13036     }
13037 
13038     DAG.ReplaceAllUsesOfValueWith(PromOp,
13039       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13040   }
13041 
13042   // Now we're left with the initial extension itself.
13043   if (!ReallyNeedsExt)
13044     return N->getOperand(0);
13045 
13046   // To zero extend, just mask off everything except for the first bit (in the
13047   // i1 case).
13048   if (N->getOpcode() == ISD::ZERO_EXTEND)
13049     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13050                        DAG.getConstant(APInt::getLowBitsSet(
13051                                          N->getValueSizeInBits(0), PromBits),
13052                                        dl, N->getValueType(0)));
13053 
13054   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13055          "Invalid extension type");
13056   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13057   SDValue ShiftCst =
13058       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13059   return DAG.getNode(
13060       ISD::SRA, dl, N->getValueType(0),
13061       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13062       ShiftCst);
13063 }
13064 
13065 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13066                                         DAGCombinerInfo &DCI) const {
13067   assert(N->getOpcode() == ISD::SETCC &&
13068          "Should be called with a SETCC node");
13069 
13070   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13071   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13072     SDValue LHS = N->getOperand(0);
13073     SDValue RHS = N->getOperand(1);
13074 
13075     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13076     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13077         LHS.hasOneUse())
13078       std::swap(LHS, RHS);
13079 
13080     // x == 0-y --> x+y == 0
13081     // x != 0-y --> x+y != 0
13082     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13083         RHS.hasOneUse()) {
13084       SDLoc DL(N);
13085       SelectionDAG &DAG = DCI.DAG;
13086       EVT VT = N->getValueType(0);
13087       EVT OpVT = LHS.getValueType();
13088       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13089       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13090     }
13091   }
13092 
13093   return DAGCombineTruncBoolExt(N, DCI);
13094 }
13095 
13096 // Is this an extending load from an f32 to an f64?
13097 static bool isFPExtLoad(SDValue Op) {
13098   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13099     return LD->getExtensionType() == ISD::EXTLOAD &&
13100       Op.getValueType() == MVT::f64;
13101   return false;
13102 }
13103 
13104 /// Reduces the number of fp-to-int conversion when building a vector.
13105 ///
13106 /// If this vector is built out of floating to integer conversions,
13107 /// transform it to a vector built out of floating point values followed by a
13108 /// single floating to integer conversion of the vector.
13109 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13110 /// becomes (fptosi (build_vector ($A, $B, ...)))
13111 SDValue PPCTargetLowering::
13112 combineElementTruncationToVectorTruncation(SDNode *N,
13113                                            DAGCombinerInfo &DCI) const {
13114   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13115          "Should be called with a BUILD_VECTOR node");
13116 
13117   SelectionDAG &DAG = DCI.DAG;
13118   SDLoc dl(N);
13119 
13120   SDValue FirstInput = N->getOperand(0);
13121   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13122          "The input operand must be an fp-to-int conversion.");
13123 
13124   // This combine happens after legalization so the fp_to_[su]i nodes are
13125   // already converted to PPCSISD nodes.
13126   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13127   if (FirstConversion == PPCISD::FCTIDZ ||
13128       FirstConversion == PPCISD::FCTIDUZ ||
13129       FirstConversion == PPCISD::FCTIWZ ||
13130       FirstConversion == PPCISD::FCTIWUZ) {
13131     bool IsSplat = true;
13132     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13133       FirstConversion == PPCISD::FCTIWUZ;
13134     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13135     SmallVector<SDValue, 4> Ops;
13136     EVT TargetVT = N->getValueType(0);
13137     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13138       SDValue NextOp = N->getOperand(i);
13139       if (NextOp.getOpcode() != PPCISD::MFVSR)
13140         return SDValue();
13141       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13142       if (NextConversion != FirstConversion)
13143         return SDValue();
13144       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13145       // This is not valid if the input was originally double precision. It is
13146       // also not profitable to do unless this is an extending load in which
13147       // case doing this combine will allow us to combine consecutive loads.
13148       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13149         return SDValue();
13150       if (N->getOperand(i) != FirstInput)
13151         IsSplat = false;
13152     }
13153 
13154     // If this is a splat, we leave it as-is since there will be only a single
13155     // fp-to-int conversion followed by a splat of the integer. This is better
13156     // for 32-bit and smaller ints and neutral for 64-bit ints.
13157     if (IsSplat)
13158       return SDValue();
13159 
13160     // Now that we know we have the right type of node, get its operands
13161     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13162       SDValue In = N->getOperand(i).getOperand(0);
13163       if (Is32Bit) {
13164         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13165         // here, we know that all inputs are extending loads so this is safe).
13166         if (In.isUndef())
13167           Ops.push_back(DAG.getUNDEF(SrcVT));
13168         else {
13169           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13170                                       MVT::f32, In.getOperand(0),
13171                                       DAG.getIntPtrConstant(1, dl));
13172           Ops.push_back(Trunc);
13173         }
13174       } else
13175         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13176     }
13177 
13178     unsigned Opcode;
13179     if (FirstConversion == PPCISD::FCTIDZ ||
13180         FirstConversion == PPCISD::FCTIWZ)
13181       Opcode = ISD::FP_TO_SINT;
13182     else
13183       Opcode = ISD::FP_TO_UINT;
13184 
13185     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13186     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13187     return DAG.getNode(Opcode, dl, TargetVT, BV);
13188   }
13189   return SDValue();
13190 }
13191 
13192 /// Reduce the number of loads when building a vector.
13193 ///
13194 /// Building a vector out of multiple loads can be converted to a load
13195 /// of the vector type if the loads are consecutive. If the loads are
13196 /// consecutive but in descending order, a shuffle is added at the end
13197 /// to reorder the vector.
13198 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13199   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13200          "Should be called with a BUILD_VECTOR node");
13201 
13202   SDLoc dl(N);
13203 
13204   // Return early for non byte-sized type, as they can't be consecutive.
13205   if (!N->getValueType(0).getVectorElementType().isByteSized())
13206     return SDValue();
13207 
13208   bool InputsAreConsecutiveLoads = true;
13209   bool InputsAreReverseConsecutive = true;
13210   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13211   SDValue FirstInput = N->getOperand(0);
13212   bool IsRoundOfExtLoad = false;
13213 
13214   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13215       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13216     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13217     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13218   }
13219   // Not a build vector of (possibly fp_rounded) loads.
13220   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13221       N->getNumOperands() == 1)
13222     return SDValue();
13223 
13224   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13225     // If any inputs are fp_round(extload), they all must be.
13226     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13227       return SDValue();
13228 
13229     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13230       N->getOperand(i);
13231     if (NextInput.getOpcode() != ISD::LOAD)
13232       return SDValue();
13233 
13234     SDValue PreviousInput =
13235       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13236     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13237     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13238 
13239     // If any inputs are fp_round(extload), they all must be.
13240     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13241       return SDValue();
13242 
13243     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13244       InputsAreConsecutiveLoads = false;
13245     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13246       InputsAreReverseConsecutive = false;
13247 
13248     // Exit early if the loads are neither consecutive nor reverse consecutive.
13249     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13250       return SDValue();
13251   }
13252 
13253   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13254          "The loads cannot be both consecutive and reverse consecutive.");
13255 
13256   SDValue FirstLoadOp =
13257     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13258   SDValue LastLoadOp =
13259     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13260                        N->getOperand(N->getNumOperands()-1);
13261 
13262   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13263   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13264   if (InputsAreConsecutiveLoads) {
13265     assert(LD1 && "Input needs to be a LoadSDNode.");
13266     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13267                        LD1->getBasePtr(), LD1->getPointerInfo(),
13268                        LD1->getAlignment());
13269   }
13270   if (InputsAreReverseConsecutive) {
13271     assert(LDL && "Input needs to be a LoadSDNode.");
13272     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13273                                LDL->getBasePtr(), LDL->getPointerInfo(),
13274                                LDL->getAlignment());
13275     SmallVector<int, 16> Ops;
13276     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13277       Ops.push_back(i);
13278 
13279     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13280                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13281   }
13282   return SDValue();
13283 }
13284 
13285 // This function adds the required vector_shuffle needed to get
13286 // the elements of the vector extract in the correct position
13287 // as specified by the CorrectElems encoding.
13288 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13289                                       SDValue Input, uint64_t Elems,
13290                                       uint64_t CorrectElems) {
13291   SDLoc dl(N);
13292 
13293   unsigned NumElems = Input.getValueType().getVectorNumElements();
13294   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13295 
13296   // Knowing the element indices being extracted from the original
13297   // vector and the order in which they're being inserted, just put
13298   // them at element indices required for the instruction.
13299   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13300     if (DAG.getDataLayout().isLittleEndian())
13301       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13302     else
13303       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13304     CorrectElems = CorrectElems >> 8;
13305     Elems = Elems >> 8;
13306   }
13307 
13308   SDValue Shuffle =
13309       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13310                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13311 
13312   EVT VT = N->getValueType(0);
13313   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13314 
13315   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13316                                Input.getValueType().getVectorElementType(),
13317                                VT.getVectorNumElements());
13318   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13319                      DAG.getValueType(ExtVT));
13320 }
13321 
13322 // Look for build vector patterns where input operands come from sign
13323 // extended vector_extract elements of specific indices. If the correct indices
13324 // aren't used, add a vector shuffle to fix up the indices and create
13325 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13326 // during instruction selection.
13327 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13328   // This array encodes the indices that the vector sign extend instructions
13329   // extract from when extending from one type to another for both BE and LE.
13330   // The right nibble of each byte corresponds to the LE incides.
13331   // and the left nibble of each byte corresponds to the BE incides.
13332   // For example: 0x3074B8FC  byte->word
13333   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13334   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13335   // For example: 0x000070F8  byte->double word
13336   // For LE: the allowed indices are: 0x0,0x8
13337   // For BE: the allowed indices are: 0x7,0xF
13338   uint64_t TargetElems[] = {
13339       0x3074B8FC, // b->w
13340       0x000070F8, // b->d
13341       0x10325476, // h->w
13342       0x00003074, // h->d
13343       0x00001032, // w->d
13344   };
13345 
13346   uint64_t Elems = 0;
13347   int Index;
13348   SDValue Input;
13349 
13350   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13351     if (!Op)
13352       return false;
13353     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13354         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13355       return false;
13356 
13357     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13358     // of the right width.
13359     SDValue Extract = Op.getOperand(0);
13360     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13361       Extract = Extract.getOperand(0);
13362     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13363       return false;
13364 
13365     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13366     if (!ExtOp)
13367       return false;
13368 
13369     Index = ExtOp->getZExtValue();
13370     if (Input && Input != Extract.getOperand(0))
13371       return false;
13372 
13373     if (!Input)
13374       Input = Extract.getOperand(0);
13375 
13376     Elems = Elems << 8;
13377     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13378     Elems |= Index;
13379 
13380     return true;
13381   };
13382 
13383   // If the build vector operands aren't sign extended vector extracts,
13384   // of the same input vector, then return.
13385   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13386     if (!isSExtOfVecExtract(N->getOperand(i))) {
13387       return SDValue();
13388     }
13389   }
13390 
13391   // If the vector extract indicies are not correct, add the appropriate
13392   // vector_shuffle.
13393   int TgtElemArrayIdx;
13394   int InputSize = Input.getValueType().getScalarSizeInBits();
13395   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13396   if (InputSize + OutputSize == 40)
13397     TgtElemArrayIdx = 0;
13398   else if (InputSize + OutputSize == 72)
13399     TgtElemArrayIdx = 1;
13400   else if (InputSize + OutputSize == 48)
13401     TgtElemArrayIdx = 2;
13402   else if (InputSize + OutputSize == 80)
13403     TgtElemArrayIdx = 3;
13404   else if (InputSize + OutputSize == 96)
13405     TgtElemArrayIdx = 4;
13406   else
13407     return SDValue();
13408 
13409   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13410   CorrectElems = DAG.getDataLayout().isLittleEndian()
13411                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13412                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13413   if (Elems != CorrectElems) {
13414     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13415   }
13416 
13417   // Regular lowering will catch cases where a shuffle is not needed.
13418   return SDValue();
13419 }
13420 
13421 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13422                                                  DAGCombinerInfo &DCI) const {
13423   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13424          "Should be called with a BUILD_VECTOR node");
13425 
13426   SelectionDAG &DAG = DCI.DAG;
13427   SDLoc dl(N);
13428 
13429   if (!Subtarget.hasVSX())
13430     return SDValue();
13431 
13432   // The target independent DAG combiner will leave a build_vector of
13433   // float-to-int conversions intact. We can generate MUCH better code for
13434   // a float-to-int conversion of a vector of floats.
13435   SDValue FirstInput = N->getOperand(0);
13436   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13437     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13438     if (Reduced)
13439       return Reduced;
13440   }
13441 
13442   // If we're building a vector out of consecutive loads, just load that
13443   // vector type.
13444   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13445   if (Reduced)
13446     return Reduced;
13447 
13448   // If we're building a vector out of extended elements from another vector
13449   // we have P9 vector integer extend instructions. The code assumes legal
13450   // input types (i.e. it can't handle things like v4i16) so do not run before
13451   // legalization.
13452   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13453     Reduced = combineBVOfVecSExt(N, DAG);
13454     if (Reduced)
13455       return Reduced;
13456   }
13457 
13458 
13459   if (N->getValueType(0) != MVT::v2f64)
13460     return SDValue();
13461 
13462   // Looking for:
13463   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13464   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13465       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13466     return SDValue();
13467   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13468       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13469     return SDValue();
13470   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13471     return SDValue();
13472 
13473   SDValue Ext1 = FirstInput.getOperand(0);
13474   SDValue Ext2 = N->getOperand(1).getOperand(0);
13475   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13476      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13477     return SDValue();
13478 
13479   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13480   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13481   if (!Ext1Op || !Ext2Op)
13482     return SDValue();
13483   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13484       Ext1.getOperand(0) != Ext2.getOperand(0))
13485     return SDValue();
13486 
13487   int FirstElem = Ext1Op->getZExtValue();
13488   int SecondElem = Ext2Op->getZExtValue();
13489   int SubvecIdx;
13490   if (FirstElem == 0 && SecondElem == 1)
13491     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13492   else if (FirstElem == 2 && SecondElem == 3)
13493     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13494   else
13495     return SDValue();
13496 
13497   SDValue SrcVec = Ext1.getOperand(0);
13498   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13499     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13500   return DAG.getNode(NodeType, dl, MVT::v2f64,
13501                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13502 }
13503 
13504 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13505                                               DAGCombinerInfo &DCI) const {
13506   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13507           N->getOpcode() == ISD::UINT_TO_FP) &&
13508          "Need an int -> FP conversion node here");
13509 
13510   if (useSoftFloat() || !Subtarget.has64BitSupport())
13511     return SDValue();
13512 
13513   SelectionDAG &DAG = DCI.DAG;
13514   SDLoc dl(N);
13515   SDValue Op(N, 0);
13516 
13517   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13518   // from the hardware.
13519   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13520     return SDValue();
13521   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13522       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13523     return SDValue();
13524 
13525   SDValue FirstOperand(Op.getOperand(0));
13526   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13527     (FirstOperand.getValueType() == MVT::i8 ||
13528      FirstOperand.getValueType() == MVT::i16);
13529   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13530     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13531     bool DstDouble = Op.getValueType() == MVT::f64;
13532     unsigned ConvOp = Signed ?
13533       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13534       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13535     SDValue WidthConst =
13536       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13537                             dl, false);
13538     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13539     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13540     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13541                                          DAG.getVTList(MVT::f64, MVT::Other),
13542                                          Ops, MVT::i8, LDN->getMemOperand());
13543 
13544     // For signed conversion, we need to sign-extend the value in the VSR
13545     if (Signed) {
13546       SDValue ExtOps[] = { Ld, WidthConst };
13547       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13548       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13549     } else
13550       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13551   }
13552 
13553 
13554   // For i32 intermediate values, unfortunately, the conversion functions
13555   // leave the upper 32 bits of the value are undefined. Within the set of
13556   // scalar instructions, we have no method for zero- or sign-extending the
13557   // value. Thus, we cannot handle i32 intermediate values here.
13558   if (Op.getOperand(0).getValueType() == MVT::i32)
13559     return SDValue();
13560 
13561   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13562          "UINT_TO_FP is supported only with FPCVT");
13563 
13564   // If we have FCFIDS, then use it when converting to single-precision.
13565   // Otherwise, convert to double-precision and then round.
13566   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13567                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13568                                                             : PPCISD::FCFIDS)
13569                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13570                                                             : PPCISD::FCFID);
13571   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13572                   ? MVT::f32
13573                   : MVT::f64;
13574 
13575   // If we're converting from a float, to an int, and back to a float again,
13576   // then we don't need the store/load pair at all.
13577   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13578        Subtarget.hasFPCVT()) ||
13579       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13580     SDValue Src = Op.getOperand(0).getOperand(0);
13581     if (Src.getValueType() == MVT::f32) {
13582       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13583       DCI.AddToWorklist(Src.getNode());
13584     } else if (Src.getValueType() != MVT::f64) {
13585       // Make sure that we don't pick up a ppc_fp128 source value.
13586       return SDValue();
13587     }
13588 
13589     unsigned FCTOp =
13590       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13591                                                         PPCISD::FCTIDUZ;
13592 
13593     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13594     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13595 
13596     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13597       FP = DAG.getNode(ISD::FP_ROUND, dl,
13598                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13599       DCI.AddToWorklist(FP.getNode());
13600     }
13601 
13602     return FP;
13603   }
13604 
13605   return SDValue();
13606 }
13607 
13608 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13609 // builtins) into loads with swaps.
13610 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13611                                               DAGCombinerInfo &DCI) const {
13612   SelectionDAG &DAG = DCI.DAG;
13613   SDLoc dl(N);
13614   SDValue Chain;
13615   SDValue Base;
13616   MachineMemOperand *MMO;
13617 
13618   switch (N->getOpcode()) {
13619   default:
13620     llvm_unreachable("Unexpected opcode for little endian VSX load");
13621   case ISD::LOAD: {
13622     LoadSDNode *LD = cast<LoadSDNode>(N);
13623     Chain = LD->getChain();
13624     Base = LD->getBasePtr();
13625     MMO = LD->getMemOperand();
13626     // If the MMO suggests this isn't a load of a full vector, leave
13627     // things alone.  For a built-in, we have to make the change for
13628     // correctness, so if there is a size problem that will be a bug.
13629     if (MMO->getSize() < 16)
13630       return SDValue();
13631     break;
13632   }
13633   case ISD::INTRINSIC_W_CHAIN: {
13634     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13635     Chain = Intrin->getChain();
13636     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13637     // us what we want. Get operand 2 instead.
13638     Base = Intrin->getOperand(2);
13639     MMO = Intrin->getMemOperand();
13640     break;
13641   }
13642   }
13643 
13644   MVT VecTy = N->getValueType(0).getSimpleVT();
13645 
13646   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13647   // aligned and the type is a vector with elements up to 4 bytes
13648   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13649       VecTy.getScalarSizeInBits() <= 32) {
13650     return SDValue();
13651   }
13652 
13653   SDValue LoadOps[] = { Chain, Base };
13654   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13655                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13656                                          LoadOps, MVT::v2f64, MMO);
13657 
13658   DCI.AddToWorklist(Load.getNode());
13659   Chain = Load.getValue(1);
13660   SDValue Swap = DAG.getNode(
13661       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13662   DCI.AddToWorklist(Swap.getNode());
13663 
13664   // Add a bitcast if the resulting load type doesn't match v2f64.
13665   if (VecTy != MVT::v2f64) {
13666     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13667     DCI.AddToWorklist(N.getNode());
13668     // Package {bitcast value, swap's chain} to match Load's shape.
13669     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13670                        N, Swap.getValue(1));
13671   }
13672 
13673   return Swap;
13674 }
13675 
13676 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13677 // builtins) into stores with swaps.
13678 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13679                                                DAGCombinerInfo &DCI) const {
13680   SelectionDAG &DAG = DCI.DAG;
13681   SDLoc dl(N);
13682   SDValue Chain;
13683   SDValue Base;
13684   unsigned SrcOpnd;
13685   MachineMemOperand *MMO;
13686 
13687   switch (N->getOpcode()) {
13688   default:
13689     llvm_unreachable("Unexpected opcode for little endian VSX store");
13690   case ISD::STORE: {
13691     StoreSDNode *ST = cast<StoreSDNode>(N);
13692     Chain = ST->getChain();
13693     Base = ST->getBasePtr();
13694     MMO = ST->getMemOperand();
13695     SrcOpnd = 1;
13696     // If the MMO suggests this isn't a store of a full vector, leave
13697     // things alone.  For a built-in, we have to make the change for
13698     // correctness, so if there is a size problem that will be a bug.
13699     if (MMO->getSize() < 16)
13700       return SDValue();
13701     break;
13702   }
13703   case ISD::INTRINSIC_VOID: {
13704     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13705     Chain = Intrin->getChain();
13706     // Intrin->getBasePtr() oddly does not get what we want.
13707     Base = Intrin->getOperand(3);
13708     MMO = Intrin->getMemOperand();
13709     SrcOpnd = 2;
13710     break;
13711   }
13712   }
13713 
13714   SDValue Src = N->getOperand(SrcOpnd);
13715   MVT VecTy = Src.getValueType().getSimpleVT();
13716 
13717   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13718   // aligned and the type is a vector with elements up to 4 bytes
13719   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13720       VecTy.getScalarSizeInBits() <= 32) {
13721     return SDValue();
13722   }
13723 
13724   // All stores are done as v2f64 and possible bit cast.
13725   if (VecTy != MVT::v2f64) {
13726     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13727     DCI.AddToWorklist(Src.getNode());
13728   }
13729 
13730   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13731                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13732   DCI.AddToWorklist(Swap.getNode());
13733   Chain = Swap.getValue(1);
13734   SDValue StoreOps[] = { Chain, Swap, Base };
13735   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13736                                           DAG.getVTList(MVT::Other),
13737                                           StoreOps, VecTy, MMO);
13738   DCI.AddToWorklist(Store.getNode());
13739   return Store;
13740 }
13741 
13742 // Handle DAG combine for STORE (FP_TO_INT F).
13743 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13744                                                DAGCombinerInfo &DCI) const {
13745 
13746   SelectionDAG &DAG = DCI.DAG;
13747   SDLoc dl(N);
13748   unsigned Opcode = N->getOperand(1).getOpcode();
13749 
13750   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13751          && "Not a FP_TO_INT Instruction!");
13752 
13753   SDValue Val = N->getOperand(1).getOperand(0);
13754   EVT Op1VT = N->getOperand(1).getValueType();
13755   EVT ResVT = Val.getValueType();
13756 
13757   // Floating point types smaller than 32 bits are not legal on Power.
13758   if (ResVT.getScalarSizeInBits() < 32)
13759     return SDValue();
13760 
13761   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13762   bool ValidTypeForStoreFltAsInt =
13763         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13764          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13765 
13766   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13767       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13768     return SDValue();
13769 
13770   // Extend f32 values to f64
13771   if (ResVT.getScalarSizeInBits() == 32) {
13772     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13773     DCI.AddToWorklist(Val.getNode());
13774   }
13775 
13776   // Set signed or unsigned conversion opcode.
13777   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13778                           PPCISD::FP_TO_SINT_IN_VSR :
13779                           PPCISD::FP_TO_UINT_IN_VSR;
13780 
13781   Val = DAG.getNode(ConvOpcode,
13782                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13783   DCI.AddToWorklist(Val.getNode());
13784 
13785   // Set number of bytes being converted.
13786   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13787   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13788                     DAG.getIntPtrConstant(ByteSize, dl, false),
13789                     DAG.getValueType(Op1VT) };
13790 
13791   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13792           DAG.getVTList(MVT::Other), Ops,
13793           cast<StoreSDNode>(N)->getMemoryVT(),
13794           cast<StoreSDNode>(N)->getMemOperand());
13795 
13796   DCI.AddToWorklist(Val.getNode());
13797   return Val;
13798 }
13799 
13800 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13801   // Check that the source of the element keeps flipping
13802   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
13803   bool PrevElemFromFirstVec = Mask[0] < NumElts;
13804   for (int i = 1, e = Mask.size(); i < e; i++) {
13805     if (PrevElemFromFirstVec && Mask[i] < NumElts)
13806       return false;
13807     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
13808       return false;
13809     PrevElemFromFirstVec = !PrevElemFromFirstVec;
13810   }
13811   return true;
13812 }
13813 
13814 static bool isSplatBV(SDValue Op) {
13815   if (Op.getOpcode() != ISD::BUILD_VECTOR)
13816     return false;
13817   SDValue FirstOp;
13818 
13819   // Find first non-undef input.
13820   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
13821     FirstOp = Op.getOperand(i);
13822     if (!FirstOp.isUndef())
13823       break;
13824   }
13825 
13826   // All inputs are undef or the same as the first non-undef input.
13827   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
13828     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
13829       return false;
13830   return true;
13831 }
13832 
13833 static SDValue isScalarToVec(SDValue Op) {
13834   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13835     return Op;
13836   if (Op.getOpcode() != ISD::BITCAST)
13837     return SDValue();
13838   Op = Op.getOperand(0);
13839   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13840     return Op;
13841   return SDValue();
13842 }
13843 
13844 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
13845                                             int LHSMaxIdx, int RHSMinIdx,
13846                                             int RHSMaxIdx, int HalfVec) {
13847   for (int i = 0, e = ShuffV.size(); i < e; i++) {
13848     int Idx = ShuffV[i];
13849     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
13850       ShuffV[i] += HalfVec;
13851   }
13852   return;
13853 }
13854 
13855 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
13856 // the original is:
13857 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
13858 // In such a case, just change the shuffle mask to extract the element
13859 // from the permuted index.
13860 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
13861   SDLoc dl(OrigSToV);
13862   EVT VT = OrigSToV.getValueType();
13863   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13864          "Expecting a SCALAR_TO_VECTOR here");
13865   SDValue Input = OrigSToV.getOperand(0);
13866 
13867   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13868     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
13869     SDValue OrigVector = Input.getOperand(0);
13870 
13871     // Can't handle non-const element indices or different vector types
13872     // for the input to the extract and the output of the scalar_to_vector.
13873     if (Idx && VT == OrigVector.getValueType()) {
13874       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
13875       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
13876       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
13877     }
13878   }
13879   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
13880                      OrigSToV.getOperand(0));
13881 }
13882 
13883 // On little endian subtargets, combine shuffles such as:
13884 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
13885 // into:
13886 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
13887 // because the latter can be matched to a single instruction merge.
13888 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
13889 // to put the value into element zero. Adjust the shuffle mask so that the
13890 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
13891 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
13892                                                 SelectionDAG &DAG) const {
13893   SDValue LHS = SVN->getOperand(0);
13894   SDValue RHS = SVN->getOperand(1);
13895   auto Mask = SVN->getMask();
13896   int NumElts = LHS.getValueType().getVectorNumElements();
13897   SDValue Res(SVN, 0);
13898   SDLoc dl(SVN);
13899 
13900   // None of these combines are useful on big endian systems since the ISA
13901   // already has a big endian bias.
13902   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13903     return Res;
13904 
13905   // If this is not a shuffle of a shuffle and the first element comes from
13906   // the second vector, canonicalize to the commuted form. This will make it
13907   // more likely to match one of the single instruction patterns.
13908   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13909       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
13910     std::swap(LHS, RHS);
13911     Res = DAG.getCommutedVectorShuffle(*SVN);
13912     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13913   }
13914 
13915   // Adjust the shuffle mask if either input vector comes from a
13916   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
13917   // form (to prevent the need for a swap).
13918   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
13919   SDValue SToVLHS = isScalarToVec(LHS);
13920   SDValue SToVRHS = isScalarToVec(RHS);
13921   if (SToVLHS || SToVRHS) {
13922     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
13923                             : SToVRHS.getValueType().getVectorNumElements();
13924     int NumEltsOut = ShuffV.size();
13925 
13926     // Initially assume that neither input is permuted. These will be adjusted
13927     // accordingly if either input is.
13928     int LHSMaxIdx = -1;
13929     int RHSMinIdx = -1;
13930     int RHSMaxIdx = -1;
13931     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
13932 
13933     // Get the permuted scalar to vector nodes for the source(s) that come from
13934     // ISD::SCALAR_TO_VECTOR.
13935     if (SToVLHS) {
13936       // Set up the values for the shuffle vector fixup.
13937       LHSMaxIdx = NumEltsOut / NumEltsIn;
13938       SToVLHS = getSToVPermuted(SToVLHS, DAG);
13939       if (SToVLHS.getValueType() != LHS.getValueType())
13940         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
13941       LHS = SToVLHS;
13942     }
13943     if (SToVRHS) {
13944       RHSMinIdx = NumEltsOut;
13945       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
13946       SToVRHS = getSToVPermuted(SToVRHS, DAG);
13947       if (SToVRHS.getValueType() != RHS.getValueType())
13948         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
13949       RHS = SToVRHS;
13950     }
13951 
13952     // Fix up the shuffle mask to reflect where the desired element actually is.
13953     // The minimum and maximum indices that correspond to element zero for both
13954     // the LHS and RHS are computed and will control which shuffle mask entries
13955     // are to be changed. For example, if the RHS is permuted, any shuffle mask
13956     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
13957     // HalfVec to refer to the corresponding element in the permuted vector.
13958     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
13959                                     HalfVec);
13960     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
13961 
13962     // We may have simplified away the shuffle. We won't be able to do anything
13963     // further with it here.
13964     if (!isa<ShuffleVectorSDNode>(Res))
13965       return Res;
13966     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13967   }
13968 
13969   // The common case after we commuted the shuffle is that the RHS is a splat
13970   // and we have elements coming in from the splat at indices that are not
13971   // conducive to using a merge.
13972   // Example:
13973   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
13974   if (!isSplatBV(RHS))
13975     return Res;
13976 
13977   // We are looking for a mask such that all even elements are from
13978   // one vector and all odd elements from the other.
13979   if (!isAlternatingShuffMask(Mask, NumElts))
13980     return Res;
13981 
13982   // Adjust the mask so we are pulling in the same index from the splat
13983   // as the index from the interesting vector in consecutive elements.
13984   // Example (even elements from first vector):
13985   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
13986   if (Mask[0] < NumElts)
13987     for (int i = 1, e = Mask.size(); i < e; i += 2)
13988       ShuffV[i] = (ShuffV[i - 1] + NumElts);
13989   // Example (odd elements from first vector):
13990   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
13991   else
13992     for (int i = 0, e = Mask.size(); i < e; i += 2)
13993       ShuffV[i] = (ShuffV[i + 1] + NumElts);
13994 
13995   // If the RHS has undefs, we need to remove them since we may have created
13996   // a shuffle that adds those instead of the splat value.
13997   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
13998   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
13999 
14000   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14001   return Res;
14002 }
14003 
14004 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14005                                                 LSBaseSDNode *LSBase,
14006                                                 DAGCombinerInfo &DCI) const {
14007   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14008         "Not a reverse memop pattern!");
14009 
14010   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14011     auto Mask = SVN->getMask();
14012     int i = 0;
14013     auto I = Mask.rbegin();
14014     auto E = Mask.rend();
14015 
14016     for (; I != E; ++I) {
14017       if (*I != i)
14018         return false;
14019       i++;
14020     }
14021     return true;
14022   };
14023 
14024   SelectionDAG &DAG = DCI.DAG;
14025   EVT VT = SVN->getValueType(0);
14026 
14027   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14028     return SDValue();
14029 
14030   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14031   // See comment in PPCVSXSwapRemoval.cpp.
14032   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14033   if (!Subtarget.hasP9Vector())
14034     return SDValue();
14035 
14036   if(!IsElementReverse(SVN))
14037     return SDValue();
14038 
14039   if (LSBase->getOpcode() == ISD::LOAD) {
14040     SDLoc dl(SVN);
14041     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14042     return DAG.getMemIntrinsicNode(
14043         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14044         LSBase->getMemoryVT(), LSBase->getMemOperand());
14045   }
14046 
14047   if (LSBase->getOpcode() == ISD::STORE) {
14048     SDLoc dl(LSBase);
14049     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14050                           LSBase->getBasePtr()};
14051     return DAG.getMemIntrinsicNode(
14052         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14053         LSBase->getMemoryVT(), LSBase->getMemOperand());
14054   }
14055 
14056   llvm_unreachable("Expected a load or store node here");
14057 }
14058 
14059 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14060                                              DAGCombinerInfo &DCI) const {
14061   SelectionDAG &DAG = DCI.DAG;
14062   SDLoc dl(N);
14063   switch (N->getOpcode()) {
14064   default: break;
14065   case ISD::ADD:
14066     return combineADD(N, DCI);
14067   case ISD::SHL:
14068     return combineSHL(N, DCI);
14069   case ISD::SRA:
14070     return combineSRA(N, DCI);
14071   case ISD::SRL:
14072     return combineSRL(N, DCI);
14073   case ISD::MUL:
14074     return combineMUL(N, DCI);
14075   case ISD::FMA:
14076   case PPCISD::FNMSUB:
14077     return combineFMALike(N, DCI);
14078   case PPCISD::SHL:
14079     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14080         return N->getOperand(0);
14081     break;
14082   case PPCISD::SRL:
14083     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14084         return N->getOperand(0);
14085     break;
14086   case PPCISD::SRA:
14087     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14088       if (C->isNullValue() ||   //  0 >>s V -> 0.
14089           C->isAllOnesValue())    // -1 >>s V -> -1.
14090         return N->getOperand(0);
14091     }
14092     break;
14093   case ISD::SIGN_EXTEND:
14094   case ISD::ZERO_EXTEND:
14095   case ISD::ANY_EXTEND:
14096     return DAGCombineExtBoolTrunc(N, DCI);
14097   case ISD::TRUNCATE:
14098     return combineTRUNCATE(N, DCI);
14099   case ISD::SETCC:
14100     if (SDValue CSCC = combineSetCC(N, DCI))
14101       return CSCC;
14102     LLVM_FALLTHROUGH;
14103   case ISD::SELECT_CC:
14104     return DAGCombineTruncBoolExt(N, DCI);
14105   case ISD::SINT_TO_FP:
14106   case ISD::UINT_TO_FP:
14107     return combineFPToIntToFP(N, DCI);
14108   case ISD::VECTOR_SHUFFLE:
14109     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14110       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14111       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14112     }
14113     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14114   case ISD::STORE: {
14115 
14116     EVT Op1VT = N->getOperand(1).getValueType();
14117     unsigned Opcode = N->getOperand(1).getOpcode();
14118 
14119     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14120       SDValue Val= combineStoreFPToInt(N, DCI);
14121       if (Val)
14122         return Val;
14123     }
14124 
14125     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14126       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14127       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14128       if (Val)
14129         return Val;
14130     }
14131 
14132     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14133     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14134         N->getOperand(1).getNode()->hasOneUse() &&
14135         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14136          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14137 
14138       // STBRX can only handle simple types and it makes no sense to store less
14139       // two bytes in byte-reversed order.
14140       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14141       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14142         break;
14143 
14144       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14145       // Do an any-extend to 32-bits if this is a half-word input.
14146       if (BSwapOp.getValueType() == MVT::i16)
14147         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14148 
14149       // If the type of BSWAP operand is wider than stored memory width
14150       // it need to be shifted to the right side before STBRX.
14151       if (Op1VT.bitsGT(mVT)) {
14152         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14153         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14154                               DAG.getConstant(Shift, dl, MVT::i32));
14155         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14156         if (Op1VT == MVT::i64)
14157           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14158       }
14159 
14160       SDValue Ops[] = {
14161         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14162       };
14163       return
14164         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14165                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14166                                 cast<StoreSDNode>(N)->getMemOperand());
14167     }
14168 
14169     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14170     // So it can increase the chance of CSE constant construction.
14171     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14172         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14173       // Need to sign-extended to 64-bits to handle negative values.
14174       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14175       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14176                                     MemVT.getSizeInBits());
14177       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14178 
14179       // DAG.getTruncStore() can't be used here because it doesn't accept
14180       // the general (base + offset) addressing mode.
14181       // So we use UpdateNodeOperands and setTruncatingStore instead.
14182       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14183                              N->getOperand(3));
14184       cast<StoreSDNode>(N)->setTruncatingStore(true);
14185       return SDValue(N, 0);
14186     }
14187 
14188     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14189     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14190     if (Op1VT.isSimple()) {
14191       MVT StoreVT = Op1VT.getSimpleVT();
14192       if (Subtarget.needsSwapsForVSXMemOps() &&
14193           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14194            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14195         return expandVSXStoreForLE(N, DCI);
14196     }
14197     break;
14198   }
14199   case ISD::LOAD: {
14200     LoadSDNode *LD = cast<LoadSDNode>(N);
14201     EVT VT = LD->getValueType(0);
14202 
14203     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14204     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14205     if (VT.isSimple()) {
14206       MVT LoadVT = VT.getSimpleVT();
14207       if (Subtarget.needsSwapsForVSXMemOps() &&
14208           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14209            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14210         return expandVSXLoadForLE(N, DCI);
14211     }
14212 
14213     // We sometimes end up with a 64-bit integer load, from which we extract
14214     // two single-precision floating-point numbers. This happens with
14215     // std::complex<float>, and other similar structures, because of the way we
14216     // canonicalize structure copies. However, if we lack direct moves,
14217     // then the final bitcasts from the extracted integer values to the
14218     // floating-point numbers turn into store/load pairs. Even with direct moves,
14219     // just loading the two floating-point numbers is likely better.
14220     auto ReplaceTwoFloatLoad = [&]() {
14221       if (VT != MVT::i64)
14222         return false;
14223 
14224       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14225           LD->isVolatile())
14226         return false;
14227 
14228       //  We're looking for a sequence like this:
14229       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14230       //      t16: i64 = srl t13, Constant:i32<32>
14231       //    t17: i32 = truncate t16
14232       //  t18: f32 = bitcast t17
14233       //    t19: i32 = truncate t13
14234       //  t20: f32 = bitcast t19
14235 
14236       if (!LD->hasNUsesOfValue(2, 0))
14237         return false;
14238 
14239       auto UI = LD->use_begin();
14240       while (UI.getUse().getResNo() != 0) ++UI;
14241       SDNode *Trunc = *UI++;
14242       while (UI.getUse().getResNo() != 0) ++UI;
14243       SDNode *RightShift = *UI;
14244       if (Trunc->getOpcode() != ISD::TRUNCATE)
14245         std::swap(Trunc, RightShift);
14246 
14247       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14248           Trunc->getValueType(0) != MVT::i32 ||
14249           !Trunc->hasOneUse())
14250         return false;
14251       if (RightShift->getOpcode() != ISD::SRL ||
14252           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14253           RightShift->getConstantOperandVal(1) != 32 ||
14254           !RightShift->hasOneUse())
14255         return false;
14256 
14257       SDNode *Trunc2 = *RightShift->use_begin();
14258       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14259           Trunc2->getValueType(0) != MVT::i32 ||
14260           !Trunc2->hasOneUse())
14261         return false;
14262 
14263       SDNode *Bitcast = *Trunc->use_begin();
14264       SDNode *Bitcast2 = *Trunc2->use_begin();
14265 
14266       if (Bitcast->getOpcode() != ISD::BITCAST ||
14267           Bitcast->getValueType(0) != MVT::f32)
14268         return false;
14269       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14270           Bitcast2->getValueType(0) != MVT::f32)
14271         return false;
14272 
14273       if (Subtarget.isLittleEndian())
14274         std::swap(Bitcast, Bitcast2);
14275 
14276       // Bitcast has the second float (in memory-layout order) and Bitcast2
14277       // has the first one.
14278 
14279       SDValue BasePtr = LD->getBasePtr();
14280       if (LD->isIndexed()) {
14281         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14282                "Non-pre-inc AM on PPC?");
14283         BasePtr =
14284           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14285                       LD->getOffset());
14286       }
14287 
14288       auto MMOFlags =
14289           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14290       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14291                                       LD->getPointerInfo(), LD->getAlignment(),
14292                                       MMOFlags, LD->getAAInfo());
14293       SDValue AddPtr =
14294         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14295                     BasePtr, DAG.getIntPtrConstant(4, dl));
14296       SDValue FloatLoad2 = DAG.getLoad(
14297           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14298           LD->getPointerInfo().getWithOffset(4),
14299           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14300 
14301       if (LD->isIndexed()) {
14302         // Note that DAGCombine should re-form any pre-increment load(s) from
14303         // what is produced here if that makes sense.
14304         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14305       }
14306 
14307       DCI.CombineTo(Bitcast2, FloatLoad);
14308       DCI.CombineTo(Bitcast, FloatLoad2);
14309 
14310       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14311                                     SDValue(FloatLoad2.getNode(), 1));
14312       return true;
14313     };
14314 
14315     if (ReplaceTwoFloatLoad())
14316       return SDValue(N, 0);
14317 
14318     EVT MemVT = LD->getMemoryVT();
14319     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14320     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14321     if (LD->isUnindexed() && VT.isVector() &&
14322         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14323           // P8 and later hardware should just use LOAD.
14324           !Subtarget.hasP8Vector() &&
14325           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14326            VT == MVT::v4f32))) &&
14327         LD->getAlign() < ABIAlignment) {
14328       // This is a type-legal unaligned Altivec load.
14329       SDValue Chain = LD->getChain();
14330       SDValue Ptr = LD->getBasePtr();
14331       bool isLittleEndian = Subtarget.isLittleEndian();
14332 
14333       // This implements the loading of unaligned vectors as described in
14334       // the venerable Apple Velocity Engine overview. Specifically:
14335       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14336       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14337       //
14338       // The general idea is to expand a sequence of one or more unaligned
14339       // loads into an alignment-based permutation-control instruction (lvsl
14340       // or lvsr), a series of regular vector loads (which always truncate
14341       // their input address to an aligned address), and a series of
14342       // permutations.  The results of these permutations are the requested
14343       // loaded values.  The trick is that the last "extra" load is not taken
14344       // from the address you might suspect (sizeof(vector) bytes after the
14345       // last requested load), but rather sizeof(vector) - 1 bytes after the
14346       // last requested vector. The point of this is to avoid a page fault if
14347       // the base address happened to be aligned. This works because if the
14348       // base address is aligned, then adding less than a full vector length
14349       // will cause the last vector in the sequence to be (re)loaded.
14350       // Otherwise, the next vector will be fetched as you might suspect was
14351       // necessary.
14352 
14353       // We might be able to reuse the permutation generation from
14354       // a different base address offset from this one by an aligned amount.
14355       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14356       // optimization later.
14357       Intrinsic::ID Intr, IntrLD, IntrPerm;
14358       MVT PermCntlTy, PermTy, LDTy;
14359       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14360                             : Intrinsic::ppc_altivec_lvsl;
14361       IntrLD = Intrinsic::ppc_altivec_lvx;
14362       IntrPerm = Intrinsic::ppc_altivec_vperm;
14363       PermCntlTy = MVT::v16i8;
14364       PermTy = MVT::v4i32;
14365       LDTy = MVT::v4i32;
14366 
14367       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14368 
14369       // Create the new MMO for the new base load. It is like the original MMO,
14370       // but represents an area in memory almost twice the vector size centered
14371       // on the original address. If the address is unaligned, we might start
14372       // reading up to (sizeof(vector)-1) bytes below the address of the
14373       // original unaligned load.
14374       MachineFunction &MF = DAG.getMachineFunction();
14375       MachineMemOperand *BaseMMO =
14376         MF.getMachineMemOperand(LD->getMemOperand(),
14377                                 -(long)MemVT.getStoreSize()+1,
14378                                 2*MemVT.getStoreSize()-1);
14379 
14380       // Create the new base load.
14381       SDValue LDXIntID =
14382           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14383       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14384       SDValue BaseLoad =
14385         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14386                                 DAG.getVTList(PermTy, MVT::Other),
14387                                 BaseLoadOps, LDTy, BaseMMO);
14388 
14389       // Note that the value of IncOffset (which is provided to the next
14390       // load's pointer info offset value, and thus used to calculate the
14391       // alignment), and the value of IncValue (which is actually used to
14392       // increment the pointer value) are different! This is because we
14393       // require the next load to appear to be aligned, even though it
14394       // is actually offset from the base pointer by a lesser amount.
14395       int IncOffset = VT.getSizeInBits() / 8;
14396       int IncValue = IncOffset;
14397 
14398       // Walk (both up and down) the chain looking for another load at the real
14399       // (aligned) offset (the alignment of the other load does not matter in
14400       // this case). If found, then do not use the offset reduction trick, as
14401       // that will prevent the loads from being later combined (as they would
14402       // otherwise be duplicates).
14403       if (!findConsecutiveLoad(LD, DAG))
14404         --IncValue;
14405 
14406       SDValue Increment =
14407           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14408       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14409 
14410       MachineMemOperand *ExtraMMO =
14411         MF.getMachineMemOperand(LD->getMemOperand(),
14412                                 1, 2*MemVT.getStoreSize()-1);
14413       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14414       SDValue ExtraLoad =
14415         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14416                                 DAG.getVTList(PermTy, MVT::Other),
14417                                 ExtraLoadOps, LDTy, ExtraMMO);
14418 
14419       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14420         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14421 
14422       // Because vperm has a big-endian bias, we must reverse the order
14423       // of the input vectors and complement the permute control vector
14424       // when generating little endian code.  We have already handled the
14425       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14426       // and ExtraLoad here.
14427       SDValue Perm;
14428       if (isLittleEndian)
14429         Perm = BuildIntrinsicOp(IntrPerm,
14430                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14431       else
14432         Perm = BuildIntrinsicOp(IntrPerm,
14433                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14434 
14435       if (VT != PermTy)
14436         Perm = Subtarget.hasAltivec()
14437                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14438                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14439                                  DAG.getTargetConstant(1, dl, MVT::i64));
14440                                // second argument is 1 because this rounding
14441                                // is always exact.
14442 
14443       // The output of the permutation is our loaded result, the TokenFactor is
14444       // our new chain.
14445       DCI.CombineTo(N, Perm, TF);
14446       return SDValue(N, 0);
14447     }
14448     }
14449     break;
14450     case ISD::INTRINSIC_WO_CHAIN: {
14451       bool isLittleEndian = Subtarget.isLittleEndian();
14452       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14453       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14454                                            : Intrinsic::ppc_altivec_lvsl);
14455       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14456         SDValue Add = N->getOperand(1);
14457 
14458         int Bits = 4 /* 16 byte alignment */;
14459 
14460         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14461                                   APInt::getAllOnesValue(Bits /* alignment */)
14462                                       .zext(Add.getScalarValueSizeInBits()))) {
14463           SDNode *BasePtr = Add->getOperand(0).getNode();
14464           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14465                                     UE = BasePtr->use_end();
14466                UI != UE; ++UI) {
14467             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14468                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14469                     IID) {
14470               // We've found another LVSL/LVSR, and this address is an aligned
14471               // multiple of that one. The results will be the same, so use the
14472               // one we've just found instead.
14473 
14474               return SDValue(*UI, 0);
14475             }
14476           }
14477         }
14478 
14479         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14480           SDNode *BasePtr = Add->getOperand(0).getNode();
14481           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14482                UE = BasePtr->use_end(); UI != UE; ++UI) {
14483             if (UI->getOpcode() == ISD::ADD &&
14484                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14485                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14486                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14487                 (1ULL << Bits) == 0) {
14488               SDNode *OtherAdd = *UI;
14489               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14490                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14491                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14492                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14493                   return SDValue(*VI, 0);
14494                 }
14495               }
14496             }
14497           }
14498         }
14499       }
14500 
14501       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14502       // Expose the vabsduw/h/b opportunity for down stream
14503       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14504           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14505            IID == Intrinsic::ppc_altivec_vmaxsh ||
14506            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14507         SDValue V1 = N->getOperand(1);
14508         SDValue V2 = N->getOperand(2);
14509         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14510              V1.getSimpleValueType() == MVT::v8i16 ||
14511              V1.getSimpleValueType() == MVT::v16i8) &&
14512             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14513           // (0-a, a)
14514           if (V1.getOpcode() == ISD::SUB &&
14515               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14516               V1.getOperand(1) == V2) {
14517             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14518           }
14519           // (a, 0-a)
14520           if (V2.getOpcode() == ISD::SUB &&
14521               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14522               V2.getOperand(1) == V1) {
14523             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14524           }
14525           // (x-y, y-x)
14526           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14527               V1.getOperand(0) == V2.getOperand(1) &&
14528               V1.getOperand(1) == V2.getOperand(0)) {
14529             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14530           }
14531         }
14532       }
14533     }
14534 
14535     break;
14536   case ISD::INTRINSIC_W_CHAIN:
14537     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14538     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14539     if (Subtarget.needsSwapsForVSXMemOps()) {
14540       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14541       default:
14542         break;
14543       case Intrinsic::ppc_vsx_lxvw4x:
14544       case Intrinsic::ppc_vsx_lxvd2x:
14545         return expandVSXLoadForLE(N, DCI);
14546       }
14547     }
14548     break;
14549   case ISD::INTRINSIC_VOID:
14550     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14551     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14552     if (Subtarget.needsSwapsForVSXMemOps()) {
14553       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14554       default:
14555         break;
14556       case Intrinsic::ppc_vsx_stxvw4x:
14557       case Intrinsic::ppc_vsx_stxvd2x:
14558         return expandVSXStoreForLE(N, DCI);
14559       }
14560     }
14561     break;
14562   case ISD::BSWAP:
14563     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14564     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14565         N->getOperand(0).hasOneUse() &&
14566         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14567          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14568           N->getValueType(0) == MVT::i64))) {
14569       SDValue Load = N->getOperand(0);
14570       LoadSDNode *LD = cast<LoadSDNode>(Load);
14571       // Create the byte-swapping load.
14572       SDValue Ops[] = {
14573         LD->getChain(),    // Chain
14574         LD->getBasePtr(),  // Ptr
14575         DAG.getValueType(N->getValueType(0)) // VT
14576       };
14577       SDValue BSLoad =
14578         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14579                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14580                                               MVT::i64 : MVT::i32, MVT::Other),
14581                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14582 
14583       // If this is an i16 load, insert the truncate.
14584       SDValue ResVal = BSLoad;
14585       if (N->getValueType(0) == MVT::i16)
14586         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14587 
14588       // First, combine the bswap away.  This makes the value produced by the
14589       // load dead.
14590       DCI.CombineTo(N, ResVal);
14591 
14592       // Next, combine the load away, we give it a bogus result value but a real
14593       // chain result.  The result value is dead because the bswap is dead.
14594       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14595 
14596       // Return N so it doesn't get rechecked!
14597       return SDValue(N, 0);
14598     }
14599     break;
14600   case PPCISD::VCMP:
14601     // If a VCMPo node already exists with exactly the same operands as this
14602     // node, use its result instead of this node (VCMPo computes both a CR6 and
14603     // a normal output).
14604     //
14605     if (!N->getOperand(0).hasOneUse() &&
14606         !N->getOperand(1).hasOneUse() &&
14607         !N->getOperand(2).hasOneUse()) {
14608 
14609       // Scan all of the users of the LHS, looking for VCMPo's that match.
14610       SDNode *VCMPoNode = nullptr;
14611 
14612       SDNode *LHSN = N->getOperand(0).getNode();
14613       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14614            UI != E; ++UI)
14615         if (UI->getOpcode() == PPCISD::VCMPo &&
14616             UI->getOperand(1) == N->getOperand(1) &&
14617             UI->getOperand(2) == N->getOperand(2) &&
14618             UI->getOperand(0) == N->getOperand(0)) {
14619           VCMPoNode = *UI;
14620           break;
14621         }
14622 
14623       // If there is no VCMPo node, or if the flag value has a single use, don't
14624       // transform this.
14625       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14626         break;
14627 
14628       // Look at the (necessarily single) use of the flag value.  If it has a
14629       // chain, this transformation is more complex.  Note that multiple things
14630       // could use the value result, which we should ignore.
14631       SDNode *FlagUser = nullptr;
14632       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14633            FlagUser == nullptr; ++UI) {
14634         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14635         SDNode *User = *UI;
14636         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14637           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14638             FlagUser = User;
14639             break;
14640           }
14641         }
14642       }
14643 
14644       // If the user is a MFOCRF instruction, we know this is safe.
14645       // Otherwise we give up for right now.
14646       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14647         return SDValue(VCMPoNode, 0);
14648     }
14649     break;
14650   case ISD::BRCOND: {
14651     SDValue Cond = N->getOperand(1);
14652     SDValue Target = N->getOperand(2);
14653 
14654     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14655         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14656           Intrinsic::loop_decrement) {
14657 
14658       // We now need to make the intrinsic dead (it cannot be instruction
14659       // selected).
14660       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14661       assert(Cond.getNode()->hasOneUse() &&
14662              "Counter decrement has more than one use");
14663 
14664       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14665                          N->getOperand(0), Target);
14666     }
14667   }
14668   break;
14669   case ISD::BR_CC: {
14670     // If this is a branch on an altivec predicate comparison, lower this so
14671     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14672     // lowering is done pre-legalize, because the legalizer lowers the predicate
14673     // compare down to code that is difficult to reassemble.
14674     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14675     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14676 
14677     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14678     // value. If so, pass-through the AND to get to the intrinsic.
14679     if (LHS.getOpcode() == ISD::AND &&
14680         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14681         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14682           Intrinsic::loop_decrement &&
14683         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14684         !isNullConstant(LHS.getOperand(1)))
14685       LHS = LHS.getOperand(0);
14686 
14687     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14688         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14689           Intrinsic::loop_decrement &&
14690         isa<ConstantSDNode>(RHS)) {
14691       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14692              "Counter decrement comparison is not EQ or NE");
14693 
14694       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14695       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14696                     (CC == ISD::SETNE && !Val);
14697 
14698       // We now need to make the intrinsic dead (it cannot be instruction
14699       // selected).
14700       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14701       assert(LHS.getNode()->hasOneUse() &&
14702              "Counter decrement has more than one use");
14703 
14704       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14705                          N->getOperand(0), N->getOperand(4));
14706     }
14707 
14708     int CompareOpc;
14709     bool isDot;
14710 
14711     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14712         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14713         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14714       assert(isDot && "Can't compare against a vector result!");
14715 
14716       // If this is a comparison against something other than 0/1, then we know
14717       // that the condition is never/always true.
14718       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14719       if (Val != 0 && Val != 1) {
14720         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14721           return N->getOperand(0);
14722         // Always !=, turn it into an unconditional branch.
14723         return DAG.getNode(ISD::BR, dl, MVT::Other,
14724                            N->getOperand(0), N->getOperand(4));
14725       }
14726 
14727       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14728 
14729       // Create the PPCISD altivec 'dot' comparison node.
14730       SDValue Ops[] = {
14731         LHS.getOperand(2),  // LHS of compare
14732         LHS.getOperand(3),  // RHS of compare
14733         DAG.getConstant(CompareOpc, dl, MVT::i32)
14734       };
14735       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14736       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14737 
14738       // Unpack the result based on how the target uses it.
14739       PPC::Predicate CompOpc;
14740       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14741       default:  // Can't happen, don't crash on invalid number though.
14742       case 0:   // Branch on the value of the EQ bit of CR6.
14743         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14744         break;
14745       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14746         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14747         break;
14748       case 2:   // Branch on the value of the LT bit of CR6.
14749         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14750         break;
14751       case 3:   // Branch on the inverted value of the LT bit of CR6.
14752         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14753         break;
14754       }
14755 
14756       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14757                          DAG.getConstant(CompOpc, dl, MVT::i32),
14758                          DAG.getRegister(PPC::CR6, MVT::i32),
14759                          N->getOperand(4), CompNode.getValue(1));
14760     }
14761     break;
14762   }
14763   case ISD::BUILD_VECTOR:
14764     return DAGCombineBuildVector(N, DCI);
14765   case ISD::ABS:
14766     return combineABS(N, DCI);
14767   case ISD::VSELECT:
14768     return combineVSelect(N, DCI);
14769   }
14770 
14771   return SDValue();
14772 }
14773 
14774 SDValue
14775 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14776                                  SelectionDAG &DAG,
14777                                  SmallVectorImpl<SDNode *> &Created) const {
14778   // fold (sdiv X, pow2)
14779   EVT VT = N->getValueType(0);
14780   if (VT == MVT::i64 && !Subtarget.isPPC64())
14781     return SDValue();
14782   if ((VT != MVT::i32 && VT != MVT::i64) ||
14783       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14784     return SDValue();
14785 
14786   SDLoc DL(N);
14787   SDValue N0 = N->getOperand(0);
14788 
14789   bool IsNegPow2 = (-Divisor).isPowerOf2();
14790   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14791   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14792 
14793   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14794   Created.push_back(Op.getNode());
14795 
14796   if (IsNegPow2) {
14797     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14798     Created.push_back(Op.getNode());
14799   }
14800 
14801   return Op;
14802 }
14803 
14804 //===----------------------------------------------------------------------===//
14805 // Inline Assembly Support
14806 //===----------------------------------------------------------------------===//
14807 
14808 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14809                                                       KnownBits &Known,
14810                                                       const APInt &DemandedElts,
14811                                                       const SelectionDAG &DAG,
14812                                                       unsigned Depth) const {
14813   Known.resetAll();
14814   switch (Op.getOpcode()) {
14815   default: break;
14816   case PPCISD::LBRX: {
14817     // lhbrx is known to have the top bits cleared out.
14818     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14819       Known.Zero = 0xFFFF0000;
14820     break;
14821   }
14822   case ISD::INTRINSIC_WO_CHAIN: {
14823     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14824     default: break;
14825     case Intrinsic::ppc_altivec_vcmpbfp_p:
14826     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14827     case Intrinsic::ppc_altivec_vcmpequb_p:
14828     case Intrinsic::ppc_altivec_vcmpequh_p:
14829     case Intrinsic::ppc_altivec_vcmpequw_p:
14830     case Intrinsic::ppc_altivec_vcmpequd_p:
14831     case Intrinsic::ppc_altivec_vcmpgefp_p:
14832     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14833     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14834     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14835     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14836     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14837     case Intrinsic::ppc_altivec_vcmpgtub_p:
14838     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14839     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14840     case Intrinsic::ppc_altivec_vcmpgtud_p:
14841       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14842       break;
14843     }
14844   }
14845   }
14846 }
14847 
14848 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14849   switch (Subtarget.getCPUDirective()) {
14850   default: break;
14851   case PPC::DIR_970:
14852   case PPC::DIR_PWR4:
14853   case PPC::DIR_PWR5:
14854   case PPC::DIR_PWR5X:
14855   case PPC::DIR_PWR6:
14856   case PPC::DIR_PWR6X:
14857   case PPC::DIR_PWR7:
14858   case PPC::DIR_PWR8:
14859   case PPC::DIR_PWR9:
14860   case PPC::DIR_PWR10:
14861   case PPC::DIR_PWR_FUTURE: {
14862     if (!ML)
14863       break;
14864 
14865     if (!DisableInnermostLoopAlign32) {
14866       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14867       // so that we can decrease cache misses and branch-prediction misses.
14868       // Actual alignment of the loop will depend on the hotness check and other
14869       // logic in alignBlocks.
14870       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14871         return Align(32);
14872     }
14873 
14874     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14875 
14876     // For small loops (between 5 and 8 instructions), align to a 32-byte
14877     // boundary so that the entire loop fits in one instruction-cache line.
14878     uint64_t LoopSize = 0;
14879     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14880       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14881         LoopSize += TII->getInstSizeInBytes(*J);
14882         if (LoopSize > 32)
14883           break;
14884       }
14885 
14886     if (LoopSize > 16 && LoopSize <= 32)
14887       return Align(32);
14888 
14889     break;
14890   }
14891   }
14892 
14893   return TargetLowering::getPrefLoopAlignment(ML);
14894 }
14895 
14896 /// getConstraintType - Given a constraint, return the type of
14897 /// constraint it is for this target.
14898 PPCTargetLowering::ConstraintType
14899 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14900   if (Constraint.size() == 1) {
14901     switch (Constraint[0]) {
14902     default: break;
14903     case 'b':
14904     case 'r':
14905     case 'f':
14906     case 'd':
14907     case 'v':
14908     case 'y':
14909       return C_RegisterClass;
14910     case 'Z':
14911       // FIXME: While Z does indicate a memory constraint, it specifically
14912       // indicates an r+r address (used in conjunction with the 'y' modifier
14913       // in the replacement string). Currently, we're forcing the base
14914       // register to be r0 in the asm printer (which is interpreted as zero)
14915       // and forming the complete address in the second register. This is
14916       // suboptimal.
14917       return C_Memory;
14918     }
14919   } else if (Constraint == "wc") { // individual CR bits.
14920     return C_RegisterClass;
14921   } else if (Constraint == "wa" || Constraint == "wd" ||
14922              Constraint == "wf" || Constraint == "ws" ||
14923              Constraint == "wi" || Constraint == "ww") {
14924     return C_RegisterClass; // VSX registers.
14925   }
14926   return TargetLowering::getConstraintType(Constraint);
14927 }
14928 
14929 /// Examine constraint type and operand type and determine a weight value.
14930 /// This object must already have been set up with the operand type
14931 /// and the current alternative constraint selected.
14932 TargetLowering::ConstraintWeight
14933 PPCTargetLowering::getSingleConstraintMatchWeight(
14934     AsmOperandInfo &info, const char *constraint) const {
14935   ConstraintWeight weight = CW_Invalid;
14936   Value *CallOperandVal = info.CallOperandVal;
14937     // If we don't have a value, we can't do a match,
14938     // but allow it at the lowest weight.
14939   if (!CallOperandVal)
14940     return CW_Default;
14941   Type *type = CallOperandVal->getType();
14942 
14943   // Look at the constraint type.
14944   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14945     return CW_Register; // an individual CR bit.
14946   else if ((StringRef(constraint) == "wa" ||
14947             StringRef(constraint) == "wd" ||
14948             StringRef(constraint) == "wf") &&
14949            type->isVectorTy())
14950     return CW_Register;
14951   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14952     return CW_Register; // just hold 64-bit integers data.
14953   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14954     return CW_Register;
14955   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14956     return CW_Register;
14957 
14958   switch (*constraint) {
14959   default:
14960     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14961     break;
14962   case 'b':
14963     if (type->isIntegerTy())
14964       weight = CW_Register;
14965     break;
14966   case 'f':
14967     if (type->isFloatTy())
14968       weight = CW_Register;
14969     break;
14970   case 'd':
14971     if (type->isDoubleTy())
14972       weight = CW_Register;
14973     break;
14974   case 'v':
14975     if (type->isVectorTy())
14976       weight = CW_Register;
14977     break;
14978   case 'y':
14979     weight = CW_Register;
14980     break;
14981   case 'Z':
14982     weight = CW_Memory;
14983     break;
14984   }
14985   return weight;
14986 }
14987 
14988 std::pair<unsigned, const TargetRegisterClass *>
14989 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14990                                                 StringRef Constraint,
14991                                                 MVT VT) const {
14992   if (Constraint.size() == 1) {
14993     // GCC RS6000 Constraint Letters
14994     switch (Constraint[0]) {
14995     case 'b':   // R1-R31
14996       if (VT == MVT::i64 && Subtarget.isPPC64())
14997         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14998       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14999     case 'r':   // R0-R31
15000       if (VT == MVT::i64 && Subtarget.isPPC64())
15001         return std::make_pair(0U, &PPC::G8RCRegClass);
15002       return std::make_pair(0U, &PPC::GPRCRegClass);
15003     // 'd' and 'f' constraints are both defined to be "the floating point
15004     // registers", where one is for 32-bit and the other for 64-bit. We don't
15005     // really care overly much here so just give them all the same reg classes.
15006     case 'd':
15007     case 'f':
15008       if (Subtarget.hasSPE()) {
15009         if (VT == MVT::f32 || VT == MVT::i32)
15010           return std::make_pair(0U, &PPC::GPRCRegClass);
15011         if (VT == MVT::f64 || VT == MVT::i64)
15012           return std::make_pair(0U, &PPC::SPERCRegClass);
15013       } else {
15014         if (VT == MVT::f32 || VT == MVT::i32)
15015           return std::make_pair(0U, &PPC::F4RCRegClass);
15016         if (VT == MVT::f64 || VT == MVT::i64)
15017           return std::make_pair(0U, &PPC::F8RCRegClass);
15018       }
15019       break;
15020     case 'v':
15021       if (Subtarget.hasAltivec())
15022         return std::make_pair(0U, &PPC::VRRCRegClass);
15023       break;
15024     case 'y':   // crrc
15025       return std::make_pair(0U, &PPC::CRRCRegClass);
15026     }
15027   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15028     // An individual CR bit.
15029     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15030   } else if ((Constraint == "wa" || Constraint == "wd" ||
15031              Constraint == "wf" || Constraint == "wi") &&
15032              Subtarget.hasVSX()) {
15033     return std::make_pair(0U, &PPC::VSRCRegClass);
15034   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15035     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15036       return std::make_pair(0U, &PPC::VSSRCRegClass);
15037     else
15038       return std::make_pair(0U, &PPC::VSFRCRegClass);
15039   }
15040 
15041   // If we name a VSX register, we can't defer to the base class because it
15042   // will not recognize the correct register (their names will be VSL{0-31}
15043   // and V{0-31} so they won't match). So we match them here.
15044   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15045     int VSNum = atoi(Constraint.data() + 3);
15046     assert(VSNum >= 0 && VSNum <= 63 &&
15047            "Attempted to access a vsr out of range");
15048     if (VSNum < 32)
15049       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15050     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15051   }
15052   std::pair<unsigned, const TargetRegisterClass *> R =
15053       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15054 
15055   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15056   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15057   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15058   // register.
15059   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15060   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15061   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15062       PPC::GPRCRegClass.contains(R.first))
15063     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15064                             PPC::sub_32, &PPC::G8RCRegClass),
15065                           &PPC::G8RCRegClass);
15066 
15067   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15068   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15069     R.first = PPC::CR0;
15070     R.second = &PPC::CRRCRegClass;
15071   }
15072 
15073   return R;
15074 }
15075 
15076 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15077 /// vector.  If it is invalid, don't add anything to Ops.
15078 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15079                                                      std::string &Constraint,
15080                                                      std::vector<SDValue>&Ops,
15081                                                      SelectionDAG &DAG) const {
15082   SDValue Result;
15083 
15084   // Only support length 1 constraints.
15085   if (Constraint.length() > 1) return;
15086 
15087   char Letter = Constraint[0];
15088   switch (Letter) {
15089   default: break;
15090   case 'I':
15091   case 'J':
15092   case 'K':
15093   case 'L':
15094   case 'M':
15095   case 'N':
15096   case 'O':
15097   case 'P': {
15098     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15099     if (!CST) return; // Must be an immediate to match.
15100     SDLoc dl(Op);
15101     int64_t Value = CST->getSExtValue();
15102     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15103                          // numbers are printed as such.
15104     switch (Letter) {
15105     default: llvm_unreachable("Unknown constraint letter!");
15106     case 'I':  // "I" is a signed 16-bit constant.
15107       if (isInt<16>(Value))
15108         Result = DAG.getTargetConstant(Value, dl, TCVT);
15109       break;
15110     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15111       if (isShiftedUInt<16, 16>(Value))
15112         Result = DAG.getTargetConstant(Value, dl, TCVT);
15113       break;
15114     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15115       if (isShiftedInt<16, 16>(Value))
15116         Result = DAG.getTargetConstant(Value, dl, TCVT);
15117       break;
15118     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15119       if (isUInt<16>(Value))
15120         Result = DAG.getTargetConstant(Value, dl, TCVT);
15121       break;
15122     case 'M':  // "M" is a constant that is greater than 31.
15123       if (Value > 31)
15124         Result = DAG.getTargetConstant(Value, dl, TCVT);
15125       break;
15126     case 'N':  // "N" is a positive constant that is an exact power of two.
15127       if (Value > 0 && isPowerOf2_64(Value))
15128         Result = DAG.getTargetConstant(Value, dl, TCVT);
15129       break;
15130     case 'O':  // "O" is the constant zero.
15131       if (Value == 0)
15132         Result = DAG.getTargetConstant(Value, dl, TCVT);
15133       break;
15134     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15135       if (isInt<16>(-Value))
15136         Result = DAG.getTargetConstant(Value, dl, TCVT);
15137       break;
15138     }
15139     break;
15140   }
15141   }
15142 
15143   if (Result.getNode()) {
15144     Ops.push_back(Result);
15145     return;
15146   }
15147 
15148   // Handle standard constraint letters.
15149   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15150 }
15151 
15152 // isLegalAddressingMode - Return true if the addressing mode represented
15153 // by AM is legal for this target, for a load/store of the specified type.
15154 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15155                                               const AddrMode &AM, Type *Ty,
15156                                               unsigned AS,
15157                                               Instruction *I) const {
15158   // Vector type r+i form is supported since power9 as DQ form. We don't check
15159   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15160   // imm form is preferred and the offset can be adjusted to use imm form later
15161   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15162   // max offset to check legal addressing mode, we should be a little aggressive
15163   // to contain other offsets for that LSRUse.
15164   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15165     return false;
15166 
15167   // PPC allows a sign-extended 16-bit immediate field.
15168   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15169     return false;
15170 
15171   // No global is ever allowed as a base.
15172   if (AM.BaseGV)
15173     return false;
15174 
15175   // PPC only support r+r,
15176   switch (AM.Scale) {
15177   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15178     break;
15179   case 1:
15180     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15181       return false;
15182     // Otherwise we have r+r or r+i.
15183     break;
15184   case 2:
15185     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15186       return false;
15187     // Allow 2*r as r+r.
15188     break;
15189   default:
15190     // No other scales are supported.
15191     return false;
15192   }
15193 
15194   return true;
15195 }
15196 
15197 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15198                                            SelectionDAG &DAG) const {
15199   MachineFunction &MF = DAG.getMachineFunction();
15200   MachineFrameInfo &MFI = MF.getFrameInfo();
15201   MFI.setReturnAddressIsTaken(true);
15202 
15203   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15204     return SDValue();
15205 
15206   SDLoc dl(Op);
15207   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15208 
15209   // Make sure the function does not optimize away the store of the RA to
15210   // the stack.
15211   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15212   FuncInfo->setLRStoreRequired();
15213   bool isPPC64 = Subtarget.isPPC64();
15214   auto PtrVT = getPointerTy(MF.getDataLayout());
15215 
15216   if (Depth > 0) {
15217     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15218     SDValue Offset =
15219         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15220                         isPPC64 ? MVT::i64 : MVT::i32);
15221     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15222                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15223                        MachinePointerInfo());
15224   }
15225 
15226   // Just load the return address off the stack.
15227   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15228   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15229                      MachinePointerInfo());
15230 }
15231 
15232 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15233                                           SelectionDAG &DAG) const {
15234   SDLoc dl(Op);
15235   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15236 
15237   MachineFunction &MF = DAG.getMachineFunction();
15238   MachineFrameInfo &MFI = MF.getFrameInfo();
15239   MFI.setFrameAddressIsTaken(true);
15240 
15241   EVT PtrVT = getPointerTy(MF.getDataLayout());
15242   bool isPPC64 = PtrVT == MVT::i64;
15243 
15244   // Naked functions never have a frame pointer, and so we use r1. For all
15245   // other functions, this decision must be delayed until during PEI.
15246   unsigned FrameReg;
15247   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15248     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15249   else
15250     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15251 
15252   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15253                                          PtrVT);
15254   while (Depth--)
15255     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15256                             FrameAddr, MachinePointerInfo());
15257   return FrameAddr;
15258 }
15259 
15260 // FIXME? Maybe this could be a TableGen attribute on some registers and
15261 // this table could be generated automatically from RegInfo.
15262 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15263                                               const MachineFunction &MF) const {
15264   bool isPPC64 = Subtarget.isPPC64();
15265 
15266   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15267   if (!is64Bit && VT != LLT::scalar(32))
15268     report_fatal_error("Invalid register global variable type");
15269 
15270   Register Reg = StringSwitch<Register>(RegName)
15271                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15272                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15273                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15274                      .Default(Register());
15275 
15276   if (Reg)
15277     return Reg;
15278   report_fatal_error("Invalid register name global variable");
15279 }
15280 
15281 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15282   // 32-bit SVR4 ABI access everything as got-indirect.
15283   if (Subtarget.is32BitELFABI())
15284     return true;
15285 
15286   // AIX accesses everything indirectly through the TOC, which is similar to
15287   // the GOT.
15288   if (Subtarget.isAIXABI())
15289     return true;
15290 
15291   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15292   // If it is small or large code model, module locals are accessed
15293   // indirectly by loading their address from .toc/.got.
15294   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15295     return true;
15296 
15297   // JumpTable and BlockAddress are accessed as got-indirect.
15298   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15299     return true;
15300 
15301   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15302     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15303 
15304   return false;
15305 }
15306 
15307 bool
15308 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15309   // The PowerPC target isn't yet aware of offsets.
15310   return false;
15311 }
15312 
15313 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15314                                            const CallInst &I,
15315                                            MachineFunction &MF,
15316                                            unsigned Intrinsic) const {
15317   switch (Intrinsic) {
15318   case Intrinsic::ppc_altivec_lvx:
15319   case Intrinsic::ppc_altivec_lvxl:
15320   case Intrinsic::ppc_altivec_lvebx:
15321   case Intrinsic::ppc_altivec_lvehx:
15322   case Intrinsic::ppc_altivec_lvewx:
15323   case Intrinsic::ppc_vsx_lxvd2x:
15324   case Intrinsic::ppc_vsx_lxvw4x: {
15325     EVT VT;
15326     switch (Intrinsic) {
15327     case Intrinsic::ppc_altivec_lvebx:
15328       VT = MVT::i8;
15329       break;
15330     case Intrinsic::ppc_altivec_lvehx:
15331       VT = MVT::i16;
15332       break;
15333     case Intrinsic::ppc_altivec_lvewx:
15334       VT = MVT::i32;
15335       break;
15336     case Intrinsic::ppc_vsx_lxvd2x:
15337       VT = MVT::v2f64;
15338       break;
15339     default:
15340       VT = MVT::v4i32;
15341       break;
15342     }
15343 
15344     Info.opc = ISD::INTRINSIC_W_CHAIN;
15345     Info.memVT = VT;
15346     Info.ptrVal = I.getArgOperand(0);
15347     Info.offset = -VT.getStoreSize()+1;
15348     Info.size = 2*VT.getStoreSize()-1;
15349     Info.align = Align(1);
15350     Info.flags = MachineMemOperand::MOLoad;
15351     return true;
15352   }
15353   case Intrinsic::ppc_altivec_stvx:
15354   case Intrinsic::ppc_altivec_stvxl:
15355   case Intrinsic::ppc_altivec_stvebx:
15356   case Intrinsic::ppc_altivec_stvehx:
15357   case Intrinsic::ppc_altivec_stvewx:
15358   case Intrinsic::ppc_vsx_stxvd2x:
15359   case Intrinsic::ppc_vsx_stxvw4x: {
15360     EVT VT;
15361     switch (Intrinsic) {
15362     case Intrinsic::ppc_altivec_stvebx:
15363       VT = MVT::i8;
15364       break;
15365     case Intrinsic::ppc_altivec_stvehx:
15366       VT = MVT::i16;
15367       break;
15368     case Intrinsic::ppc_altivec_stvewx:
15369       VT = MVT::i32;
15370       break;
15371     case Intrinsic::ppc_vsx_stxvd2x:
15372       VT = MVT::v2f64;
15373       break;
15374     default:
15375       VT = MVT::v4i32;
15376       break;
15377     }
15378 
15379     Info.opc = ISD::INTRINSIC_VOID;
15380     Info.memVT = VT;
15381     Info.ptrVal = I.getArgOperand(1);
15382     Info.offset = -VT.getStoreSize()+1;
15383     Info.size = 2*VT.getStoreSize()-1;
15384     Info.align = Align(1);
15385     Info.flags = MachineMemOperand::MOStore;
15386     return true;
15387   }
15388   default:
15389     break;
15390   }
15391 
15392   return false;
15393 }
15394 
15395 /// It returns EVT::Other if the type should be determined using generic
15396 /// target-independent logic.
15397 EVT PPCTargetLowering::getOptimalMemOpType(
15398     const MemOp &Op, const AttributeList &FuncAttributes) const {
15399   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15400     // We should use Altivec/VSX loads and stores when available. For unaligned
15401     // addresses, unaligned VSX loads are only fast starting with the P8.
15402     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15403         (Op.isAligned(Align(16)) ||
15404          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15405       return MVT::v4i32;
15406   }
15407 
15408   if (Subtarget.isPPC64()) {
15409     return MVT::i64;
15410   }
15411 
15412   return MVT::i32;
15413 }
15414 
15415 /// Returns true if it is beneficial to convert a load of a constant
15416 /// to just the constant itself.
15417 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15418                                                           Type *Ty) const {
15419   assert(Ty->isIntegerTy());
15420 
15421   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15422   return !(BitSize == 0 || BitSize > 64);
15423 }
15424 
15425 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15426   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15427     return false;
15428   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15429   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15430   return NumBits1 == 64 && NumBits2 == 32;
15431 }
15432 
15433 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15434   if (!VT1.isInteger() || !VT2.isInteger())
15435     return false;
15436   unsigned NumBits1 = VT1.getSizeInBits();
15437   unsigned NumBits2 = VT2.getSizeInBits();
15438   return NumBits1 == 64 && NumBits2 == 32;
15439 }
15440 
15441 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15442   // Generally speaking, zexts are not free, but they are free when they can be
15443   // folded with other operations.
15444   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15445     EVT MemVT = LD->getMemoryVT();
15446     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15447          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15448         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15449          LD->getExtensionType() == ISD::ZEXTLOAD))
15450       return true;
15451   }
15452 
15453   // FIXME: Add other cases...
15454   //  - 32-bit shifts with a zext to i64
15455   //  - zext after ctlz, bswap, etc.
15456   //  - zext after and by a constant mask
15457 
15458   return TargetLowering::isZExtFree(Val, VT2);
15459 }
15460 
15461 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15462   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15463          "invalid fpext types");
15464   // Extending to float128 is not free.
15465   if (DestVT == MVT::f128)
15466     return false;
15467   return true;
15468 }
15469 
15470 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15471   return isInt<16>(Imm) || isUInt<16>(Imm);
15472 }
15473 
15474 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15475   return isInt<16>(Imm) || isUInt<16>(Imm);
15476 }
15477 
15478 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15479                                                        unsigned,
15480                                                        unsigned,
15481                                                        MachineMemOperand::Flags,
15482                                                        bool *Fast) const {
15483   if (DisablePPCUnaligned)
15484     return false;
15485 
15486   // PowerPC supports unaligned memory access for simple non-vector types.
15487   // Although accessing unaligned addresses is not as efficient as accessing
15488   // aligned addresses, it is generally more efficient than manual expansion,
15489   // and generally only traps for software emulation when crossing page
15490   // boundaries.
15491 
15492   if (!VT.isSimple())
15493     return false;
15494 
15495   if (VT.isFloatingPoint() && !VT.isVector() &&
15496       !Subtarget.allowsUnalignedFPAccess())
15497     return false;
15498 
15499   if (VT.getSimpleVT().isVector()) {
15500     if (Subtarget.hasVSX()) {
15501       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15502           VT != MVT::v4f32 && VT != MVT::v4i32)
15503         return false;
15504     } else {
15505       return false;
15506     }
15507   }
15508 
15509   if (VT == MVT::ppcf128)
15510     return false;
15511 
15512   if (Fast)
15513     *Fast = true;
15514 
15515   return true;
15516 }
15517 
15518 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15519                                                    EVT VT) const {
15520   return isFMAFasterThanFMulAndFAdd(
15521       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15522 }
15523 
15524 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15525                                                    Type *Ty) const {
15526   switch (Ty->getScalarType()->getTypeID()) {
15527   case Type::FloatTyID:
15528   case Type::DoubleTyID:
15529     return true;
15530   case Type::FP128TyID:
15531     return Subtarget.hasP9Vector();
15532   default:
15533     return false;
15534   }
15535 }
15536 
15537 // FIXME: add more patterns which are not profitable to hoist.
15538 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15539   if (!I->hasOneUse())
15540     return true;
15541 
15542   Instruction *User = I->user_back();
15543   assert(User && "A single use instruction with no uses.");
15544 
15545   switch (I->getOpcode()) {
15546   case Instruction::FMul: {
15547     // Don't break FMA, PowerPC prefers FMA.
15548     if (User->getOpcode() != Instruction::FSub &&
15549         User->getOpcode() != Instruction::FAdd)
15550       return true;
15551 
15552     const TargetOptions &Options = getTargetMachine().Options;
15553     const Function *F = I->getFunction();
15554     const DataLayout &DL = F->getParent()->getDataLayout();
15555     Type *Ty = User->getOperand(0)->getType();
15556 
15557     return !(
15558         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15559         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15560         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15561   }
15562   case Instruction::Load: {
15563     // Don't break "store (load float*)" pattern, this pattern will be combined
15564     // to "store (load int32)" in later InstCombine pass. See function
15565     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15566     // cycles than loading a 32 bit integer.
15567     LoadInst *LI = cast<LoadInst>(I);
15568     // For the loads that combineLoadToOperationType does nothing, like
15569     // ordered load, it should be profitable to hoist them.
15570     // For swifterror load, it can only be used for pointer to pointer type, so
15571     // later type check should get rid of this case.
15572     if (!LI->isUnordered())
15573       return true;
15574 
15575     if (User->getOpcode() != Instruction::Store)
15576       return true;
15577 
15578     if (I->getType()->getTypeID() != Type::FloatTyID)
15579       return true;
15580 
15581     return false;
15582   }
15583   default:
15584     return true;
15585   }
15586   return true;
15587 }
15588 
15589 const MCPhysReg *
15590 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15591   // LR is a callee-save register, but we must treat it as clobbered by any call
15592   // site. Hence we include LR in the scratch registers, which are in turn added
15593   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15594   // to CTR, which is used by any indirect call.
15595   static const MCPhysReg ScratchRegs[] = {
15596     PPC::X12, PPC::LR8, PPC::CTR8, 0
15597   };
15598 
15599   return ScratchRegs;
15600 }
15601 
15602 Register PPCTargetLowering::getExceptionPointerRegister(
15603     const Constant *PersonalityFn) const {
15604   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15605 }
15606 
15607 Register PPCTargetLowering::getExceptionSelectorRegister(
15608     const Constant *PersonalityFn) const {
15609   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15610 }
15611 
15612 bool
15613 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15614                      EVT VT , unsigned DefinedValues) const {
15615   if (VT == MVT::v2i64)
15616     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15617 
15618   if (Subtarget.hasVSX())
15619     return true;
15620 
15621   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15622 }
15623 
15624 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15625   if (DisableILPPref || Subtarget.enableMachineScheduler())
15626     return TargetLowering::getSchedulingPreference(N);
15627 
15628   return Sched::ILP;
15629 }
15630 
15631 // Create a fast isel object.
15632 FastISel *
15633 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15634                                   const TargetLibraryInfo *LibInfo) const {
15635   return PPC::createFastISel(FuncInfo, LibInfo);
15636 }
15637 
15638 // 'Inverted' means the FMA opcode after negating one multiplicand.
15639 // For example, (fma -a b c) = (fnmsub a b c)
15640 static unsigned invertFMAOpcode(unsigned Opc) {
15641   switch (Opc) {
15642   default:
15643     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15644   case ISD::FMA:
15645     return PPCISD::FNMSUB;
15646   case PPCISD::FNMSUB:
15647     return ISD::FMA;
15648   }
15649 }
15650 
15651 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15652                                                 bool LegalOps, bool OptForSize,
15653                                                 NegatibleCost &Cost,
15654                                                 unsigned Depth) const {
15655   if (Depth > SelectionDAG::MaxRecursionDepth)
15656     return SDValue();
15657 
15658   unsigned Opc = Op.getOpcode();
15659   EVT VT = Op.getValueType();
15660   SDNodeFlags Flags = Op.getNode()->getFlags();
15661 
15662   switch (Opc) {
15663   case PPCISD::FNMSUB:
15664     if (!Op.hasOneUse() || !isTypeLegal(VT))
15665       break;
15666 
15667     const TargetOptions &Options = getTargetMachine().Options;
15668     SDValue N0 = Op.getOperand(0);
15669     SDValue N1 = Op.getOperand(1);
15670     SDValue N2 = Op.getOperand(2);
15671     SDLoc Loc(Op);
15672 
15673     NegatibleCost N2Cost = NegatibleCost::Expensive;
15674     SDValue NegN2 =
15675         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15676 
15677     if (!NegN2)
15678       return SDValue();
15679 
15680     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15681     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15682     // These transformations may change sign of zeroes. For example,
15683     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15684     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15685       // Try and choose the cheaper one to negate.
15686       NegatibleCost N0Cost = NegatibleCost::Expensive;
15687       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15688                                            N0Cost, Depth + 1);
15689 
15690       NegatibleCost N1Cost = NegatibleCost::Expensive;
15691       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15692                                            N1Cost, Depth + 1);
15693 
15694       if (NegN0 && N0Cost <= N1Cost) {
15695         Cost = std::min(N0Cost, N2Cost);
15696         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15697       } else if (NegN1) {
15698         Cost = std::min(N1Cost, N2Cost);
15699         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15700       }
15701     }
15702 
15703     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15704     if (isOperationLegal(ISD::FMA, VT)) {
15705       Cost = N2Cost;
15706       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15707     }
15708 
15709     break;
15710   }
15711 
15712   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15713                                               Cost, Depth);
15714 }
15715 
15716 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15717 bool PPCTargetLowering::useLoadStackGuardNode() const {
15718   if (!Subtarget.isTargetLinux())
15719     return TargetLowering::useLoadStackGuardNode();
15720   return true;
15721 }
15722 
15723 // Override to disable global variable loading on Linux.
15724 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15725   if (!Subtarget.isTargetLinux())
15726     return TargetLowering::insertSSPDeclarations(M);
15727 }
15728 
15729 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15730                                      bool ForCodeSize) const {
15731   if (!VT.isSimple() || !Subtarget.hasVSX())
15732     return false;
15733 
15734   switch(VT.getSimpleVT().SimpleTy) {
15735   default:
15736     // For FP types that are currently not supported by PPC backend, return
15737     // false. Examples: f16, f80.
15738     return false;
15739   case MVT::f32:
15740   case MVT::f64:
15741     if (Subtarget.hasPrefixInstrs()) {
15742       // With prefixed instructions, we can materialize anything that can be
15743       // represented with a 32-bit immediate, not just positive zero.
15744       APFloat APFloatOfImm = Imm;
15745       return convertToNonDenormSingle(APFloatOfImm);
15746     }
15747     LLVM_FALLTHROUGH;
15748   case MVT::ppcf128:
15749     return Imm.isPosZero();
15750   }
15751 }
15752 
15753 // For vector shift operation op, fold
15754 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15755 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15756                                   SelectionDAG &DAG) {
15757   SDValue N0 = N->getOperand(0);
15758   SDValue N1 = N->getOperand(1);
15759   EVT VT = N0.getValueType();
15760   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15761   unsigned Opcode = N->getOpcode();
15762   unsigned TargetOpcode;
15763 
15764   switch (Opcode) {
15765   default:
15766     llvm_unreachable("Unexpected shift operation");
15767   case ISD::SHL:
15768     TargetOpcode = PPCISD::SHL;
15769     break;
15770   case ISD::SRL:
15771     TargetOpcode = PPCISD::SRL;
15772     break;
15773   case ISD::SRA:
15774     TargetOpcode = PPCISD::SRA;
15775     break;
15776   }
15777 
15778   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15779       N1->getOpcode() == ISD::AND)
15780     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15781       if (Mask->getZExtValue() == OpSizeInBits - 1)
15782         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15783 
15784   return SDValue();
15785 }
15786 
15787 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15788   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15789     return Value;
15790 
15791   SDValue N0 = N->getOperand(0);
15792   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15793   if (!Subtarget.isISA3_0() ||
15794       N0.getOpcode() != ISD::SIGN_EXTEND ||
15795       N0.getOperand(0).getValueType() != MVT::i32 ||
15796       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15797     return SDValue();
15798 
15799   // We can't save an operation here if the value is already extended, and
15800   // the existing shift is easier to combine.
15801   SDValue ExtsSrc = N0.getOperand(0);
15802   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15803       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15804     return SDValue();
15805 
15806   SDLoc DL(N0);
15807   SDValue ShiftBy = SDValue(CN1, 0);
15808   // We want the shift amount to be i32 on the extswli, but the shift could
15809   // have an i64.
15810   if (ShiftBy.getValueType() == MVT::i64)
15811     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15812 
15813   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15814                          ShiftBy);
15815 }
15816 
15817 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15818   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15819     return Value;
15820 
15821   return SDValue();
15822 }
15823 
15824 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15825   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15826     return Value;
15827 
15828   return SDValue();
15829 }
15830 
15831 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15832 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15833 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15834 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15835 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15836                                  const PPCSubtarget &Subtarget) {
15837   if (!Subtarget.isPPC64())
15838     return SDValue();
15839 
15840   SDValue LHS = N->getOperand(0);
15841   SDValue RHS = N->getOperand(1);
15842 
15843   auto isZextOfCompareWithConstant = [](SDValue Op) {
15844     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15845         Op.getValueType() != MVT::i64)
15846       return false;
15847 
15848     SDValue Cmp = Op.getOperand(0);
15849     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15850         Cmp.getOperand(0).getValueType() != MVT::i64)
15851       return false;
15852 
15853     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15854       int64_t NegConstant = 0 - Constant->getSExtValue();
15855       // Due to the limitations of the addi instruction,
15856       // -C is required to be [-32768, 32767].
15857       return isInt<16>(NegConstant);
15858     }
15859 
15860     return false;
15861   };
15862 
15863   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15864   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15865 
15866   // If there is a pattern, canonicalize a zext operand to the RHS.
15867   if (LHSHasPattern && !RHSHasPattern)
15868     std::swap(LHS, RHS);
15869   else if (!LHSHasPattern && !RHSHasPattern)
15870     return SDValue();
15871 
15872   SDLoc DL(N);
15873   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15874   SDValue Cmp = RHS.getOperand(0);
15875   SDValue Z = Cmp.getOperand(0);
15876   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15877 
15878   assert(Constant && "Constant Should not be a null pointer.");
15879   int64_t NegConstant = 0 - Constant->getSExtValue();
15880 
15881   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15882   default: break;
15883   case ISD::SETNE: {
15884     //                                 when C == 0
15885     //                             --> addze X, (addic Z, -1).carry
15886     //                            /
15887     // add X, (zext(setne Z, C))--
15888     //                            \    when -32768 <= -C <= 32767 && C != 0
15889     //                             --> addze X, (addic (addi Z, -C), -1).carry
15890     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15891                               DAG.getConstant(NegConstant, DL, MVT::i64));
15892     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15893     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15894                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15895     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15896                        SDValue(Addc.getNode(), 1));
15897     }
15898   case ISD::SETEQ: {
15899     //                                 when C == 0
15900     //                             --> addze X, (subfic Z, 0).carry
15901     //                            /
15902     // add X, (zext(sete  Z, C))--
15903     //                            \    when -32768 <= -C <= 32767 && C != 0
15904     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15905     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15906                               DAG.getConstant(NegConstant, DL, MVT::i64));
15907     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15908     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15909                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15910     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15911                        SDValue(Subc.getNode(), 1));
15912     }
15913   }
15914 
15915   return SDValue();
15916 }
15917 
15918 // Transform
15919 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
15920 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
15921 // In this case both C1 and C2 must be known constants.
15922 // C1+C2 must fit into a 34 bit signed integer.
15923 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
15924                                           const PPCSubtarget &Subtarget) {
15925   if (!Subtarget.isUsingPCRelativeCalls())
15926     return SDValue();
15927 
15928   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
15929   // If we find that node try to cast the Global Address and the Constant.
15930   SDValue LHS = N->getOperand(0);
15931   SDValue RHS = N->getOperand(1);
15932 
15933   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15934     std::swap(LHS, RHS);
15935 
15936   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15937     return SDValue();
15938 
15939   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
15940   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
15941   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
15942 
15943   // Check that both casts succeeded.
15944   if (!GSDN || !ConstNode)
15945     return SDValue();
15946 
15947   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
15948   SDLoc DL(GSDN);
15949 
15950   // The signed int offset needs to fit in 34 bits.
15951   if (!isInt<34>(NewOffset))
15952     return SDValue();
15953 
15954   // The new global address is a copy of the old global address except
15955   // that it has the updated Offset.
15956   SDValue GA =
15957       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
15958                                  NewOffset, GSDN->getTargetFlags());
15959   SDValue MatPCRel =
15960       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
15961   return MatPCRel;
15962 }
15963 
15964 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15965   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15966     return Value;
15967 
15968   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
15969     return Value;
15970 
15971   return SDValue();
15972 }
15973 
15974 // Detect TRUNCATE operations on bitcasts of float128 values.
15975 // What we are looking for here is the situtation where we extract a subset
15976 // of bits from a 128 bit float.
15977 // This can be of two forms:
15978 // 1) BITCAST of f128 feeding TRUNCATE
15979 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15980 // The reason this is required is because we do not have a legal i128 type
15981 // and so we want to prevent having to store the f128 and then reload part
15982 // of it.
15983 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15984                                            DAGCombinerInfo &DCI) const {
15985   // If we are using CRBits then try that first.
15986   if (Subtarget.useCRBits()) {
15987     // Check if CRBits did anything and return that if it did.
15988     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15989       return CRTruncValue;
15990   }
15991 
15992   SDLoc dl(N);
15993   SDValue Op0 = N->getOperand(0);
15994 
15995   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
15996   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
15997     EVT VT = N->getValueType(0);
15998     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15999       return SDValue();
16000     SDValue Sub = Op0.getOperand(0);
16001     if (Sub.getOpcode() == ISD::SUB) {
16002       SDValue SubOp0 = Sub.getOperand(0);
16003       SDValue SubOp1 = Sub.getOperand(1);
16004       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16005           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16006         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16007                                SubOp1.getOperand(0),
16008                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16009       }
16010     }
16011   }
16012 
16013   // Looking for a truncate of i128 to i64.
16014   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16015     return SDValue();
16016 
16017   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16018 
16019   // SRL feeding TRUNCATE.
16020   if (Op0.getOpcode() == ISD::SRL) {
16021     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16022     // The right shift has to be by 64 bits.
16023     if (!ConstNode || ConstNode->getZExtValue() != 64)
16024       return SDValue();
16025 
16026     // Switch the element number to extract.
16027     EltToExtract = EltToExtract ? 0 : 1;
16028     // Update Op0 past the SRL.
16029     Op0 = Op0.getOperand(0);
16030   }
16031 
16032   // BITCAST feeding a TRUNCATE possibly via SRL.
16033   if (Op0.getOpcode() == ISD::BITCAST &&
16034       Op0.getValueType() == MVT::i128 &&
16035       Op0.getOperand(0).getValueType() == MVT::f128) {
16036     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16037     return DCI.DAG.getNode(
16038         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16039         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16040   }
16041   return SDValue();
16042 }
16043 
16044 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16045   SelectionDAG &DAG = DCI.DAG;
16046 
16047   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16048   if (!ConstOpOrElement)
16049     return SDValue();
16050 
16051   // An imul is usually smaller than the alternative sequence for legal type.
16052   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16053       isOperationLegal(ISD::MUL, N->getValueType(0)))
16054     return SDValue();
16055 
16056   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16057     switch (this->Subtarget.getCPUDirective()) {
16058     default:
16059       // TODO: enhance the condition for subtarget before pwr8
16060       return false;
16061     case PPC::DIR_PWR8:
16062       //  type        mul     add    shl
16063       // scalar        4       1      1
16064       // vector        7       2      2
16065       return true;
16066     case PPC::DIR_PWR9:
16067     case PPC::DIR_PWR10:
16068     case PPC::DIR_PWR_FUTURE:
16069       //  type        mul     add    shl
16070       // scalar        5       2      2
16071       // vector        7       2      2
16072 
16073       // The cycle RATIO of related operations are showed as a table above.
16074       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16075       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16076       // are 4, it is always profitable; but for 3 instrs patterns
16077       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16078       // So we should only do it for vector type.
16079       return IsAddOne && IsNeg ? VT.isVector() : true;
16080     }
16081   };
16082 
16083   EVT VT = N->getValueType(0);
16084   SDLoc DL(N);
16085 
16086   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16087   bool IsNeg = MulAmt.isNegative();
16088   APInt MulAmtAbs = MulAmt.abs();
16089 
16090   if ((MulAmtAbs - 1).isPowerOf2()) {
16091     // (mul x, 2^N + 1) => (add (shl x, N), x)
16092     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16093 
16094     if (!IsProfitable(IsNeg, true, VT))
16095       return SDValue();
16096 
16097     SDValue Op0 = N->getOperand(0);
16098     SDValue Op1 =
16099         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16100                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16101     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16102 
16103     if (!IsNeg)
16104       return Res;
16105 
16106     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16107   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16108     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16109     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16110 
16111     if (!IsProfitable(IsNeg, false, VT))
16112       return SDValue();
16113 
16114     SDValue Op0 = N->getOperand(0);
16115     SDValue Op1 =
16116         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16117                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16118 
16119     if (!IsNeg)
16120       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16121     else
16122       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16123 
16124   } else {
16125     return SDValue();
16126   }
16127 }
16128 
16129 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16130 // in combiner since we need to check SD flags and other subtarget features.
16131 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16132                                           DAGCombinerInfo &DCI) const {
16133   SDValue N0 = N->getOperand(0);
16134   SDValue N1 = N->getOperand(1);
16135   SDValue N2 = N->getOperand(2);
16136   SDNodeFlags Flags = N->getFlags();
16137   EVT VT = N->getValueType(0);
16138   SelectionDAG &DAG = DCI.DAG;
16139   const TargetOptions &Options = getTargetMachine().Options;
16140   unsigned Opc = N->getOpcode();
16141   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16142   bool LegalOps = !DCI.isBeforeLegalizeOps();
16143   SDLoc Loc(N);
16144 
16145   if (!isOperationLegal(ISD::FMA, VT))
16146     return SDValue();
16147 
16148   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16149   // since (fnmsub a b c)=-0 while c-ab=+0.
16150   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16151     return SDValue();
16152 
16153   // (fma (fneg a) b c) => (fnmsub a b c)
16154   // (fnmsub (fneg a) b c) => (fma a b c)
16155   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16156     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16157 
16158   // (fma a (fneg b) c) => (fnmsub a b c)
16159   // (fnmsub a (fneg b) c) => (fma a b c)
16160   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16161     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16162 
16163   return SDValue();
16164 }
16165 
16166 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16167   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16168   if (!Subtarget.is64BitELFABI())
16169     return false;
16170 
16171   // If not a tail call then no need to proceed.
16172   if (!CI->isTailCall())
16173     return false;
16174 
16175   // If sibling calls have been disabled and tail-calls aren't guaranteed
16176   // there is no reason to duplicate.
16177   auto &TM = getTargetMachine();
16178   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16179     return false;
16180 
16181   // Can't tail call a function called indirectly, or if it has variadic args.
16182   const Function *Callee = CI->getCalledFunction();
16183   if (!Callee || Callee->isVarArg())
16184     return false;
16185 
16186   // Make sure the callee and caller calling conventions are eligible for tco.
16187   const Function *Caller = CI->getParent()->getParent();
16188   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16189                                            CI->getCallingConv()))
16190       return false;
16191 
16192   // If the function is local then we have a good chance at tail-calling it
16193   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16194 }
16195 
16196 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16197   if (!Subtarget.hasVSX())
16198     return false;
16199   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16200     return true;
16201   return VT == MVT::f32 || VT == MVT::f64 ||
16202     VT == MVT::v4f32 || VT == MVT::v2f64;
16203 }
16204 
16205 bool PPCTargetLowering::
16206 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16207   const Value *Mask = AndI.getOperand(1);
16208   // If the mask is suitable for andi. or andis. we should sink the and.
16209   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16210     // Can't handle constants wider than 64-bits.
16211     if (CI->getBitWidth() > 64)
16212       return false;
16213     int64_t ConstVal = CI->getZExtValue();
16214     return isUInt<16>(ConstVal) ||
16215       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16216   }
16217 
16218   // For non-constant masks, we can always use the record-form and.
16219   return true;
16220 }
16221 
16222 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16223 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16224 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16225 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16226 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16227 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16228   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16229   assert(Subtarget.hasP9Altivec() &&
16230          "Only combine this when P9 altivec supported!");
16231   EVT VT = N->getValueType(0);
16232   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16233     return SDValue();
16234 
16235   SelectionDAG &DAG = DCI.DAG;
16236   SDLoc dl(N);
16237   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16238     // Even for signed integers, if it's known to be positive (as signed
16239     // integer) due to zero-extended inputs.
16240     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16241     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16242     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16243          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16244         (SubOpcd1 == ISD::ZERO_EXTEND ||
16245          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16246       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16247                          N->getOperand(0)->getOperand(0),
16248                          N->getOperand(0)->getOperand(1),
16249                          DAG.getTargetConstant(0, dl, MVT::i32));
16250     }
16251 
16252     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16253     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16254         N->getOperand(0).hasOneUse()) {
16255       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16256                          N->getOperand(0)->getOperand(0),
16257                          N->getOperand(0)->getOperand(1),
16258                          DAG.getTargetConstant(1, dl, MVT::i32));
16259     }
16260   }
16261 
16262   return SDValue();
16263 }
16264 
16265 // For type v4i32/v8ii16/v16i8, transform
16266 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16267 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16268 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16269 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16270 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16271                                           DAGCombinerInfo &DCI) const {
16272   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16273   assert(Subtarget.hasP9Altivec() &&
16274          "Only combine this when P9 altivec supported!");
16275 
16276   SelectionDAG &DAG = DCI.DAG;
16277   SDLoc dl(N);
16278   SDValue Cond = N->getOperand(0);
16279   SDValue TrueOpnd = N->getOperand(1);
16280   SDValue FalseOpnd = N->getOperand(2);
16281   EVT VT = N->getOperand(1).getValueType();
16282 
16283   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16284       FalseOpnd.getOpcode() != ISD::SUB)
16285     return SDValue();
16286 
16287   // ABSD only available for type v4i32/v8i16/v16i8
16288   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16289     return SDValue();
16290 
16291   // At least to save one more dependent computation
16292   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16293     return SDValue();
16294 
16295   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16296 
16297   // Can only handle unsigned comparison here
16298   switch (CC) {
16299   default:
16300     return SDValue();
16301   case ISD::SETUGT:
16302   case ISD::SETUGE:
16303     break;
16304   case ISD::SETULT:
16305   case ISD::SETULE:
16306     std::swap(TrueOpnd, FalseOpnd);
16307     break;
16308   }
16309 
16310   SDValue CmpOpnd1 = Cond.getOperand(0);
16311   SDValue CmpOpnd2 = Cond.getOperand(1);
16312 
16313   // SETCC CmpOpnd1 CmpOpnd2 cond
16314   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16315   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16316   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16317       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16318       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16319       FalseOpnd.getOperand(1) == CmpOpnd1) {
16320     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16321                        CmpOpnd1, CmpOpnd2,
16322                        DAG.getTargetConstant(0, dl, MVT::i32));
16323   }
16324 
16325   return SDValue();
16326 }
16327