523d6eb0c2c14b276c57c15d133d512a2f375c08
[oota-llvm.git] / lib / Target / Hexagon / HexagonISelDAGToDAG.cpp
1 //===-- HexagonISelDAGToDAG.cpp - A dag to dag inst selector for Hexagon --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the Hexagon target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Hexagon.h"
15 #include "HexagonISelLowering.h"
16 #include "HexagonMachineFunctionInfo.h"
17 #include "HexagonTargetMachine.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/FunctionLoweringInfo.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/SelectionDAGISel.h"
22 #include "llvm/IR/Intrinsics.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Debug.h"
26 using namespace llvm;
27
28 #define DEBUG_TYPE "hexagon-isel"
29
30 static
31 cl::opt<unsigned>
32 MaxNumOfUsesForConstExtenders("ga-max-num-uses-for-constant-extenders",
33   cl::Hidden, cl::init(2),
34   cl::desc("Maximum number of uses of a global address such that we still us a"
35            "constant extended instruction"));
36
37 //===----------------------------------------------------------------------===//
38 // Instruction Selector Implementation
39 //===----------------------------------------------------------------------===//
40
41 namespace llvm {
42   void initializeHexagonDAGToDAGISelPass(PassRegistry&);
43 }
44
45 //===--------------------------------------------------------------------===//
46 /// HexagonDAGToDAGISel - Hexagon specific code to select Hexagon machine
47 /// instructions for SelectionDAG operations.
48 ///
49 namespace {
50 class HexagonDAGToDAGISel : public SelectionDAGISel {
51   const HexagonTargetMachine& HTM;
52   const HexagonSubtarget *HST;
53 public:
54   explicit HexagonDAGToDAGISel(HexagonTargetMachine &tm,
55                                CodeGenOpt::Level OptLevel)
56       : SelectionDAGISel(tm, OptLevel), HTM(tm) {
57     initializeHexagonDAGToDAGISelPass(*PassRegistry::getPassRegistry());
58   }
59
60   bool runOnMachineFunction(MachineFunction &MF) override {
61     // Reset the subtarget each time through.
62     HST = &MF.getSubtarget<HexagonSubtarget>();
63     SelectionDAGISel::runOnMachineFunction(MF);
64     return true;
65   }
66
67   virtual void PreprocessISelDAG() override;
68   virtual void EmitFunctionEntryCode() override;
69
70   SDNode *Select(SDNode *N) override;
71
72   // Complex Pattern Selectors.
73   inline bool SelectAddrGA(SDValue &N, SDValue &R);
74   inline bool SelectAddrGP(SDValue &N, SDValue &R);
75   bool SelectGlobalAddress(SDValue &N, SDValue &R, bool UseGP);
76   bool SelectAddrFI(SDValue &N, SDValue &R);
77
78   const char *getPassName() const override {
79     return "Hexagon DAG->DAG Pattern Instruction Selection";
80   }
81
82   SDNode *SelectFrameIndex(SDNode *N);
83   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
84   /// inline asm expressions.
85   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
86                                     unsigned ConstraintID,
87                                     std::vector<SDValue> &OutOps) override;
88   SDNode *SelectLoad(SDNode *N);
89   SDNode *SelectBaseOffsetLoad(LoadSDNode *LD, SDLoc dl);
90   SDNode *SelectIndexedLoad(LoadSDNode *LD, SDLoc dl);
91   SDNode *SelectIndexedLoadZeroExtend64(LoadSDNode *LD, unsigned Opcode,
92                                         SDLoc dl);
93   SDNode *SelectIndexedLoadSignExtend64(LoadSDNode *LD, unsigned Opcode,
94                                         SDLoc dl);
95   SDNode *SelectBaseOffsetStore(StoreSDNode *ST, SDLoc dl);
96   SDNode *SelectIndexedStore(StoreSDNode *ST, SDLoc dl);
97   SDNode *SelectStore(SDNode *N);
98   SDNode *SelectSHL(SDNode *N);
99   SDNode *SelectMul(SDNode *N);
100   SDNode *SelectZeroExtend(SDNode *N);
101   SDNode *SelectIntrinsicWChain(SDNode *N);
102   SDNode *SelectIntrinsicWOChain(SDNode *N);
103   SDNode *SelectConstant(SDNode *N);
104   SDNode *SelectConstantFP(SDNode *N);
105   SDNode *SelectAdd(SDNode *N);
106   SDNode *SelectBitOp(SDNode *N);
107   bool isConstExtProfitable(SDNode *N) const;
108
109   // XformMskToBitPosU5Imm - Returns the bit position which
110   // the single bit 32 bit mask represents.
111   // Used in Clr and Set bit immediate memops.
112   SDValue XformMskToBitPosU5Imm(uint32_t Imm, SDLoc DL) {
113     int32_t bitPos;
114     bitPos = Log2_32(Imm);
115     assert(bitPos >= 0 && bitPos < 32 &&
116            "Constant out of range for 32 BitPos Memops");
117     return CurDAG->getTargetConstant(bitPos, DL, MVT::i32);
118   }
119
120   // XformMskToBitPosU4Imm - Returns the bit position which the single-bit
121   // 16 bit mask represents. Used in Clr and Set bit immediate memops.
122   SDValue XformMskToBitPosU4Imm(uint16_t Imm, SDLoc DL) {
123     return XformMskToBitPosU5Imm(Imm, DL);
124   }
125
126   // XformMskToBitPosU3Imm - Returns the bit position which the single-bit
127   // 8 bit mask represents. Used in Clr and Set bit immediate memops.
128   SDValue XformMskToBitPosU3Imm(uint8_t Imm, SDLoc DL) {
129     return XformMskToBitPosU5Imm(Imm, DL);
130   }
131
132   // Return true if there is exactly one bit set in V, i.e., if V is one of the
133   // following integers: 2^0, 2^1, ..., 2^31.
134   bool ImmIsSingleBit(uint32_t v) const {
135     return isPowerOf2_32(v);
136   }
137
138   // XformM5ToU5Imm - Return a target constant with the specified value, of
139   // type i32 where the negative literal is transformed into a positive literal
140   // for use in -= memops.
141   inline SDValue XformM5ToU5Imm(signed Imm, SDLoc DL) {
142      assert( (Imm >= -31 && Imm <= -1)  && "Constant out of range for Memops");
143      return CurDAG->getTargetConstant( - Imm, DL, MVT::i32);
144   }
145
146   // XformU7ToU7M1Imm - Return a target constant decremented by 1, in range
147   // [1..128], used in cmpb.gtu instructions.
148   inline SDValue XformU7ToU7M1Imm(signed Imm, SDLoc DL) {
149     assert((Imm >= 1 && Imm <= 128) && "Constant out of range for cmpb op");
150     return CurDAG->getTargetConstant(Imm - 1, DL, MVT::i8);
151   }
152
153   // XformS8ToS8M1Imm - Return a target constant decremented by 1.
154   inline SDValue XformSToSM1Imm(signed Imm, SDLoc DL) {
155     return CurDAG->getTargetConstant(Imm - 1, DL, MVT::i32);
156   }
157
158   // XformU8ToU8M1Imm - Return a target constant decremented by 1.
159   inline SDValue XformUToUM1Imm(unsigned Imm, SDLoc DL) {
160     assert((Imm >= 1) && "Cannot decrement unsigned int less than 1");
161     return CurDAG->getTargetConstant(Imm - 1, DL, MVT::i32);
162   }
163
164   // XformSToSM2Imm - Return a target constant decremented by 2.
165   inline SDValue XformSToSM2Imm(unsigned Imm, SDLoc DL) {
166     return CurDAG->getTargetConstant(Imm - 2, DL, MVT::i32);
167   }
168
169   // XformSToSM3Imm - Return a target constant decremented by 3.
170   inline SDValue XformSToSM3Imm(unsigned Imm, SDLoc DL) {
171     return CurDAG->getTargetConstant(Imm - 3, DL, MVT::i32);
172   }
173
174   // Include the pieces autogenerated from the target description.
175   #include "HexagonGenDAGISel.inc"
176
177 private:
178   bool isValueExtension(const SDValue &Val, unsigned FromBits, SDValue &Src);
179 }; // end HexagonDAGToDAGISel
180 }  // end anonymous namespace
181
182
183 /// createHexagonISelDag - This pass converts a legalized DAG into a
184 /// Hexagon-specific DAG, ready for instruction scheduling.
185 ///
186 namespace llvm {
187 FunctionPass *createHexagonISelDag(HexagonTargetMachine &TM,
188                                    CodeGenOpt::Level OptLevel) {
189   return new HexagonDAGToDAGISel(TM, OptLevel);
190 }
191 }
192
193 static void initializePassOnce(PassRegistry &Registry) {
194   const char *Name = "Hexagon DAG->DAG Pattern Instruction Selection";
195   PassInfo *PI = new PassInfo(Name, "hexagon-isel",
196                               &SelectionDAGISel::ID, nullptr, false, false);
197   Registry.registerPass(*PI, true);
198 }
199
200 void llvm::initializeHexagonDAGToDAGISelPass(PassRegistry &Registry) {
201   CALL_ONCE_INITIALIZATION(initializePassOnce)
202 }
203
204
205 // Intrinsics that return a a predicate.
206 static unsigned doesIntrinsicReturnPredicate(unsigned ID)
207 {
208   switch (ID) {
209     default:
210       return 0;
211     case Intrinsic::hexagon_C2_cmpeq:
212     case Intrinsic::hexagon_C2_cmpgt:
213     case Intrinsic::hexagon_C2_cmpgtu:
214     case Intrinsic::hexagon_C2_cmpgtup:
215     case Intrinsic::hexagon_C2_cmpgtp:
216     case Intrinsic::hexagon_C2_cmpeqp:
217     case Intrinsic::hexagon_C2_bitsset:
218     case Intrinsic::hexagon_C2_bitsclr:
219     case Intrinsic::hexagon_C2_cmpeqi:
220     case Intrinsic::hexagon_C2_cmpgti:
221     case Intrinsic::hexagon_C2_cmpgtui:
222     case Intrinsic::hexagon_C2_cmpgei:
223     case Intrinsic::hexagon_C2_cmpgeui:
224     case Intrinsic::hexagon_C2_cmplt:
225     case Intrinsic::hexagon_C2_cmpltu:
226     case Intrinsic::hexagon_C2_bitsclri:
227     case Intrinsic::hexagon_C2_and:
228     case Intrinsic::hexagon_C2_or:
229     case Intrinsic::hexagon_C2_xor:
230     case Intrinsic::hexagon_C2_andn:
231     case Intrinsic::hexagon_C2_not:
232     case Intrinsic::hexagon_C2_orn:
233     case Intrinsic::hexagon_C2_pxfer_map:
234     case Intrinsic::hexagon_C2_any8:
235     case Intrinsic::hexagon_C2_all8:
236     case Intrinsic::hexagon_A2_vcmpbeq:
237     case Intrinsic::hexagon_A2_vcmpbgtu:
238     case Intrinsic::hexagon_A2_vcmpheq:
239     case Intrinsic::hexagon_A2_vcmphgt:
240     case Intrinsic::hexagon_A2_vcmphgtu:
241     case Intrinsic::hexagon_A2_vcmpweq:
242     case Intrinsic::hexagon_A2_vcmpwgt:
243     case Intrinsic::hexagon_A2_vcmpwgtu:
244     case Intrinsic::hexagon_C2_tfrrp:
245     case Intrinsic::hexagon_S2_tstbit_i:
246     case Intrinsic::hexagon_S2_tstbit_r:
247       return 1;
248   }
249 }
250
251 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadSignExtend64(LoadSDNode *LD,
252                                                            unsigned Opcode,
253                                                            SDLoc dl) {
254   SDValue Chain = LD->getChain();
255   EVT LoadedVT = LD->getMemoryVT();
256   SDValue Base = LD->getBasePtr();
257   SDValue Offset = LD->getOffset();
258   SDNode *OffsetNode = Offset.getNode();
259   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
260
261   const HexagonInstrInfo &TII = *HST->getInstrInfo();
262   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
263     SDValue TargetConst = CurDAG->getTargetConstant(Val, dl, MVT::i32);
264     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::i32,
265                                               MVT::Other, Base, TargetConst,
266                                               Chain);
267     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
268                                               SDValue(Result_1, 0));
269     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
270     MemOp[0] = LD->getMemOperand();
271     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
272     const SDValue Froms[] = { SDValue(LD, 0),
273                               SDValue(LD, 1),
274                               SDValue(LD, 2) };
275     const SDValue Tos[]   = { SDValue(Result_2, 0),
276                               SDValue(Result_1, 1),
277                               SDValue(Result_1, 2) };
278     ReplaceUses(Froms, Tos, 3);
279     return Result_2;
280   }
281
282   SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
283   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
284   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Other,
285                                             Base, TargetConst0, Chain);
286   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
287                                             SDValue(Result_1, 0));
288   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
289                                             Base, TargetConstVal,
290                                             SDValue(Result_1, 1));
291   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
292   MemOp[0] = LD->getMemOperand();
293   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
294   const SDValue Froms[] = { SDValue(LD, 0),
295                             SDValue(LD, 1),
296                             SDValue(LD, 2) };
297   const SDValue Tos[]   = { SDValue(Result_2, 0),
298                             SDValue(Result_3, 0),
299                             SDValue(Result_1, 1) };
300   ReplaceUses(Froms, Tos, 3);
301   return Result_2;
302 }
303
304
305 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadZeroExtend64(LoadSDNode *LD,
306                                                            unsigned Opcode,
307                                                            SDLoc dl) {
308   SDValue Chain = LD->getChain();
309   EVT LoadedVT = LD->getMemoryVT();
310   SDValue Base = LD->getBasePtr();
311   SDValue Offset = LD->getOffset();
312   SDNode *OffsetNode = Offset.getNode();
313   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
314
315   const HexagonInstrInfo &TII = *HST->getInstrInfo();
316   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
317     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
318     SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
319     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
320                                               MVT::i32, MVT::Other, Base,
321                                               TargetConstVal, Chain);
322     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
323                                               MVT::i64, MVT::Other,
324                                               TargetConst0,
325                                               SDValue(Result_1,0));
326     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
327     MemOp[0] = LD->getMemOperand();
328     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
329     const SDValue Froms[] = { SDValue(LD, 0),
330                               SDValue(LD, 1),
331                               SDValue(LD, 2) };
332     const SDValue Tos[]   = { SDValue(Result_2, 0),
333                               SDValue(Result_1, 1),
334                               SDValue(Result_1, 2) };
335     ReplaceUses(Froms, Tos, 3);
336     return Result_2;
337   }
338
339   // Generate an indirect load.
340   SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
341   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
342   SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
343                                             MVT::Other, Base, TargetConst0,
344                                             Chain);
345   SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A4_combineir, dl,
346                                             MVT::i64, MVT::Other,
347                                             TargetConst0,
348                                             SDValue(Result_1,0));
349   // Add offset to base.
350   SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
351                                             Base, TargetConstVal,
352                                             SDValue(Result_1, 1));
353   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
354   MemOp[0] = LD->getMemOperand();
355   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
356   const SDValue Froms[] = { SDValue(LD, 0),
357                             SDValue(LD, 1),
358                             SDValue(LD, 2) };
359   const SDValue Tos[]   = { SDValue(Result_2, 0), // Load value.
360                             SDValue(Result_3, 0), // New address.
361                             SDValue(Result_1, 1) };
362   ReplaceUses(Froms, Tos, 3);
363   return Result_2;
364 }
365
366
367 SDNode *HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, SDLoc dl) {
368   SDValue Chain = LD->getChain();
369   SDValue Base = LD->getBasePtr();
370   SDValue Offset = LD->getOffset();
371   SDNode *OffsetNode = Offset.getNode();
372   // Get the constant value.
373   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
374   EVT LoadedVT = LD->getMemoryVT();
375   unsigned Opcode = 0;
376
377   // Check for zero extended loads. Treat any-extend loads as zero extended
378   // loads.
379   ISD::LoadExtType ExtType = LD->getExtensionType();
380   bool IsZeroExt = (ExtType == ISD::ZEXTLOAD || ExtType == ISD::EXTLOAD);
381
382   // Figure out the opcode.
383   const HexagonInstrInfo &TII = *HST->getInstrInfo();
384   if (LoadedVT == MVT::i64) {
385     if (TII.isValidAutoIncImm(LoadedVT, Val))
386       Opcode = Hexagon::L2_loadrd_pi;
387     else
388       Opcode = Hexagon::L2_loadrd_io;
389   } else if (LoadedVT == MVT::i32) {
390     if (TII.isValidAutoIncImm(LoadedVT, Val))
391       Opcode = Hexagon::L2_loadri_pi;
392     else
393       Opcode = Hexagon::L2_loadri_io;
394   } else if (LoadedVT == MVT::i16) {
395     if (TII.isValidAutoIncImm(LoadedVT, Val))
396       Opcode = IsZeroExt ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadrh_pi;
397     else
398       Opcode = IsZeroExt ? Hexagon::L2_loadruh_io : Hexagon::L2_loadrh_io;
399   } else if (LoadedVT == MVT::i8) {
400     if (TII.isValidAutoIncImm(LoadedVT, Val))
401       Opcode = IsZeroExt ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrb_pi;
402     else
403       Opcode = IsZeroExt ? Hexagon::L2_loadrub_io : Hexagon::L2_loadrb_io;
404   } else
405     llvm_unreachable("unknown memory type");
406
407   // For zero extended i64 loads, we need to add combine instructions.
408   if (LD->getValueType(0) == MVT::i64 && IsZeroExt)
409     return SelectIndexedLoadZeroExtend64(LD, Opcode, dl);
410   // Handle sign extended i64 loads.
411   if (LD->getValueType(0) == MVT::i64 && ExtType == ISD::SEXTLOAD)
412     return SelectIndexedLoadSignExtend64(LD, Opcode, dl);
413
414   if (TII.isValidAutoIncImm(LoadedVT, Val)) {
415     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
416     SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
417                                             LD->getValueType(0),
418                                             MVT::i32, MVT::Other, Base,
419                                             TargetConstVal, Chain);
420     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
421     MemOp[0] = LD->getMemOperand();
422     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
423     const SDValue Froms[] = { SDValue(LD, 0),
424                               SDValue(LD, 1),
425                               SDValue(LD, 2)
426     };
427     const SDValue Tos[]   = { SDValue(Result, 0),
428                               SDValue(Result, 1),
429                               SDValue(Result, 2)
430     };
431     ReplaceUses(Froms, Tos, 3);
432     return Result;
433   } else {
434     SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
435     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
436     SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl,
437                                               LD->getValueType(0),
438                                               MVT::Other, Base, TargetConst0,
439                                               Chain);
440     SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
441                                               Base, TargetConstVal,
442                                               SDValue(Result_1, 1));
443     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
444     MemOp[0] = LD->getMemOperand();
445     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
446     const SDValue Froms[] = { SDValue(LD, 0),
447                               SDValue(LD, 1),
448                               SDValue(LD, 2)
449     };
450     const SDValue Tos[]   = { SDValue(Result_1, 0),
451                               SDValue(Result_2, 0),
452                               SDValue(Result_1, 1)
453     };
454     ReplaceUses(Froms, Tos, 3);
455     return Result_1;
456   }
457 }
458
459
460 SDNode *HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
461   SDNode *result;
462   SDLoc dl(N);
463   LoadSDNode *LD = cast<LoadSDNode>(N);
464   ISD::MemIndexedMode AM = LD->getAddressingMode();
465
466   // Handle indexed loads.
467   if (AM != ISD::UNINDEXED) {
468     result = SelectIndexedLoad(LD, dl);
469   } else {
470     result = SelectCode(LD);
471   }
472
473   return result;
474 }
475
476
477 SDNode *HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, SDLoc dl) {
478   SDValue Chain = ST->getChain();
479   SDValue Base = ST->getBasePtr();
480   SDValue Offset = ST->getOffset();
481   SDValue Value = ST->getValue();
482   SDNode *OffsetNode = Offset.getNode();
483   // Get the constant value.
484   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
485   EVT StoredVT = ST->getMemoryVT();
486   EVT ValueVT = Value.getValueType();
487
488   // Offset value must be within representable range
489   // and must have correct alignment properties.
490   const HexagonInstrInfo &TII = *HST->getInstrInfo();
491   if (TII.isValidAutoIncImm(StoredVT, Val)) {
492     unsigned Opcode = 0;
493
494     // Figure out the post inc version of opcode.
495     if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_pi;
496     else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_pi;
497     else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_pi;
498     else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_pi;
499     else llvm_unreachable("unknown memory type");
500
501     if (ST->isTruncatingStore() && ValueVT.getSizeInBits() == 64) {
502       assert(StoredVT.getSizeInBits() < 64 && "Not a truncating store");
503       Value = CurDAG->getTargetExtractSubreg(Hexagon::subreg_loreg,
504                                              dl, MVT::i32, Value);
505     }
506     SDValue Ops[] = {Base, CurDAG->getTargetConstant(Val, dl, MVT::i32), Value,
507                      Chain};
508     // Build post increment store.
509     SDNode* Result = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
510                                             MVT::Other, Ops);
511     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
512     MemOp[0] = ST->getMemOperand();
513     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
514
515     ReplaceUses(ST, Result);
516     ReplaceUses(SDValue(ST,1), SDValue(Result,1));
517     return Result;
518   }
519
520   // Note: Order of operands matches the def of instruction:
521   // def S2_storerd_io
522   //   : STInst<(outs), (ins IntRegs:$base, imm:$offset, DoubleRegs:$src1), ...
523   // and it differs for POST_ST* for instance.
524   SDValue Ops[] = { Base, CurDAG->getTargetConstant(0, dl, MVT::i32), Value,
525                     Chain};
526   unsigned Opcode = 0;
527
528   // Figure out the opcode.
529   if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_io;
530   else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_io;
531   else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_io;
532   else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_io;
533   else llvm_unreachable("unknown memory type");
534
535   // Build regular store.
536   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, dl, MVT::i32);
537   SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
538   // Build splitted incriment instruction.
539   SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
540                                             Base,
541                                             TargetConstVal,
542                                             SDValue(Result_1, 0));
543   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
544   MemOp[0] = ST->getMemOperand();
545   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
546
547   ReplaceUses(SDValue(ST,0), SDValue(Result_2,0));
548   ReplaceUses(SDValue(ST,1), SDValue(Result_1,0));
549   return Result_2;
550 }
551
552 SDNode *HexagonDAGToDAGISel::SelectStore(SDNode *N) {
553   SDLoc dl(N);
554   StoreSDNode *ST = cast<StoreSDNode>(N);
555   ISD::MemIndexedMode AM = ST->getAddressingMode();
556
557   // Handle indexed stores.
558   if (AM != ISD::UNINDEXED) {
559     return SelectIndexedStore(ST, dl);
560   }
561
562   return SelectCode(ST);
563 }
564
565 SDNode *HexagonDAGToDAGISel::SelectMul(SDNode *N) {
566   SDLoc dl(N);
567
568   //
569   // %conv.i = sext i32 %tmp1 to i64
570   // %conv2.i = sext i32 %add to i64
571   // %mul.i = mul nsw i64 %conv2.i, %conv.i
572   //
573   //   --- match with the following ---
574   //
575   // %mul.i = mpy (%tmp1, %add)
576   //
577
578   if (N->getValueType(0) == MVT::i64) {
579     // Shifting a i64 signed multiply.
580     SDValue MulOp0 = N->getOperand(0);
581     SDValue MulOp1 = N->getOperand(1);
582
583     SDValue OP0;
584     SDValue OP1;
585
586     // Handle sign_extend and sextload.
587     if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
588       SDValue Sext0 = MulOp0.getOperand(0);
589       if (Sext0.getNode()->getValueType(0) != MVT::i32) {
590         return SelectCode(N);
591       }
592
593       OP0 = Sext0;
594     } else if (MulOp0.getOpcode() == ISD::LOAD) {
595       LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
596       if (LD->getMemoryVT() != MVT::i32 ||
597           LD->getExtensionType() != ISD::SEXTLOAD ||
598           LD->getAddressingMode() != ISD::UNINDEXED) {
599         return SelectCode(N);
600       }
601
602       SDValue Chain = LD->getChain();
603       SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
604       OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
605                                             MVT::Other,
606                                             LD->getBasePtr(), TargetConst0,
607                                             Chain), 0);
608     } else {
609       return SelectCode(N);
610     }
611
612     // Same goes for the second operand.
613     if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
614       SDValue Sext1 = MulOp1.getOperand(0);
615       if (Sext1.getNode()->getValueType(0) != MVT::i32) {
616         return SelectCode(N);
617       }
618
619       OP1 = Sext1;
620     } else if (MulOp1.getOpcode() == ISD::LOAD) {
621       LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
622       if (LD->getMemoryVT() != MVT::i32 ||
623           LD->getExtensionType() != ISD::SEXTLOAD ||
624           LD->getAddressingMode() != ISD::UNINDEXED) {
625         return SelectCode(N);
626       }
627
628       SDValue Chain = LD->getChain();
629       SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
630       OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
631                                             MVT::Other,
632                                             LD->getBasePtr(), TargetConst0,
633                                             Chain), 0);
634     } else {
635       return SelectCode(N);
636     }
637
638     // Generate a mpy instruction.
639     SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_dpmpyss_s0, dl, MVT::i64,
640                                             OP0, OP1);
641     ReplaceUses(N, Result);
642     return Result;
643   }
644
645   return SelectCode(N);
646 }
647
648 SDNode *HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
649   SDLoc dl(N);
650   if (N->getValueType(0) == MVT::i32) {
651     SDValue Shl_0 = N->getOperand(0);
652     SDValue Shl_1 = N->getOperand(1);
653     // RHS is const.
654     if (Shl_1.getOpcode() == ISD::Constant) {
655       if (Shl_0.getOpcode() == ISD::MUL) {
656         SDValue Mul_0 = Shl_0.getOperand(0); // Val
657         SDValue Mul_1 = Shl_0.getOperand(1); // Const
658         // RHS of mul is const.
659         if (Mul_1.getOpcode() == ISD::Constant) {
660           int32_t ShlConst =
661             cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
662           int32_t MulConst =
663             cast<ConstantSDNode>(Mul_1.getNode())->getSExtValue();
664           int32_t ValConst = MulConst << ShlConst;
665           SDValue Val = CurDAG->getTargetConstant(ValConst, dl,
666                                                   MVT::i32);
667           if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val.getNode()))
668             if (isInt<9>(CN->getSExtValue())) {
669               SDNode* Result =
670                 CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
671                                        MVT::i32, Mul_0, Val);
672               ReplaceUses(N, Result);
673               return Result;
674             }
675
676         }
677       } else if (Shl_0.getOpcode() == ISD::SUB) {
678         SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
679         SDValue Sub_1 = Shl_0.getOperand(1); // Val
680         if (Sub_0.getOpcode() == ISD::Constant) {
681           int32_t SubConst =
682             cast<ConstantSDNode>(Sub_0.getNode())->getSExtValue();
683           if (SubConst == 0) {
684             if (Sub_1.getOpcode() == ISD::SHL) {
685               SDValue Shl2_0 = Sub_1.getOperand(0); // Val
686               SDValue Shl2_1 = Sub_1.getOperand(1); // Const
687               if (Shl2_1.getOpcode() == ISD::Constant) {
688                 int32_t ShlConst =
689                   cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
690                 int32_t Shl2Const =
691                   cast<ConstantSDNode>(Shl2_1.getNode())->getSExtValue();
692                 int32_t ValConst = 1 << (ShlConst+Shl2Const);
693                 SDValue Val = CurDAG->getTargetConstant(-ValConst, dl,
694                                                         MVT::i32);
695                 if (ConstantSDNode *CN =
696                     dyn_cast<ConstantSDNode>(Val.getNode()))
697                   if (isInt<9>(CN->getSExtValue())) {
698                     SDNode* Result =
699                       CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl, MVT::i32,
700                                              Shl2_0, Val);
701                     ReplaceUses(N, Result);
702                     return Result;
703                   }
704               }
705             }
706           }
707         }
708       }
709     }
710   }
711   return SelectCode(N);
712 }
713
714
715 //
716 // If there is an zero_extend followed an intrinsic in DAG (this means - the
717 // result of the intrinsic is predicate); convert the zero_extend to
718 // transfer instruction.
719 //
720 // Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
721 // converted into a MUX as predicate registers defined as 1 bit in the
722 // compiler. Architecture defines them as 8-bit registers.
723 // We want to preserve all the lower 8-bits and, not just 1 LSB bit.
724 //
725 SDNode *HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
726   SDLoc dl(N);
727
728   SDValue Op0 = N->getOperand(0);
729   EVT OpVT = Op0.getValueType();
730   unsigned OpBW = OpVT.getSizeInBits();
731
732   // Special handling for zero-extending a vector of booleans.
733   if (OpVT.isVector() && OpVT.getVectorElementType() == MVT::i1 && OpBW <= 64) {
734     SDNode *Mask = CurDAG->getMachineNode(Hexagon::C2_mask, dl, MVT::i64, Op0);
735     unsigned NE = OpVT.getVectorNumElements();
736     EVT ExVT = N->getValueType(0);
737     unsigned ES = ExVT.getVectorElementType().getSizeInBits();
738     uint64_t MV = 0, Bit = 1;
739     for (unsigned i = 0; i < NE; ++i) {
740       MV |= Bit;
741       Bit <<= ES;
742     }
743     SDValue Ones = CurDAG->getTargetConstant(MV, dl, MVT::i64);
744     SDNode *OnesReg = CurDAG->getMachineNode(Hexagon::CONST64_Int_Real, dl,
745                                              MVT::i64, Ones);
746     if (ExVT.getSizeInBits() == 32) {
747       SDNode *And = CurDAG->getMachineNode(Hexagon::A2_andp, dl, MVT::i64,
748                                            SDValue(Mask,0), SDValue(OnesReg,0));
749       SDValue SubR = CurDAG->getTargetConstant(Hexagon::subreg_loreg, dl,
750                                                MVT::i32);
751       return CurDAG->getMachineNode(Hexagon::EXTRACT_SUBREG, dl, ExVT,
752                                     SDValue(And,0), SubR);
753     }
754     return CurDAG->getMachineNode(Hexagon::A2_andp, dl, ExVT,
755                                   SDValue(Mask,0), SDValue(OnesReg,0));
756   }
757
758   SDNode *IsIntrinsic = N->getOperand(0).getNode();
759   if ((IsIntrinsic->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
760     unsigned ID =
761       cast<ConstantSDNode>(IsIntrinsic->getOperand(0))->getZExtValue();
762     if (doesIntrinsicReturnPredicate(ID)) {
763       // Now we need to differentiate target data types.
764       if (N->getValueType(0) == MVT::i64) {
765         // Convert the zero_extend to Rs = Pd followed by A2_combinew(0,Rs).
766         SDValue TargetConst0 = CurDAG->getTargetConstant(0, dl, MVT::i32);
767         SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
768                                                   MVT::i32,
769                                                   SDValue(IsIntrinsic, 0));
770         SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
771                                                   MVT::i32,
772                                                   TargetConst0);
773         SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
774                                                   MVT::i64, MVT::Other,
775                                                   SDValue(Result_2, 0),
776                                                   SDValue(Result_1, 0));
777         ReplaceUses(N, Result_3);
778         return Result_3;
779       }
780       if (N->getValueType(0) == MVT::i32) {
781         // Convert the zero_extend to Rs = Pd
782         SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
783                                               MVT::i32,
784                                               SDValue(IsIntrinsic, 0));
785         ReplaceUses(N, RsPd);
786         return RsPd;
787       }
788       llvm_unreachable("Unexpected value type");
789     }
790   }
791   return SelectCode(N);
792 }
793
794 //
795 // Checking for intrinsics circular load/store, and bitreverse load/store
796 // instrisics in order to select the correct lowered operation.
797 //
798 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWChain(SDNode *N) {
799   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
800   if (IntNo == Intrinsic::hexagon_circ_ldd  ||
801       IntNo == Intrinsic::hexagon_circ_ldw  ||
802       IntNo == Intrinsic::hexagon_circ_lduh ||
803       IntNo == Intrinsic::hexagon_circ_ldh  ||
804       IntNo == Intrinsic::hexagon_circ_ldub ||
805       IntNo == Intrinsic::hexagon_circ_ldb) {
806     SDLoc dl(N);
807     SDValue Chain = N->getOperand(0);
808     SDValue Base = N->getOperand(2);
809     SDValue Load = N->getOperand(3);
810     SDValue ModifierExpr = N->getOperand(4);
811     SDValue Offset = N->getOperand(5);
812
813     // We need to add the rerurn type for the load.  This intrinsic has
814     // two return types, one for the load and one for the post-increment.
815     // Only the *_ld instructions push the extra return type, and bump the
816     // result node operand number correspondingly.
817     std::vector<EVT> ResTys;
818     unsigned opc;
819     unsigned memsize, align;
820     MVT MvtSize = MVT::i32;
821
822     if (IntNo == Intrinsic::hexagon_circ_ldd) {
823       ResTys.push_back(MVT::i32);
824       ResTys.push_back(MVT::i64);
825       opc = Hexagon::L2_loadrd_pci_pseudo;
826       memsize = 8;
827       align = 8;
828     } else if (IntNo == Intrinsic::hexagon_circ_ldw) {
829       ResTys.push_back(MVT::i32);
830       ResTys.push_back(MVT::i32);
831       opc = Hexagon::L2_loadri_pci_pseudo;
832       memsize = 4;
833       align = 4;
834     } else if (IntNo == Intrinsic::hexagon_circ_ldh) {
835       ResTys.push_back(MVT::i32);
836       ResTys.push_back(MVT::i32);
837       opc = Hexagon::L2_loadrh_pci_pseudo;
838       memsize = 2;
839       align = 2;
840       MvtSize = MVT::i16;
841     } else if (IntNo == Intrinsic::hexagon_circ_lduh) {
842       ResTys.push_back(MVT::i32);
843       ResTys.push_back(MVT::i32);
844       opc = Hexagon::L2_loadruh_pci_pseudo;
845       memsize = 2;
846       align = 2;
847       MvtSize = MVT::i16;
848     } else if (IntNo == Intrinsic::hexagon_circ_ldb) {
849       ResTys.push_back(MVT::i32);
850       ResTys.push_back(MVT::i32);
851       opc = Hexagon::L2_loadrb_pci_pseudo;
852       memsize = 1;
853       align = 1;
854       MvtSize = MVT::i8;
855     } else if (IntNo == Intrinsic::hexagon_circ_ldub) {
856       ResTys.push_back(MVT::i32);
857       ResTys.push_back(MVT::i32);
858       opc = Hexagon::L2_loadrub_pci_pseudo;
859       memsize = 1;
860       align = 1;
861       MvtSize = MVT::i8;
862     } else
863       llvm_unreachable("no opc");
864
865     ResTys.push_back(MVT::Other);
866
867     // Copy over the arguments, which are the same mostly.
868     SmallVector<SDValue, 5> Ops;
869     Ops.push_back(Base);
870     Ops.push_back(Load);
871     Ops.push_back(ModifierExpr);
872     int32_t Val = cast<ConstantSDNode>(Offset.getNode())->getSExtValue();
873     Ops.push_back(CurDAG->getTargetConstant(Val, dl, MVT::i32));
874     Ops.push_back(Chain);
875     SDNode* Result = CurDAG->getMachineNode(opc, dl, ResTys, Ops);
876
877     SDValue ST;
878     MachineMemOperand *Mem =
879       MF->getMachineMemOperand(MachinePointerInfo(),
880                                MachineMemOperand::MOStore, memsize, align);
881     if (MvtSize != MVT::i32)
882       ST = CurDAG->getTruncStore(Chain, dl, SDValue(Result, 1), Load,
883                                  MvtSize, Mem);
884     else
885       ST = CurDAG->getStore(Chain, dl, SDValue(Result, 1), Load, Mem);
886
887     SDNode* Store = SelectStore(ST.getNode());
888
889     const SDValue Froms[] = { SDValue(N, 0),
890                               SDValue(N, 1) };
891     const SDValue Tos[]   = { SDValue(Result, 0),
892                               SDValue(Store, 0) };
893     ReplaceUses(Froms, Tos, 2);
894     return Result;
895   }
896
897   if (IntNo == Intrinsic::hexagon_brev_ldd  ||
898       IntNo == Intrinsic::hexagon_brev_ldw  ||
899       IntNo == Intrinsic::hexagon_brev_ldh  ||
900       IntNo == Intrinsic::hexagon_brev_lduh ||
901       IntNo == Intrinsic::hexagon_brev_ldb  ||
902       IntNo == Intrinsic::hexagon_brev_ldub) {
903     SDLoc dl(N);
904     SDValue Chain = N->getOperand(0);
905     SDValue Base = N->getOperand(2);
906     SDValue Load = N->getOperand(3);
907     SDValue ModifierExpr = N->getOperand(4);
908
909     // We need to add the rerurn type for the load.  This intrinsic has
910     // two return types, one for the load and one for the post-increment.
911     std::vector<EVT> ResTys;
912     unsigned opc;
913     unsigned memsize, align;
914     MVT MvtSize = MVT::i32;
915
916     if (IntNo == Intrinsic::hexagon_brev_ldd) {
917       ResTys.push_back(MVT::i32);
918       ResTys.push_back(MVT::i64);
919       opc = Hexagon::L2_loadrd_pbr_pseudo;
920       memsize = 8;
921       align = 8;
922     } else if (IntNo == Intrinsic::hexagon_brev_ldw) {
923       ResTys.push_back(MVT::i32);
924       ResTys.push_back(MVT::i32);
925       opc = Hexagon::L2_loadri_pbr_pseudo;
926       memsize = 4;
927       align = 4;
928     } else if (IntNo == Intrinsic::hexagon_brev_ldh) {
929       ResTys.push_back(MVT::i32);
930       ResTys.push_back(MVT::i32);
931       opc = Hexagon::L2_loadrh_pbr_pseudo;
932       memsize = 2;
933       align = 2;
934       MvtSize = MVT::i16;
935     } else if (IntNo == Intrinsic::hexagon_brev_lduh) {
936       ResTys.push_back(MVT::i32);
937       ResTys.push_back(MVT::i32);
938       opc = Hexagon::L2_loadruh_pbr_pseudo;
939       memsize = 2;
940       align = 2;
941       MvtSize = MVT::i16;
942     } else if (IntNo == Intrinsic::hexagon_brev_ldb) {
943       ResTys.push_back(MVT::i32);
944       ResTys.push_back(MVT::i32);
945       opc = Hexagon::L2_loadrb_pbr_pseudo;
946       memsize = 1;
947       align = 1;
948       MvtSize = MVT::i8;
949     } else if (IntNo == Intrinsic::hexagon_brev_ldub) {
950       ResTys.push_back(MVT::i32);
951       ResTys.push_back(MVT::i32);
952       opc = Hexagon::L2_loadrub_pbr_pseudo;
953       memsize = 1;
954       align = 1;
955       MvtSize = MVT::i8;
956     } else
957       llvm_unreachable("no opc");
958
959     ResTys.push_back(MVT::Other);
960
961     // Copy over the arguments, which are the same mostly.
962     SmallVector<SDValue, 4> Ops;
963     Ops.push_back(Base);
964     Ops.push_back(Load);
965     Ops.push_back(ModifierExpr);
966     Ops.push_back(Chain);
967     SDNode* Result = CurDAG->getMachineNode(opc, dl, ResTys, Ops);
968     SDValue ST;
969     MachineMemOperand *Mem =
970       MF->getMachineMemOperand(MachinePointerInfo(),
971                                MachineMemOperand::MOStore, memsize, align);
972     if (MvtSize != MVT::i32)
973       ST = CurDAG->getTruncStore(Chain, dl, SDValue(Result, 1), Load,
974                                  MvtSize, Mem);
975     else
976       ST = CurDAG->getStore(Chain, dl, SDValue(Result, 1), Load, Mem);
977
978     SDNode* Store = SelectStore(ST.getNode());
979
980     const SDValue Froms[] = { SDValue(N, 0),
981                               SDValue(N, 1) };
982     const SDValue Tos[]   = { SDValue(Result, 0),
983                               SDValue(Store, 0) };
984     ReplaceUses(Froms, Tos, 2);
985     return Result;
986   }
987
988   return SelectCode(N);
989 }
990
991 //
992 // Checking for intrinsics which have predicate registers as operand(s)
993 // and lowering to the actual intrinsic.
994 //
995 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
996   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
997   unsigned Bits;
998   switch (IID) {
999   case Intrinsic::hexagon_S2_vsplatrb:
1000     Bits = 8;
1001     break;
1002   case Intrinsic::hexagon_S2_vsplatrh:
1003     Bits = 16;
1004     break;
1005   default:
1006     return SelectCode(N);
1007   }
1008
1009   SDValue const &V = N->getOperand(1);
1010   SDValue U;
1011   if (isValueExtension(V, Bits, U)) {
1012     SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
1013       N->getOperand(0), U);
1014     return SelectCode(R.getNode());
1015   }
1016   return SelectCode(N);
1017 }
1018
1019 //
1020 // Map floating point constant values.
1021 //
1022 SDNode *HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
1023   SDLoc dl(N);
1024   ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
1025   APFloat APF = CN->getValueAPF();
1026   if (N->getValueType(0) == MVT::f32) {
1027     return CurDAG->getMachineNode(Hexagon::TFRI_f, dl, MVT::f32,
1028               CurDAG->getTargetConstantFP(APF.convertToFloat(), dl, MVT::f32));
1029   }
1030   else if (N->getValueType(0) == MVT::f64) {
1031     return CurDAG->getMachineNode(Hexagon::CONST64_Float_Real, dl, MVT::f64,
1032               CurDAG->getTargetConstantFP(APF.convertToDouble(), dl, MVT::f64));
1033   }
1034
1035   return SelectCode(N);
1036 }
1037
1038 //
1039 // Map predicate true (encoded as -1 in LLVM) to a XOR.
1040 //
1041 SDNode *HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
1042   SDLoc dl(N);
1043   if (N->getValueType(0) == MVT::i1) {
1044     SDNode* Result = 0;
1045     int32_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1046     if (Val == -1) {
1047       Result = CurDAG->getMachineNode(Hexagon::TFR_PdTrue, dl, MVT::i1);
1048     } else if (Val == 0) {
1049       Result = CurDAG->getMachineNode(Hexagon::TFR_PdFalse, dl, MVT::i1);
1050     }
1051     if (Result) {
1052       ReplaceUses(N, Result);
1053       return Result;
1054     }
1055   }
1056
1057   return SelectCode(N);
1058 }
1059
1060
1061 //
1062 // Map add followed by a asr -> asr +=.
1063 //
1064 SDNode *HexagonDAGToDAGISel::SelectAdd(SDNode *N) {
1065   SDLoc dl(N);
1066   if (N->getValueType(0) != MVT::i32) {
1067     return SelectCode(N);
1068   }
1069   // Identify nodes of the form: add(asr(...)).
1070   SDNode* Src1 = N->getOperand(0).getNode();
1071   if (Src1->getOpcode() != ISD::SRA || !Src1->hasOneUse()
1072       || Src1->getValueType(0) != MVT::i32) {
1073     return SelectCode(N);
1074   }
1075
1076   // Build Rd = Rd' + asr(Rs, Rt). The machine constraints will ensure that
1077   // Rd and Rd' are assigned to the same register
1078   SDNode* Result = CurDAG->getMachineNode(Hexagon::S2_asr_r_r_acc, dl, MVT::i32,
1079                                           N->getOperand(1),
1080                                           Src1->getOperand(0),
1081                                           Src1->getOperand(1));
1082   ReplaceUses(N, Result);
1083
1084   return Result;
1085 }
1086
1087 //
1088 // Map the following, where possible.
1089 // AND/FABS -> clrbit
1090 // OR -> setbit
1091 // XOR/FNEG ->toggle_bit.
1092 //
1093 SDNode *HexagonDAGToDAGISel::SelectBitOp(SDNode *N) {
1094   SDLoc dl(N);
1095   EVT ValueVT = N->getValueType(0);
1096
1097   // We handle only 32 and 64-bit bit ops.
1098   if (!(ValueVT == MVT::i32 || ValueVT == MVT::i64 ||
1099         ValueVT == MVT::f32 || ValueVT == MVT::f64))
1100     return SelectCode(N);
1101
1102   // We handly only fabs and fneg for V5.
1103   unsigned Opc = N->getOpcode();
1104   if ((Opc == ISD::FABS || Opc == ISD::FNEG) && !HST->hasV5TOps())
1105     return SelectCode(N);
1106
1107   int64_t Val = 0;
1108   if (Opc != ISD::FABS && Opc != ISD::FNEG) {
1109     if (N->getOperand(1).getOpcode() == ISD::Constant)
1110       Val = cast<ConstantSDNode>((N)->getOperand(1))->getSExtValue();
1111     else
1112      return SelectCode(N);
1113   }
1114
1115   if (Opc == ISD::AND) {
1116     if (((ValueVT == MVT::i32) &&
1117                   (!((Val & 0x80000000) || (Val & 0x7fffffff)))) ||
1118         ((ValueVT == MVT::i64) &&
1119                   (!((Val & 0x8000000000000000) || (Val & 0x7fffffff)))))
1120       // If it's simple AND, do the normal op.
1121       return SelectCode(N);
1122     else
1123       Val = ~Val;
1124   }
1125
1126   // If OR or AND is being fed by shl, srl and, sra don't do this change,
1127   // because Hexagon provide |= &= on shl, srl, and sra.
1128   // Traverse the DAG to see if there is shl, srl and sra.
1129   if (Opc == ISD::OR || Opc == ISD::AND) {
1130     switch (N->getOperand(0)->getOpcode()) {
1131       default: break;
1132       case ISD::SRA:
1133       case ISD::SRL:
1134       case ISD::SHL:
1135         return SelectCode(N);
1136     }
1137   }
1138
1139   // Make sure it's power of 2.
1140   unsigned bitpos = 0;
1141   if (Opc != ISD::FABS && Opc != ISD::FNEG) {
1142     if (((ValueVT == MVT::i32) && !isPowerOf2_32(Val)) ||
1143         ((ValueVT == MVT::i64) && !isPowerOf2_64(Val)))
1144       return SelectCode(N);
1145
1146     // Get the bit position.
1147     bitpos = countTrailingZeros(uint64_t(Val));
1148   } else {
1149     // For fabs and fneg, it's always the 31st bit.
1150     bitpos = 31;
1151   }
1152
1153   unsigned BitOpc = 0;
1154   // Set the right opcode for bitwise operations.
1155   switch(Opc) {
1156     default: llvm_unreachable("Only bit-wise/abs/neg operations are allowed.");
1157     case ISD::AND:
1158     case ISD::FABS:
1159       BitOpc = Hexagon::S2_clrbit_i;
1160       break;
1161     case ISD::OR:
1162       BitOpc = Hexagon::S2_setbit_i;
1163       break;
1164     case ISD::XOR:
1165     case ISD::FNEG:
1166       BitOpc = Hexagon::S2_togglebit_i;
1167       break;
1168   }
1169
1170   SDNode *Result;
1171   // Get the right SDVal for the opcode.
1172   SDValue SDVal = CurDAG->getTargetConstant(bitpos, dl, MVT::i32);
1173
1174   if (ValueVT == MVT::i32 || ValueVT == MVT::f32) {
1175     Result = CurDAG->getMachineNode(BitOpc, dl, ValueVT,
1176                                     N->getOperand(0), SDVal);
1177   } else {
1178     // 64-bit gymnastic to use REG_SEQUENCE. But it's worth it.
1179     EVT SubValueVT;
1180     if (ValueVT == MVT::i64)
1181       SubValueVT = MVT::i32;
1182     else
1183       SubValueVT = MVT::f32;
1184
1185     SDNode *Reg = N->getOperand(0).getNode();
1186     SDValue RegClass = CurDAG->getTargetConstant(Hexagon::DoubleRegsRegClassID,
1187                                                  dl, MVT::i64);
1188
1189     SDValue SubregHiIdx = CurDAG->getTargetConstant(Hexagon::subreg_hireg, dl,
1190                                                     MVT::i32);
1191     SDValue SubregLoIdx = CurDAG->getTargetConstant(Hexagon::subreg_loreg, dl,
1192                                                     MVT::i32);
1193
1194     SDValue SubregHI = CurDAG->getTargetExtractSubreg(Hexagon::subreg_hireg, dl,
1195                                                     MVT::i32, SDValue(Reg, 0));
1196
1197     SDValue SubregLO = CurDAG->getTargetExtractSubreg(Hexagon::subreg_loreg, dl,
1198                                                     MVT::i32, SDValue(Reg, 0));
1199
1200     // Clear/set/toggle hi or lo registers depending on the bit position.
1201     if (SubValueVT != MVT::f32 && bitpos < 32) {
1202       SDNode *Result0 = CurDAG->getMachineNode(BitOpc, dl, SubValueVT,
1203                                                SubregLO, SDVal);
1204       const SDValue Ops[] = { RegClass, SubregHI, SubregHiIdx,
1205                               SDValue(Result0, 0), SubregLoIdx };
1206       Result = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1207                                       dl, ValueVT, Ops);
1208     } else {
1209       if (Opc != ISD::FABS && Opc != ISD::FNEG)
1210         SDVal = CurDAG->getTargetConstant(bitpos - 32, dl, MVT::i32);
1211       SDNode *Result0 = CurDAG->getMachineNode(BitOpc, dl, SubValueVT,
1212                                                SubregHI, SDVal);
1213       const SDValue Ops[] = { RegClass, SDValue(Result0, 0), SubregHiIdx,
1214                               SubregLO, SubregLoIdx };
1215       Result = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE,
1216                                       dl, ValueVT, Ops);
1217     }
1218   }
1219
1220   ReplaceUses(N, Result);
1221   return Result;
1222 }
1223
1224
1225 SDNode *HexagonDAGToDAGISel::SelectFrameIndex(SDNode *N) {
1226   MachineFrameInfo *MFI = MF->getFrameInfo();
1227   const HexagonFrameLowering *HFI = HST->getFrameLowering();
1228   int FX = cast<FrameIndexSDNode>(N)->getIndex();
1229   unsigned StkA = HFI->getStackAlignment();
1230   unsigned MaxA = MFI->getMaxAlignment();
1231   SDValue FI = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1232   SDLoc DL(N);
1233   SDValue Zero = CurDAG->getTargetConstant(0, DL, MVT::i32);
1234   SDNode *R = 0;
1235
1236   // Use TFR_FI when:
1237   // - the object is fixed, or
1238   // - there are no objects with higher-than-default alignment, or
1239   // - there are no dynamically allocated objects.
1240   // Otherwise, use TFR_FIA.
1241   if (FX < 0 || MaxA <= StkA || !MFI->hasVarSizedObjects()) {
1242     R = CurDAG->getMachineNode(Hexagon::TFR_FI, DL, MVT::i32, FI, Zero);
1243   } else {
1244     auto &HMFI = *MF->getInfo<HexagonMachineFunctionInfo>();
1245     unsigned AR = HMFI.getStackAlignBaseVReg();
1246     SDValue CH = CurDAG->getEntryNode();
1247     SDValue Ops[] = { CurDAG->getCopyFromReg(CH, DL, AR, MVT::i32), FI, Zero };
1248     R = CurDAG->getMachineNode(Hexagon::TFR_FIA, DL, MVT::i32, Ops);
1249   }
1250
1251   if (N->getHasDebugValue())
1252     CurDAG->TransferDbgValues(SDValue(N, 0), SDValue(R, 0));
1253   return R;
1254 }
1255
1256
1257 SDNode *HexagonDAGToDAGISel::Select(SDNode *N) {
1258   if (N->isMachineOpcode()) {
1259     N->setNodeId(-1);
1260     return nullptr;   // Already selected.
1261   }
1262
1263   switch (N->getOpcode()) {
1264   case ISD::Constant:
1265     return SelectConstant(N);
1266
1267   case ISD::ConstantFP:
1268     return SelectConstantFP(N);
1269
1270   case ISD::FrameIndex:
1271     return SelectFrameIndex(N);
1272
1273   case ISD::ADD:
1274     return SelectAdd(N);
1275
1276   case ISD::SHL:
1277     return SelectSHL(N);
1278
1279   case ISD::LOAD:
1280     return SelectLoad(N);
1281
1282   case ISD::STORE:
1283     return SelectStore(N);
1284
1285   case ISD::MUL:
1286     return SelectMul(N);
1287
1288   case ISD::AND:
1289   case ISD::OR:
1290   case ISD::XOR:
1291   case ISD::FABS:
1292   case ISD::FNEG:
1293     return SelectBitOp(N);
1294
1295   case ISD::ZERO_EXTEND:
1296     return SelectZeroExtend(N);
1297
1298   case ISD::INTRINSIC_W_CHAIN:
1299     return SelectIntrinsicWChain(N);
1300
1301   case ISD::INTRINSIC_WO_CHAIN:
1302     return SelectIntrinsicWOChain(N);
1303   }
1304
1305   return SelectCode(N);
1306 }
1307
1308 bool HexagonDAGToDAGISel::
1309 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
1310                              std::vector<SDValue> &OutOps) {
1311   SDValue Inp = Op, Res;
1312
1313   switch (ConstraintID) {
1314   default:
1315     return true;
1316   case InlineAsm::Constraint_i:
1317   case InlineAsm::Constraint_o: // Offsetable.
1318   case InlineAsm::Constraint_v: // Not offsetable.
1319   case InlineAsm::Constraint_m: // Memory.
1320     if (SelectAddrFI(Inp, Res))
1321       OutOps.push_back(Res);
1322     else
1323       OutOps.push_back(Inp);
1324     break;
1325   }
1326
1327   OutOps.push_back(CurDAG->getTargetConstant(0, SDLoc(Op), MVT::i32));
1328   return false;
1329 }
1330
1331 bool HexagonDAGToDAGISel::isConstExtProfitable(SDNode *N) const {
1332   unsigned UseCount = 0;
1333   unsigned CallCount = 0;
1334   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1335     // Ignore call instructions.
1336     if (I->getOpcode() == ISD::CopyToReg)
1337       ++CallCount;
1338     UseCount++;
1339   }
1340
1341   return (UseCount <= 1) || (CallCount > 1);
1342
1343 }
1344
1345 void HexagonDAGToDAGISel::PreprocessISelDAG() {
1346   SelectionDAG &DAG = *CurDAG;
1347   std::vector<SDNode*> Nodes;
1348   for (SDNode &Node : DAG.allnodes())
1349     Nodes.push_back(&Node);
1350
1351   // Simplify: (or (select c x 0) z)  ->  (select c (or x z) z)
1352   //           (or (select c 0 y) z)  ->  (select c z (or y z))
1353   // This may not be the right thing for all targets, so do it here.
1354   for (auto I: Nodes) {
1355     if (I->getOpcode() != ISD::OR)
1356       continue;
1357
1358     auto IsZero = [] (const SDValue &V) -> bool {
1359       if (ConstantSDNode *SC = dyn_cast<ConstantSDNode>(V.getNode()))
1360         return SC->isNullValue();
1361       return false;
1362     };
1363     auto IsSelect0 = [IsZero] (const SDValue &Op) -> bool {
1364       if (Op.getOpcode() != ISD::SELECT)
1365         return false;
1366       return IsZero(Op.getOperand(1))  || IsZero(Op.getOperand(2));
1367     };
1368
1369     SDValue N0 = I->getOperand(0), N1 = I->getOperand(1);
1370     EVT VT = I->getValueType(0);
1371     bool SelN0 = IsSelect0(N0);
1372     SDValue SOp = SelN0 ? N0 : N1;
1373     SDValue VOp = SelN0 ? N1 : N0;
1374
1375     if (SOp.getOpcode() == ISD::SELECT && SOp.getNode()->hasOneUse()) {
1376       SDValue SC = SOp.getOperand(0);
1377       SDValue SX = SOp.getOperand(1);
1378       SDValue SY = SOp.getOperand(2);
1379       SDLoc DLS = SOp;
1380       if (IsZero(SY)) {
1381         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SX, VOp);
1382         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, NewOr, VOp);
1383         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1384       } else if (IsZero(SX)) {
1385         SDValue NewOr = DAG.getNode(ISD::OR, DLS, VT, SY, VOp);
1386         SDValue NewSel = DAG.getNode(ISD::SELECT, DLS, VT, SC, VOp, NewOr);
1387         DAG.ReplaceAllUsesWith(I, NewSel.getNode());
1388       }
1389     }
1390   }
1391 }
1392
1393 void HexagonDAGToDAGISel::EmitFunctionEntryCode() {
1394   auto &HST = static_cast<const HexagonSubtarget&>(MF->getSubtarget());
1395   auto &HFI = *HST.getFrameLowering();
1396   if (!HFI.needsAligna(*MF))
1397     return;
1398
1399   MachineFrameInfo *MFI = MF->getFrameInfo();
1400   MachineBasicBlock *EntryBB = MF->begin();
1401   unsigned AR = FuncInfo->CreateReg(MVT::i32);
1402   unsigned MaxA = MFI->getMaxAlignment();
1403   auto &HII = *HST.getInstrInfo();
1404   BuildMI(EntryBB, DebugLoc(), HII.get(Hexagon::ALIGNA), AR)
1405       .addImm(MaxA);
1406   MF->getInfo<HexagonMachineFunctionInfo>()->setStackAlignBaseVReg(AR);
1407 }
1408
1409 // Match a frame index that can be used in an addressing mode.
1410 bool HexagonDAGToDAGISel::SelectAddrFI(SDValue& N, SDValue &R) {
1411   if (N.getOpcode() != ISD::FrameIndex)
1412     return false;
1413   auto &HFI = *HST->getFrameLowering();
1414   MachineFrameInfo *MFI = MF->getFrameInfo();
1415   int FX = cast<FrameIndexSDNode>(N)->getIndex();
1416   if (!MFI->isFixedObjectIndex(FX) && HFI.needsAligna(*MF))
1417     return false;
1418   R = CurDAG->getTargetFrameIndex(FX, MVT::i32);
1419   return true;
1420 }
1421
1422 inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1423   return SelectGlobalAddress(N, R, false);
1424 }
1425
1426 inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1427   return SelectGlobalAddress(N, R, true);
1428 }
1429
1430 bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1431                                               bool UseGP) {
1432   switch (N.getOpcode()) {
1433   case ISD::ADD: {
1434     SDValue N0 = N.getOperand(0);
1435     SDValue N1 = N.getOperand(1);
1436     unsigned GAOpc = N0.getOpcode();
1437     if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1438       return false;
1439     if (!UseGP && GAOpc != HexagonISD::CONST32)
1440       return false;
1441     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1442       SDValue Addr = N0.getOperand(0);
1443       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1444         if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1445           uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1446           R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1447                                              N.getValueType(), NewOff);
1448           return true;
1449         }
1450       }
1451     }
1452     break;
1453   }
1454   case HexagonISD::CONST32:
1455     // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1456     // want in the instruction.
1457     if (!UseGP)
1458       R = N.getOperand(0);
1459     return !UseGP;
1460   case HexagonISD::CONST32_GP:
1461     if (UseGP)
1462       R = N.getOperand(0);
1463     return UseGP;
1464   default:
1465     return false;
1466   }
1467
1468   return false;
1469 }
1470
1471 bool HexagonDAGToDAGISel::isValueExtension(const SDValue &Val,
1472       unsigned FromBits, SDValue &Src) {
1473   unsigned Opc = Val.getOpcode();
1474   switch (Opc) {
1475   case ISD::SIGN_EXTEND:
1476   case ISD::ZERO_EXTEND:
1477   case ISD::ANY_EXTEND: {
1478     SDValue const &Op0 = Val.getOperand(0);
1479     EVT T = Op0.getValueType();
1480     if (T.isInteger() && T.getSizeInBits() == FromBits) {
1481       Src = Op0;
1482       return true;
1483     }
1484     break;
1485   }
1486   case ISD::SIGN_EXTEND_INREG:
1487   case ISD::AssertSext:
1488   case ISD::AssertZext:
1489     if (Val.getOperand(0).getValueType().isInteger()) {
1490       VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1491       if (T->getVT().getSizeInBits() == FromBits) {
1492         Src = Val.getOperand(0);
1493         return true;
1494       }
1495     }
1496     break;
1497   case ISD::AND: {
1498     // Check if this is an AND with "FromBits" of lower bits set to 1.
1499     uint64_t FromMask = (1 << FromBits) - 1;
1500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1501       if (C->getZExtValue() == FromMask) {
1502         Src = Val.getOperand(1);
1503         return true;
1504       }
1505     }
1506     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1507       if (C->getZExtValue() == FromMask) {
1508         Src = Val.getOperand(0);
1509         return true;
1510       }
1511     }
1512     break;
1513   }
1514   case ISD::OR:
1515   case ISD::XOR: {
1516     // OR/XOR with the lower "FromBits" bits set to 0.
1517     uint64_t FromMask = (1 << FromBits) - 1;
1518     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1519       if ((C->getZExtValue() & FromMask) == 0) {
1520         Src = Val.getOperand(1);
1521         return true;
1522       }
1523     }
1524     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1525       if ((C->getZExtValue() & FromMask) == 0) {
1526         Src = Val.getOperand(0);
1527         return true;
1528       }
1529     }
1530   }
1531   default:
1532     break;
1533   }
1534   return false;
1535 }