[Hexagon] Renaming A2_addi and formatting.
[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 "HexagonTargetMachine.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/CodeGen/SelectionDAGISel.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Debug.h"
23 using namespace llvm;
24
25 #define DEBUG_TYPE "hexagon-isel"
26
27 static
28 cl::opt<unsigned>
29 MaxNumOfUsesForConstExtenders("ga-max-num-uses-for-constant-extenders",
30   cl::Hidden, cl::init(2),
31   cl::desc("Maximum number of uses of a global address such that we still us a"
32            "constant extended instruction"));
33
34 //===----------------------------------------------------------------------===//
35 // Instruction Selector Implementation
36 //===----------------------------------------------------------------------===//
37
38 namespace llvm {
39   void initializeHexagonDAGToDAGISelPass(PassRegistry&);
40 }
41
42 //===--------------------------------------------------------------------===//
43 /// HexagonDAGToDAGISel - Hexagon specific code to select Hexagon machine
44 /// instructions for SelectionDAG operations.
45 ///
46 namespace {
47 class HexagonDAGToDAGISel : public SelectionDAGISel {
48   /// Subtarget - Keep a pointer to the Hexagon Subtarget around so that we can
49   /// make the right decision when generating code for different targets.
50   const HexagonSubtarget *Subtarget;
51
52   // Keep a reference to HexagonTargetMachine.
53   const HexagonTargetMachine& TM;
54   DenseMap<const GlobalValue *, unsigned> GlobalAddressUseCountMap;
55 public:
56   explicit HexagonDAGToDAGISel(HexagonTargetMachine &targetmachine,
57                                CodeGenOpt::Level OptLevel)
58       : SelectionDAGISel(targetmachine, OptLevel), TM(targetmachine) {
59     initializeHexagonDAGToDAGISelPass(*PassRegistry::getPassRegistry());
60   }
61   bool hasNumUsesBelowThresGA(SDNode *N) const;
62
63   SDNode *Select(SDNode *N) override;
64
65   // Complex Pattern Selectors.
66   inline bool foldGlobalAddress(SDValue &N, SDValue &R);
67   inline bool foldGlobalAddressGP(SDValue &N, SDValue &R);
68   bool foldGlobalAddressImpl(SDValue &N, SDValue &R, bool ShouldLookForGP);
69   bool SelectADDRri(SDValue& N, SDValue &R1, SDValue &R2);
70   bool SelectADDRriS11_0(SDValue& N, SDValue &R1, SDValue &R2);
71   bool SelectADDRriS11_1(SDValue& N, SDValue &R1, SDValue &R2);
72   bool SelectADDRriS11_2(SDValue& N, SDValue &R1, SDValue &R2);
73   bool SelectMEMriS11_2(SDValue& Addr, SDValue &Base, SDValue &Offset);
74   bool SelectADDRriS11_3(SDValue& N, SDValue &R1, SDValue &R2);
75   bool SelectADDRrr(SDValue &Addr, SDValue &Base, SDValue &Offset);
76   bool SelectADDRriU6_0(SDValue& N, SDValue &R1, SDValue &R2);
77   bool SelectADDRriU6_1(SDValue& N, SDValue &R1, SDValue &R2);
78   bool SelectADDRriU6_2(SDValue& N, SDValue &R1, SDValue &R2);
79
80   // Complex Pattern Selectors.
81   inline bool SelectAddrGA(SDValue &N, SDValue &R);
82   inline bool SelectAddrGP(SDValue &N, SDValue &R);
83   bool SelectGlobalAddress(SDValue &N, SDValue &R, bool UseGP);
84   bool SelectAddrFI(SDValue &N, SDValue &R);
85
86   const char *getPassName() const override {
87     return "Hexagon DAG->DAG Pattern Instruction Selection";
88   }
89
90   bool runOnMachineFunction(MachineFunction &MF) override {
91     Subtarget = &MF.getSubtarget<HexagonSubtarget>();
92     return SelectionDAGISel::runOnMachineFunction(MF);
93   }
94
95   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
96   /// inline asm expressions.
97   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
98                                     char ConstraintCode,
99                                     std::vector<SDValue> &OutOps) override;
100   bool SelectAddr(SDNode *Op, SDValue Addr, SDValue &Base, SDValue &Offset);
101
102   SDNode *SelectLoad(SDNode *N);
103   SDNode *SelectBaseOffsetLoad(LoadSDNode *LD, SDLoc dl);
104   SDNode *SelectIndexedLoad(LoadSDNode *LD, SDLoc dl);
105   SDNode *SelectIndexedLoadZeroExtend64(LoadSDNode *LD, unsigned Opcode,
106                                         SDLoc dl);
107   SDNode *SelectIndexedLoadSignExtend64(LoadSDNode *LD, unsigned Opcode,
108                                         SDLoc dl);
109   SDNode *SelectBaseOffsetStore(StoreSDNode *ST, SDLoc dl);
110   SDNode *SelectIndexedStore(StoreSDNode *ST, SDLoc dl);
111   SDNode *SelectStore(SDNode *N);
112   SDNode *SelectSHL(SDNode *N);
113   SDNode *SelectSelect(SDNode *N);
114   SDNode *SelectTruncate(SDNode *N);
115   SDNode *SelectMul(SDNode *N);
116   SDNode *SelectZeroExtend(SDNode *N);
117   SDNode *SelectIntrinsicWOChain(SDNode *N);
118   SDNode *SelectIntrinsicWChain(SDNode *N);
119   SDNode *SelectConstant(SDNode *N);
120   SDNode *SelectConstantFP(SDNode *N);
121   SDNode *SelectAdd(SDNode *N);
122   bool isConstExtProfitable(SDNode *N) const;
123
124 // XformMskToBitPosU5Imm - Returns the bit position which
125 // the single bit 32 bit mask represents.
126 // Used in Clr and Set bit immediate memops.
127 SDValue XformMskToBitPosU5Imm(uint32_t Imm) {
128   int32_t bitPos;
129   bitPos = Log2_32(Imm);
130   assert(bitPos >= 0 && bitPos < 32 &&
131          "Constant out of range for 32 BitPos Memops");
132   return CurDAG->getTargetConstant(bitPos, MVT::i32);
133 }
134
135 // XformMskToBitPosU4Imm - Returns the bit position which the single bit 16 bit
136 // mask represents. Used in Clr and Set bit immediate memops.
137 SDValue XformMskToBitPosU4Imm(uint16_t Imm) {
138   return XformMskToBitPosU5Imm(Imm);
139 }
140
141 // XformMskToBitPosU3Imm - Returns the bit position which the single bit 8 bit
142 // mask represents. Used in Clr and Set bit immediate memops.
143 SDValue XformMskToBitPosU3Imm(uint8_t Imm) {
144   return XformMskToBitPosU5Imm(Imm);
145 }
146
147 // Return true if there is exactly one bit set in V, i.e., if V is one of the
148 // following integers: 2^0, 2^1, ..., 2^31.
149 bool ImmIsSingleBit(uint32_t v) const {
150   uint32_t c = CountPopulation_64(v);
151   // Only return true if we counted 1 bit.
152   return c == 1;
153 }
154
155 // XformM5ToU5Imm - Return a target constant with the specified value, of type
156 // i32 where the negative literal is transformed into a positive literal for
157 // use in -= memops.
158 inline SDValue XformM5ToU5Imm(signed Imm) {
159    assert( (Imm >= -31 && Imm <= -1)  && "Constant out of range for Memops");
160    return CurDAG->getTargetConstant( - Imm, MVT::i32);
161 }
162
163
164 // XformU7ToU7M1Imm - Return a target constant decremented by 1, in range
165 // [1..128], used in cmpb.gtu instructions.
166 inline SDValue XformU7ToU7M1Imm(signed Imm) {
167   assert((Imm >= 1 && Imm <= 128) && "Constant out of range for cmpb op");
168   return CurDAG->getTargetConstant(Imm - 1, MVT::i8);
169 }
170
171 // XformS8ToS8M1Imm - Return a target constant decremented by 1.
172 inline SDValue XformSToSM1Imm(signed Imm) {
173   return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
174 }
175
176 // XformU8ToU8M1Imm - Return a target constant decremented by 1.
177 inline SDValue XformUToUM1Imm(unsigned Imm) {
178   assert((Imm >= 1) && "Cannot decrement unsigned int less than 1");
179   return CurDAG->getTargetConstant(Imm - 1, MVT::i32);
180 }
181
182 // XformSToSM2Imm - Return a target constant decremented by 2.
183 inline SDValue XformSToSM2Imm(unsigned Imm) {
184   return CurDAG->getTargetConstant(Imm - 2, MVT::i32);
185 }
186
187 // XformSToSM3Imm - Return a target constant decremented by 3.
188 inline SDValue XformSToSM3Imm(unsigned Imm) {
189   return CurDAG->getTargetConstant(Imm - 3, MVT::i32);
190 }
191
192 // Include the pieces autogenerated from the target description.
193 #include "HexagonGenDAGISel.inc"
194
195 private:
196   bool isValueExtension(SDValue const &Val, unsigned FromBits, SDValue &Src);
197 };
198 }  // end anonymous namespace
199
200
201 /// createHexagonISelDag - This pass converts a legalized DAG into a
202 /// Hexagon-specific DAG, ready for instruction scheduling.
203 ///
204 FunctionPass *llvm::createHexagonISelDag(HexagonTargetMachine &TM,
205                                          CodeGenOpt::Level OptLevel) {
206   return new HexagonDAGToDAGISel(TM, OptLevel);
207 }
208
209 static void initializePassOnce(PassRegistry &Registry) {
210   const char *Name = "Hexagon DAG->DAG Pattern Instruction Selection";
211   PassInfo *PI = new PassInfo(Name, "hexagon-isel",
212                               &SelectionDAGISel::ID, nullptr, false, false);
213   Registry.registerPass(*PI, true);
214 }
215
216 void llvm::initializeHexagonDAGToDAGISelPass(PassRegistry &Registry) {
217   CALL_ONCE_INITIALIZATION(initializePassOnce)
218 }
219
220
221 static bool IsS11_0_Offset(SDNode * S) {
222     ConstantSDNode *N = cast<ConstantSDNode>(S);
223
224   // immS16 predicate - True if the immediate fits in a 16-bit sign extended
225   // field.
226   int64_t v = (int64_t)N->getSExtValue();
227   return isInt<11>(v);
228 }
229
230
231 static bool IsS11_1_Offset(SDNode * S) {
232     ConstantSDNode *N = cast<ConstantSDNode>(S);
233
234   // immS16 predicate - True if the immediate fits in a 16-bit sign extended
235   // field.
236   int64_t v = (int64_t)N->getSExtValue();
237   return isShiftedInt<11,1>(v);
238 }
239
240
241 static bool IsS11_2_Offset(SDNode * S) {
242     ConstantSDNode *N = cast<ConstantSDNode>(S);
243
244   // immS16 predicate - True if the immediate fits in a 16-bit sign extended
245   // field.
246   int64_t v = (int64_t)N->getSExtValue();
247   return isShiftedInt<11,2>(v);
248 }
249
250
251 static bool IsS11_3_Offset(SDNode * S) {
252     ConstantSDNode *N = cast<ConstantSDNode>(S);
253
254   // immS16 predicate - True if the immediate fits in a 16-bit sign extended
255   // field.
256   int64_t v = (int64_t)N->getSExtValue();
257   return isShiftedInt<11,3>(v);
258 }
259
260
261 static bool IsU6_0_Offset(SDNode * S) {
262     ConstantSDNode *N = cast<ConstantSDNode>(S);
263
264   // u6 predicate - True if the immediate fits in a 6-bit unsigned extended
265   // field.
266   int64_t v = (int64_t)N->getSExtValue();
267   return isUInt<6>(v);
268 }
269
270
271 static bool IsU6_1_Offset(SDNode * S) {
272     ConstantSDNode *N = cast<ConstantSDNode>(S);
273
274   // u6 predicate - True if the immediate fits in a 6-bit unsigned extended
275   // field.
276   int64_t v = (int64_t)N->getSExtValue();
277   return isShiftedUInt<6,1>(v);
278 }
279
280
281 static bool IsU6_2_Offset(SDNode * S) {
282     ConstantSDNode *N = cast<ConstantSDNode>(S);
283
284   // u6 predicate - True if the immediate fits in a 6-bit unsigned extended
285   // field.
286   int64_t v = (int64_t)N->getSExtValue();
287   return isShiftedUInt<6,2>(v);
288 }
289
290
291 // Intrinsics that return a a predicate.
292 static unsigned doesIntrinsicReturnPredicate(unsigned ID)
293 {
294   switch (ID) {
295     default:
296       return 0;
297     case Intrinsic::hexagon_C2_cmpeq:
298     case Intrinsic::hexagon_C2_cmpgt:
299     case Intrinsic::hexagon_C2_cmpgtu:
300     case Intrinsic::hexagon_C2_cmpgtup:
301     case Intrinsic::hexagon_C2_cmpgtp:
302     case Intrinsic::hexagon_C2_cmpeqp:
303     case Intrinsic::hexagon_C2_bitsset:
304     case Intrinsic::hexagon_C2_bitsclr:
305     case Intrinsic::hexagon_C2_cmpeqi:
306     case Intrinsic::hexagon_C2_cmpgti:
307     case Intrinsic::hexagon_C2_cmpgtui:
308     case Intrinsic::hexagon_C2_cmpgei:
309     case Intrinsic::hexagon_C2_cmpgeui:
310     case Intrinsic::hexagon_C2_cmplt:
311     case Intrinsic::hexagon_C2_cmpltu:
312     case Intrinsic::hexagon_C2_bitsclri:
313     case Intrinsic::hexagon_C2_and:
314     case Intrinsic::hexagon_C2_or:
315     case Intrinsic::hexagon_C2_xor:
316     case Intrinsic::hexagon_C2_andn:
317     case Intrinsic::hexagon_C2_not:
318     case Intrinsic::hexagon_C2_orn:
319     case Intrinsic::hexagon_C2_pxfer_map:
320     case Intrinsic::hexagon_C2_any8:
321     case Intrinsic::hexagon_C2_all8:
322     case Intrinsic::hexagon_A2_vcmpbeq:
323     case Intrinsic::hexagon_A2_vcmpbgtu:
324     case Intrinsic::hexagon_A2_vcmpheq:
325     case Intrinsic::hexagon_A2_vcmphgt:
326     case Intrinsic::hexagon_A2_vcmphgtu:
327     case Intrinsic::hexagon_A2_vcmpweq:
328     case Intrinsic::hexagon_A2_vcmpwgt:
329     case Intrinsic::hexagon_A2_vcmpwgtu:
330     case Intrinsic::hexagon_C2_tfrrp:
331     case Intrinsic::hexagon_S2_tstbit_i:
332     case Intrinsic::hexagon_S2_tstbit_r:
333       return 1;
334   }
335 }
336
337 static bool OffsetFitsS11(EVT MemType, int64_t Offset) {
338   if (MemType == MVT::i64 && isShiftedInt<11,3>(Offset)) {
339     return true;
340   }
341   if (MemType == MVT::i32 && isShiftedInt<11,2>(Offset)) {
342     return true;
343   }
344   if (MemType == MVT::i16 && isShiftedInt<11,1>(Offset)) {
345     return true;
346   }
347   if (MemType == MVT::i8 && isInt<11>(Offset)) {
348     return true;
349   }
350   return false;
351 }
352
353
354 //
355 // Try to lower loads of GlobalAdresses into base+offset loads.  Custom
356 // lowering for GlobalAddress nodes has already turned it into a
357 // CONST32.
358 //
359 SDNode *HexagonDAGToDAGISel::SelectBaseOffsetLoad(LoadSDNode *LD, SDLoc dl) {
360   SDValue Chain = LD->getChain();
361   SDNode* Const32 = LD->getBasePtr().getNode();
362   unsigned Opcode = 0;
363
364   if (Const32->getOpcode() == HexagonISD::CONST32 &&
365       ISD::isNormalLoad(LD)) {
366     SDValue Base = Const32->getOperand(0);
367     EVT LoadedVT = LD->getMemoryVT();
368     int64_t Offset = cast<GlobalAddressSDNode>(Base)->getOffset();
369     if (Offset != 0 && OffsetFitsS11(LoadedVT, Offset)) {
370       MVT PointerTy = getTargetLowering()->getPointerTy();
371       const GlobalValue* GV =
372         cast<GlobalAddressSDNode>(Base)->getGlobal();
373       SDValue TargAddr =
374         CurDAG->getTargetGlobalAddress(GV, dl, PointerTy, 0);
375       SDNode* NewBase = CurDAG->getMachineNode(Hexagon::CONST32_set,
376                                                dl, PointerTy,
377                                                TargAddr);
378       // Figure out base + offset opcode
379       if (LoadedVT == MVT::i64) Opcode = Hexagon::L2_loadrd_io;
380       else if (LoadedVT == MVT::i32) Opcode = Hexagon::L2_loadri_io;
381       else if (LoadedVT == MVT::i16) Opcode = Hexagon::L2_loadrh_io;
382       else if (LoadedVT == MVT::i8) Opcode = Hexagon::L2_loadrb_io;
383       else llvm_unreachable("unknown memory type");
384
385       // Build indexed load.
386       SDValue TargetConstOff = CurDAG->getTargetConstant(Offset, PointerTy);
387       SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
388                                               LD->getValueType(0),
389                                               MVT::Other,
390                                               SDValue(NewBase,0),
391                                               TargetConstOff,
392                                               Chain);
393       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
394       MemOp[0] = LD->getMemOperand();
395       cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
396       ReplaceUses(LD, Result);
397       return Result;
398     }
399   }
400
401   return SelectCode(LD);
402 }
403
404
405 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadSignExtend64(LoadSDNode *LD,
406                                                            unsigned Opcode,
407                                                            SDLoc dl)
408 {
409   SDValue Chain = LD->getChain();
410   EVT LoadedVT = LD->getMemoryVT();
411   SDValue Base = LD->getBasePtr();
412   SDValue Offset = LD->getOffset();
413   SDNode *OffsetNode = Offset.getNode();
414   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
415   SDValue N1 = LD->getOperand(1);
416   SDValue CPTmpN1_0;
417   SDValue CPTmpN1_1;
418
419   if (SelectADDRriS11_2(N1, CPTmpN1_0, CPTmpN1_1) &&
420       N1.getNode()->getValueType(0) == MVT::i32) {
421     const HexagonInstrInfo *TII = Subtarget->getInstrInfo();
422     if (TII->isValidAutoIncImm(LoadedVT, Val)) {
423       SDValue TargetConst = CurDAG->getTargetConstant(Val, MVT::i32);
424       SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::i32,
425                                                 MVT::Other, Base, TargetConst,
426                                                 Chain);
427       SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl, MVT::i64,
428                                                 SDValue(Result_1, 0));
429       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
430       MemOp[0] = LD->getMemOperand();
431       cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
432       const SDValue Froms[] = { SDValue(LD, 0),
433                                 SDValue(LD, 1),
434                                 SDValue(LD, 2)
435       };
436       const SDValue Tos[]   = { SDValue(Result_2, 0),
437                                 SDValue(Result_1, 1),
438                                 SDValue(Result_1, 2)
439       };
440       ReplaceUses(Froms, Tos, 3);
441       return Result_2;
442     }
443     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
444     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
445     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
446                                               MVT::Other, Base, TargetConst0,
447                                               Chain);
448     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_sxtw, dl,
449                                                 MVT::i64, SDValue(Result_1, 0));
450     SDNode* Result_3 = CurDAG->getMachineNode(Hexagon::A2_addi, dl,
451                                               MVT::i32, Base, TargetConstVal,
452                                                 SDValue(Result_1, 1));
453     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
454     MemOp[0] = LD->getMemOperand();
455     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
456     const SDValue Froms[] = { SDValue(LD, 0),
457                               SDValue(LD, 1),
458                               SDValue(LD, 2)
459     };
460     const SDValue Tos[]   = { SDValue(Result_2, 0),
461                               SDValue(Result_3, 0),
462                               SDValue(Result_1, 1)
463     };
464     ReplaceUses(Froms, Tos, 3);
465     return Result_2;
466   }
467   return SelectCode(LD);
468 }
469
470
471 SDNode *HexagonDAGToDAGISel::SelectIndexedLoadZeroExtend64(LoadSDNode *LD,
472                                                            unsigned Opcode,
473                                                            SDLoc dl)
474 {
475   SDValue Chain = LD->getChain();
476   EVT LoadedVT = LD->getMemoryVT();
477   SDValue Base = LD->getBasePtr();
478   SDValue Offset = LD->getOffset();
479   SDNode *OffsetNode = Offset.getNode();
480   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
481   SDValue N1 = LD->getOperand(1);
482   SDValue CPTmpN1_0;
483   SDValue CPTmpN1_1;
484
485   if (SelectADDRriS11_2(N1, CPTmpN1_0, CPTmpN1_1) &&
486       N1.getNode()->getValueType(0) == MVT::i32) {
487     const HexagonInstrInfo *TII = Subtarget->getInstrInfo();
488     if (TII->isValidAutoIncImm(LoadedVT, Val)) {
489       SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
490       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
491       SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
492                                                 MVT::i32, MVT::Other, Base,
493                                                 TargetConstVal, Chain);
494       SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32,
495                                                 TargetConst0);
496       SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
497                                                 MVT::i64, MVT::Other,
498                                                 SDValue(Result_2,0),
499                                                 SDValue(Result_1,0));
500       MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
501       MemOp[0] = LD->getMemOperand();
502       cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
503       const SDValue Froms[] = { SDValue(LD, 0),
504                                 SDValue(LD, 1),
505                                 SDValue(LD, 2)
506       };
507       const SDValue Tos[]   = { SDValue(Result_3, 0),
508                                 SDValue(Result_1, 1),
509                                 SDValue(Result_1, 2)
510       };
511       ReplaceUses(Froms, Tos, 3);
512       return Result_3;
513     }
514
515     // Generate an indirect load.
516     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
517     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
518     SDNode *Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
519                                               MVT::Other,
520                                               Base, TargetConst0, Chain);
521     SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32,
522                                               TargetConst0);
523     SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
524                                               MVT::i64, MVT::Other,
525                                               SDValue(Result_2,0),
526                                               SDValue(Result_1,0));
527     // Add offset to base.
528     SDNode* Result_4 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
529                                               Base, TargetConstVal,
530                                               SDValue(Result_1, 1));
531     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
532     MemOp[0] = LD->getMemOperand();
533     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
534     const SDValue Froms[] = { SDValue(LD, 0),
535                               SDValue(LD, 1),
536                               SDValue(LD, 2)
537     };
538     const SDValue Tos[]   = { SDValue(Result_3, 0), // Load value.
539                               SDValue(Result_4, 0), // New address.
540                               SDValue(Result_1, 1)
541     };
542     ReplaceUses(Froms, Tos, 3);
543     return Result_3;
544   }
545
546   return SelectCode(LD);
547 }
548
549
550 SDNode *HexagonDAGToDAGISel::SelectIndexedLoad(LoadSDNode *LD, SDLoc dl) {
551   SDValue Chain = LD->getChain();
552   SDValue Base = LD->getBasePtr();
553   SDValue Offset = LD->getOffset();
554   SDNode *OffsetNode = Offset.getNode();
555   // Get the constant value.
556   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
557   EVT LoadedVT = LD->getMemoryVT();
558   unsigned Opcode = 0;
559
560   // Check for zero ext loads.
561   bool zextval = (LD->getExtensionType() == ISD::ZEXTLOAD);
562
563   // Figure out the opcode.
564   const HexagonInstrInfo *TII = Subtarget->getInstrInfo();
565   if (LoadedVT == MVT::i64) {
566     if (TII->isValidAutoIncImm(LoadedVT, Val))
567       Opcode = Hexagon::L2_loadrd_pi;
568     else
569       Opcode = Hexagon::L2_loadrd_io;
570   } else if (LoadedVT == MVT::i32) {
571     if (TII->isValidAutoIncImm(LoadedVT, Val))
572       Opcode = Hexagon::L2_loadri_pi;
573     else
574       Opcode = Hexagon::L2_loadri_io;
575   } else if (LoadedVT == MVT::i16) {
576     if (TII->isValidAutoIncImm(LoadedVT, Val))
577       Opcode = zextval ? Hexagon::L2_loadruh_pi : Hexagon::L2_loadrh_pi;
578     else
579       Opcode = zextval ? Hexagon::L2_loadruh_io : Hexagon::L2_loadrh_io;
580   } else if (LoadedVT == MVT::i8) {
581     if (TII->isValidAutoIncImm(LoadedVT, Val))
582       Opcode = zextval ? Hexagon::L2_loadrub_pi : Hexagon::L2_loadrb_pi;
583     else
584       Opcode = zextval ? Hexagon::L2_loadrub_io : Hexagon::L2_loadrb_io;
585   } else
586     llvm_unreachable("unknown memory type");
587
588   // For zero ext i64 loads, we need to add combine instructions.
589   if (LD->getValueType(0) == MVT::i64 &&
590       LD->getExtensionType() == ISD::ZEXTLOAD) {
591     return SelectIndexedLoadZeroExtend64(LD, Opcode, dl);
592   }
593   if (LD->getValueType(0) == MVT::i64 &&
594              LD->getExtensionType() == ISD::SEXTLOAD) {
595     // Handle sign ext i64 loads.
596     return SelectIndexedLoadSignExtend64(LD, Opcode, dl);
597   }
598   if (TII->isValidAutoIncImm(LoadedVT, Val)) {
599     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
600     SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
601                                             LD->getValueType(0),
602                                             MVT::i32, MVT::Other, Base,
603                                             TargetConstVal, Chain);
604     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
605     MemOp[0] = LD->getMemOperand();
606     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
607     const SDValue Froms[] = { SDValue(LD, 0),
608                               SDValue(LD, 1),
609                               SDValue(LD, 2)
610     };
611     const SDValue Tos[]   = { SDValue(Result, 0),
612                               SDValue(Result, 1),
613                               SDValue(Result, 2)
614     };
615     ReplaceUses(Froms, Tos, 3);
616     return Result;
617   } else {
618     SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
619     SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
620     SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl,
621                                               LD->getValueType(0),
622                                               MVT::Other, Base, TargetConst0,
623                                               Chain);
624     SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
625                                               Base, TargetConstVal,
626                                               SDValue(Result_1, 1));
627     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
628     MemOp[0] = LD->getMemOperand();
629     cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
630     const SDValue Froms[] = { SDValue(LD, 0),
631                               SDValue(LD, 1),
632                               SDValue(LD, 2)
633     };
634     const SDValue Tos[]   = { SDValue(Result_1, 0),
635                               SDValue(Result_2, 0),
636                               SDValue(Result_1, 1)
637     };
638     ReplaceUses(Froms, Tos, 3);
639     return Result_1;
640   }
641 }
642
643
644 SDNode *HexagonDAGToDAGISel::SelectLoad(SDNode *N) {
645   SDNode *result;
646   SDLoc dl(N);
647   LoadSDNode *LD = cast<LoadSDNode>(N);
648   ISD::MemIndexedMode AM = LD->getAddressingMode();
649
650   // Handle indexed loads.
651   if (AM != ISD::UNINDEXED) {
652     result = SelectIndexedLoad(LD, dl);
653   } else {
654     result = SelectBaseOffsetLoad(LD, dl);
655   }
656
657   return result;
658 }
659
660
661 SDNode *HexagonDAGToDAGISel::SelectIndexedStore(StoreSDNode *ST, SDLoc dl) {
662   SDValue Chain = ST->getChain();
663   SDValue Base = ST->getBasePtr();
664   SDValue Offset = ST->getOffset();
665   SDValue Value = ST->getValue();
666   SDNode *OffsetNode = Offset.getNode();
667   // Get the constant value.
668   int32_t Val = cast<ConstantSDNode>(OffsetNode)->getSExtValue();
669   EVT StoredVT = ST->getMemoryVT();
670
671   // Offset value must be within representable range
672   // and must have correct alignment properties.
673   const HexagonInstrInfo *TII = Subtarget->getInstrInfo();
674   if (TII->isValidAutoIncImm(StoredVT, Val)) {
675     SDValue Ops[] = {Base, CurDAG->getTargetConstant(Val, MVT::i32), Value,
676                      Chain};
677     unsigned Opcode = 0;
678
679     // Figure out the post inc version of opcode.
680     if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_pi;
681     else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_pi;
682     else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_pi;
683     else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_pi;
684     else llvm_unreachable("unknown memory type");
685
686     // Build post increment store.
687     SDNode* Result = CurDAG->getMachineNode(Opcode, dl, MVT::i32,
688                                             MVT::Other, Ops);
689     MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
690     MemOp[0] = ST->getMemOperand();
691     cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
692
693     ReplaceUses(ST, Result);
694     ReplaceUses(SDValue(ST,1), SDValue(Result,1));
695     return Result;
696   }
697
698   // Note: Order of operands matches the def of instruction:
699   // def STrid : STInst<(outs), (ins MEMri:$addr, DoubleRegs:$src1), ...
700   // and it differs for POST_ST* for instance.
701   SDValue Ops[] = { Base, CurDAG->getTargetConstant(0, MVT::i32), Value,
702                     Chain};
703   unsigned Opcode = 0;
704
705   // Figure out the opcode.
706   if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_io;
707   else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_io;
708   else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_io;
709   else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_io;
710   else llvm_unreachable("unknown memory type");
711
712   // Build regular store.
713   SDValue TargetConstVal = CurDAG->getTargetConstant(Val, MVT::i32);
714   SDNode* Result_1 = CurDAG->getMachineNode(Opcode, dl, MVT::Other, Ops);
715   // Build splitted incriment instruction.
716   SDNode* Result_2 = CurDAG->getMachineNode(Hexagon::A2_addi, dl, MVT::i32,
717                                             Base,
718                                             TargetConstVal,
719                                             SDValue(Result_1, 0));
720   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
721   MemOp[0] = ST->getMemOperand();
722   cast<MachineSDNode>(Result_1)->setMemRefs(MemOp, MemOp + 1);
723
724   ReplaceUses(SDValue(ST,0), SDValue(Result_2,0));
725   ReplaceUses(SDValue(ST,1), SDValue(Result_1,0));
726   return Result_2;
727 }
728
729
730 SDNode *HexagonDAGToDAGISel::SelectBaseOffsetStore(StoreSDNode *ST,
731                                                    SDLoc dl) {
732   SDValue Chain = ST->getChain();
733   SDNode* Const32 = ST->getBasePtr().getNode();
734   SDValue Value = ST->getValue();
735   unsigned Opcode = 0;
736
737   // Try to lower stores of GlobalAdresses into indexed stores.  Custom
738   // lowering for GlobalAddress nodes has already turned it into a
739   // CONST32.  Avoid truncating stores for the moment.  Post-inc stores
740   // do the same.  Don't think there's a reason for it, so will file a
741   // bug to fix.
742   if ((Const32->getOpcode() == HexagonISD::CONST32) &&
743       !(Value.getValueType() == MVT::i64 && ST->isTruncatingStore())) {
744     SDValue Base = Const32->getOperand(0);
745     if (Base.getOpcode() == ISD::TargetGlobalAddress) {
746       EVT StoredVT = ST->getMemoryVT();
747       int64_t Offset = cast<GlobalAddressSDNode>(Base)->getOffset();
748       if (Offset != 0 && OffsetFitsS11(StoredVT, Offset)) {
749         MVT PointerTy = getTargetLowering()->getPointerTy();
750         const GlobalValue* GV =
751           cast<GlobalAddressSDNode>(Base)->getGlobal();
752         SDValue TargAddr =
753           CurDAG->getTargetGlobalAddress(GV, dl, PointerTy, 0);
754         SDNode* NewBase = CurDAG->getMachineNode(Hexagon::CONST32_set,
755                                                  dl, PointerTy,
756                                                  TargAddr);
757
758         // Figure out base + offset opcode
759         if (StoredVT == MVT::i64) Opcode = Hexagon::S2_storerd_io;
760         else if (StoredVT == MVT::i32) Opcode = Hexagon::S2_storeri_io;
761         else if (StoredVT == MVT::i16) Opcode = Hexagon::S2_storerh_io;
762         else if (StoredVT == MVT::i8) Opcode = Hexagon::S2_storerb_io;
763         else llvm_unreachable("unknown memory type");
764
765         SDValue Ops[] = {SDValue(NewBase,0),
766                          CurDAG->getTargetConstant(Offset,PointerTy),
767                          Value, Chain};
768         // build indexed store
769         SDNode* Result = CurDAG->getMachineNode(Opcode, dl,
770                                                 MVT::Other, Ops);
771         MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
772         MemOp[0] = ST->getMemOperand();
773         cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
774         ReplaceUses(ST, Result);
775         return Result;
776       }
777     }
778   }
779
780   return SelectCode(ST);
781 }
782
783
784 SDNode *HexagonDAGToDAGISel::SelectStore(SDNode *N) {
785   SDLoc dl(N);
786   StoreSDNode *ST = cast<StoreSDNode>(N);
787   ISD::MemIndexedMode AM = ST->getAddressingMode();
788
789   // Handle indexed stores.
790   if (AM != ISD::UNINDEXED) {
791     return SelectIndexedStore(ST, dl);
792   }
793
794   return SelectBaseOffsetStore(ST, dl);
795 }
796
797 SDNode *HexagonDAGToDAGISel::SelectMul(SDNode *N) {
798   SDLoc dl(N);
799
800   //
801   // %conv.i = sext i32 %tmp1 to i64
802   // %conv2.i = sext i32 %add to i64
803   // %mul.i = mul nsw i64 %conv2.i, %conv.i
804   //
805   //   --- match with the following ---
806   //
807   // %mul.i = mpy (%tmp1, %add)
808   //
809
810   if (N->getValueType(0) == MVT::i64) {
811     // Shifting a i64 signed multiply.
812     SDValue MulOp0 = N->getOperand(0);
813     SDValue MulOp1 = N->getOperand(1);
814
815     SDValue OP0;
816     SDValue OP1;
817
818     // Handle sign_extend and sextload.
819     if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
820       SDValue Sext0 = MulOp0.getOperand(0);
821       if (Sext0.getNode()->getValueType(0) != MVT::i32) {
822         return SelectCode(N);
823       }
824
825       OP0 = Sext0;
826     } else if (MulOp0.getOpcode() == ISD::LOAD) {
827       LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
828       if (LD->getMemoryVT() != MVT::i32 ||
829           LD->getExtensionType() != ISD::SEXTLOAD ||
830           LD->getAddressingMode() != ISD::UNINDEXED) {
831         return SelectCode(N);
832       }
833
834       SDValue Chain = LD->getChain();
835       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
836       OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
837                                             MVT::Other,
838                                             LD->getBasePtr(), TargetConst0,
839                                             Chain), 0);
840     } else {
841       return SelectCode(N);
842     }
843
844     // Same goes for the second operand.
845     if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
846       SDValue Sext1 = MulOp1.getOperand(0);
847       if (Sext1.getNode()->getValueType(0) != MVT::i32) {
848         return SelectCode(N);
849       }
850
851       OP1 = Sext1;
852     } else if (MulOp1.getOpcode() == ISD::LOAD) {
853       LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
854       if (LD->getMemoryVT() != MVT::i32 ||
855           LD->getExtensionType() != ISD::SEXTLOAD ||
856           LD->getAddressingMode() != ISD::UNINDEXED) {
857         return SelectCode(N);
858       }
859
860       SDValue Chain = LD->getChain();
861       SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
862       OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
863                                             MVT::Other,
864                                             LD->getBasePtr(), TargetConst0,
865                                             Chain), 0);
866     } else {
867       return SelectCode(N);
868     }
869
870     // Generate a mpy instruction.
871     SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_dpmpyss_s0, dl, MVT::i64,
872                                             OP0, OP1);
873     ReplaceUses(N, Result);
874     return Result;
875   }
876
877   return SelectCode(N);
878 }
879
880
881 SDNode *HexagonDAGToDAGISel::SelectSelect(SDNode *N) {
882   SDLoc dl(N);
883   SDValue N0 = N->getOperand(0);
884   if (N0.getOpcode() == ISD::SETCC) {
885     SDValue N00 = N0.getOperand(0);
886     if (N00.getOpcode() == ISD::SIGN_EXTEND_INREG) {
887       SDValue N000 = N00.getOperand(0);
888       SDValue N001 = N00.getOperand(1);
889       if (cast<VTSDNode>(N001)->getVT() == MVT::i16) {
890         SDValue N01 = N0.getOperand(1);
891         SDValue N02 = N0.getOperand(2);
892
893         // Pattern: (select:i32 (setcc:i1 (sext_inreg:i32 IntRegs:i32:$src2,
894         // i16:Other),IntRegs:i32:$src1, SETLT:Other),IntRegs:i32:$src1,
895         // IntRegs:i32:$src2)
896         // Emits: (MAXh_rr:i32 IntRegs:i32:$src1, IntRegs:i32:$src2)
897         // Pattern complexity = 9  cost = 1  size = 0.
898         if (cast<CondCodeSDNode>(N02)->get() == ISD::SETLT) {
899           SDValue N1 = N->getOperand(1);
900           if (N01 == N1) {
901             SDValue N2 = N->getOperand(2);
902             if (N000 == N2 &&
903                 N0.getNode()->getValueType(N0.getResNo()) == MVT::i1 &&
904                 N00.getNode()->getValueType(N00.getResNo()) == MVT::i32) {
905               SDNode *SextNode = CurDAG->getMachineNode(Hexagon::A2_sxth, dl,
906                                                         MVT::i32, N000);
907               SDNode *Result = CurDAG->getMachineNode(Hexagon::A2_max, dl,
908                                                       MVT::i32,
909                                                       SDValue(SextNode, 0),
910                                                       N1);
911               ReplaceUses(N, Result);
912               return Result;
913             }
914           }
915         }
916
917         // Pattern: (select:i32 (setcc:i1 (sext_inreg:i32 IntRegs:i32:$src2,
918         // i16:Other), IntRegs:i32:$src1, SETGT:Other), IntRegs:i32:$src1,
919         // IntRegs:i32:$src2)
920         // Emits: (MINh_rr:i32 IntRegs:i32:$src1, IntRegs:i32:$src2)
921         // Pattern complexity = 9  cost = 1  size = 0.
922         if (cast<CondCodeSDNode>(N02)->get() == ISD::SETGT) {
923           SDValue N1 = N->getOperand(1);
924           if (N01 == N1) {
925             SDValue N2 = N->getOperand(2);
926             if (N000 == N2 &&
927                 N0.getNode()->getValueType(N0.getResNo()) == MVT::i1 &&
928                 N00.getNode()->getValueType(N00.getResNo()) == MVT::i32) {
929               SDNode *SextNode = CurDAG->getMachineNode(Hexagon::A2_sxth, dl,
930                                                         MVT::i32, N000);
931               SDNode *Result = CurDAG->getMachineNode(Hexagon::A2_min, dl,
932                                                       MVT::i32,
933                                                       SDValue(SextNode, 0),
934                                                       N1);
935               ReplaceUses(N, Result);
936               return Result;
937             }
938           }
939         }
940       }
941     }
942   }
943
944   return SelectCode(N);
945 }
946
947
948 SDNode *HexagonDAGToDAGISel::SelectTruncate(SDNode *N) {
949   SDLoc dl(N);
950   SDValue Shift = N->getOperand(0);
951
952   //
953   // %conv.i = sext i32 %tmp1 to i64
954   // %conv2.i = sext i32 %add to i64
955   // %mul.i = mul nsw i64 %conv2.i, %conv.i
956   // %shr5.i = lshr i64 %mul.i, 32
957   // %conv3.i = trunc i64 %shr5.i to i32
958   //
959   //   --- match with the following ---
960   //
961   // %conv3.i = mpy (%tmp1, %add)
962   //
963   // Trunc to i32.
964   if (N->getValueType(0) == MVT::i32) {
965     // Trunc from i64.
966     if (Shift.getNode()->getValueType(0) == MVT::i64) {
967       // Trunc child is logical shift right.
968       if (Shift.getOpcode() != ISD::SRL) {
969         return SelectCode(N);
970       }
971
972       SDValue ShiftOp0 = Shift.getOperand(0);
973       SDValue ShiftOp1 = Shift.getOperand(1);
974
975       // Shift by const 32
976       if (ShiftOp1.getOpcode() != ISD::Constant) {
977         return SelectCode(N);
978       }
979
980       int32_t ShiftConst =
981         cast<ConstantSDNode>(ShiftOp1.getNode())->getSExtValue();
982       if (ShiftConst != 32) {
983         return SelectCode(N);
984       }
985
986       // Shifting a i64 signed multiply
987       SDValue Mul = ShiftOp0;
988       if (Mul.getOpcode() != ISD::MUL) {
989         return SelectCode(N);
990       }
991
992       SDValue MulOp0 = Mul.getOperand(0);
993       SDValue MulOp1 = Mul.getOperand(1);
994
995       SDValue OP0;
996       SDValue OP1;
997
998       // Handle sign_extend and sextload
999       if (MulOp0.getOpcode() == ISD::SIGN_EXTEND) {
1000         SDValue Sext0 = MulOp0.getOperand(0);
1001         if (Sext0.getNode()->getValueType(0) != MVT::i32) {
1002           return SelectCode(N);
1003         }
1004
1005         OP0 = Sext0;
1006       } else if (MulOp0.getOpcode() == ISD::LOAD) {
1007         LoadSDNode *LD = cast<LoadSDNode>(MulOp0.getNode());
1008         if (LD->getMemoryVT() != MVT::i32 ||
1009             LD->getExtensionType() != ISD::SEXTLOAD ||
1010             LD->getAddressingMode() != ISD::UNINDEXED) {
1011           return SelectCode(N);
1012         }
1013
1014         SDValue Chain = LD->getChain();
1015         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
1016         OP0 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
1017                                               MVT::Other,
1018                                               LD->getBasePtr(),
1019                                               TargetConst0, Chain), 0);
1020       } else {
1021         return SelectCode(N);
1022       }
1023
1024       // Same goes for the second operand.
1025       if (MulOp1.getOpcode() == ISD::SIGN_EXTEND) {
1026         SDValue Sext1 = MulOp1.getOperand(0);
1027         if (Sext1.getNode()->getValueType(0) != MVT::i32)
1028           return SelectCode(N);
1029
1030         OP1 = Sext1;
1031       } else if (MulOp1.getOpcode() == ISD::LOAD) {
1032         LoadSDNode *LD = cast<LoadSDNode>(MulOp1.getNode());
1033         if (LD->getMemoryVT() != MVT::i32 ||
1034             LD->getExtensionType() != ISD::SEXTLOAD ||
1035             LD->getAddressingMode() != ISD::UNINDEXED) {
1036           return SelectCode(N);
1037         }
1038
1039         SDValue Chain = LD->getChain();
1040         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
1041         OP1 = SDValue(CurDAG->getMachineNode(Hexagon::L2_loadri_io, dl, MVT::i32,
1042                                               MVT::Other,
1043                                               LD->getBasePtr(),
1044                                               TargetConst0, Chain), 0);
1045       } else {
1046         return SelectCode(N);
1047       }
1048
1049       // Generate a mpy instruction.
1050       SDNode *Result = CurDAG->getMachineNode(Hexagon::M2_mpy_up, dl, MVT::i32,
1051                                               OP0, OP1);
1052       ReplaceUses(N, Result);
1053       return Result;
1054     }
1055   }
1056
1057   return SelectCode(N);
1058 }
1059
1060
1061 SDNode *HexagonDAGToDAGISel::SelectSHL(SDNode *N) {
1062   SDLoc dl(N);
1063   if (N->getValueType(0) == MVT::i32) {
1064     SDValue Shl_0 = N->getOperand(0);
1065     SDValue Shl_1 = N->getOperand(1);
1066     // RHS is const.
1067     if (Shl_1.getOpcode() == ISD::Constant) {
1068       if (Shl_0.getOpcode() == ISD::MUL) {
1069         SDValue Mul_0 = Shl_0.getOperand(0); // Val
1070         SDValue Mul_1 = Shl_0.getOperand(1); // Const
1071         // RHS of mul is const.
1072         if (Mul_1.getOpcode() == ISD::Constant) {
1073           int32_t ShlConst =
1074             cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
1075           int32_t MulConst =
1076             cast<ConstantSDNode>(Mul_1.getNode())->getSExtValue();
1077           int32_t ValConst = MulConst << ShlConst;
1078           SDValue Val = CurDAG->getTargetConstant(ValConst,
1079                                                   MVT::i32);
1080           if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Val.getNode()))
1081             if (isInt<9>(CN->getSExtValue())) {
1082               SDNode* Result =
1083                 CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl,
1084                                        MVT::i32, Mul_0, Val);
1085               ReplaceUses(N, Result);
1086               return Result;
1087             }
1088
1089         }
1090       } else if (Shl_0.getOpcode() == ISD::SUB) {
1091         SDValue Sub_0 = Shl_0.getOperand(0); // Const 0
1092         SDValue Sub_1 = Shl_0.getOperand(1); // Val
1093         if (Sub_0.getOpcode() == ISD::Constant) {
1094           int32_t SubConst =
1095             cast<ConstantSDNode>(Sub_0.getNode())->getSExtValue();
1096           if (SubConst == 0) {
1097             if (Sub_1.getOpcode() == ISD::SHL) {
1098               SDValue Shl2_0 = Sub_1.getOperand(0); // Val
1099               SDValue Shl2_1 = Sub_1.getOperand(1); // Const
1100               if (Shl2_1.getOpcode() == ISD::Constant) {
1101                 int32_t ShlConst =
1102                   cast<ConstantSDNode>(Shl_1.getNode())->getSExtValue();
1103                 int32_t Shl2Const =
1104                   cast<ConstantSDNode>(Shl2_1.getNode())->getSExtValue();
1105                 int32_t ValConst = 1 << (ShlConst+Shl2Const);
1106                 SDValue Val = CurDAG->getTargetConstant(-ValConst, MVT::i32);
1107                 if (ConstantSDNode *CN =
1108                     dyn_cast<ConstantSDNode>(Val.getNode()))
1109                   if (isInt<9>(CN->getSExtValue())) {
1110                     SDNode* Result =
1111                       CurDAG->getMachineNode(Hexagon::M2_mpysmi, dl, MVT::i32,
1112                                              Shl2_0, Val);
1113                     ReplaceUses(N, Result);
1114                     return Result;
1115                   }
1116               }
1117             }
1118           }
1119         }
1120       }
1121     }
1122   }
1123   return SelectCode(N);
1124 }
1125
1126
1127 //
1128 // If there is an zero_extend followed an intrinsic in DAG (this means - the
1129 // result of the intrinsic is predicate); convert the zero_extend to
1130 // transfer instruction.
1131 //
1132 // Zero extend -> transfer is lowered here. Otherwise, zero_extend will be
1133 // converted into a MUX as predicate registers defined as 1 bit in the
1134 // compiler. Architecture defines them as 8-bit registers.
1135 // We want to preserve all the lower 8-bits and, not just 1 LSB bit.
1136 //
1137 SDNode *HexagonDAGToDAGISel::SelectZeroExtend(SDNode *N) {
1138   SDLoc dl(N);
1139   SDNode *IsIntrinsic = N->getOperand(0).getNode();
1140   if ((IsIntrinsic->getOpcode() == ISD::INTRINSIC_WO_CHAIN)) {
1141     unsigned ID =
1142       cast<ConstantSDNode>(IsIntrinsic->getOperand(0))->getZExtValue();
1143     if (doesIntrinsicReturnPredicate(ID)) {
1144       // Now we need to differentiate target data types.
1145       if (N->getValueType(0) == MVT::i64) {
1146         // Convert the zero_extend to Rs = Pd followed by COMBINE_rr(0,Rs).
1147         SDValue TargetConst0 = CurDAG->getTargetConstant(0, MVT::i32);
1148         SDNode *Result_1 = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
1149                                                   MVT::i32,
1150                                                   SDValue(IsIntrinsic, 0));
1151         SDNode *Result_2 = CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl,
1152                                                   MVT::i32,
1153                                                   TargetConst0);
1154         SDNode *Result_3 = CurDAG->getMachineNode(Hexagon::A2_combinew, dl,
1155                                                   MVT::i64, MVT::Other,
1156                                                   SDValue(Result_2, 0),
1157                                                   SDValue(Result_1, 0));
1158         ReplaceUses(N, Result_3);
1159         return Result_3;
1160       }
1161       if (N->getValueType(0) == MVT::i32) {
1162         // Convert the zero_extend to Rs = Pd
1163         SDNode* RsPd = CurDAG->getMachineNode(Hexagon::C2_tfrpr, dl,
1164                                               MVT::i32,
1165                                               SDValue(IsIntrinsic, 0));
1166         ReplaceUses(N, RsPd);
1167         return RsPd;
1168       }
1169       llvm_unreachable("Unexpected value type");
1170     }
1171   }
1172   return SelectCode(N);
1173 }
1174
1175 //
1176 // Checking for intrinsics which have predicate registers as operand(s)
1177 // and lowering to the actual intrinsic.
1178 //
1179 SDNode *HexagonDAGToDAGISel::SelectIntrinsicWOChain(SDNode *N) {
1180   unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
1181   unsigned Bits;
1182   switch (IID) {
1183   case Intrinsic::hexagon_S2_vsplatrb:
1184     Bits = 8;
1185     break;
1186   case Intrinsic::hexagon_S2_vsplatrh:
1187     Bits = 16;
1188     break;
1189   default:
1190     return SelectCode(N);
1191   }
1192
1193   SDValue const &V = N->getOperand(1);
1194   SDValue U;
1195   if (isValueExtension(V, Bits, U)) {
1196     SDValue R = CurDAG->getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
1197       N->getOperand(0), U);
1198     return SelectCode(R.getNode());
1199   }
1200   return SelectCode(N);
1201 }
1202
1203 //
1204 // Map floating point constant values.
1205 //
1206 SDNode *HexagonDAGToDAGISel::SelectConstantFP(SDNode *N) {
1207   SDLoc dl(N);
1208   ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
1209   APFloat APF = CN->getValueAPF();
1210   if (N->getValueType(0) == MVT::f32) {
1211     return CurDAG->getMachineNode(Hexagon::TFRI_f, dl, MVT::f32,
1212               CurDAG->getTargetConstantFP(APF.convertToFloat(), MVT::f32));
1213   }
1214   else if (N->getValueType(0) == MVT::f64) {
1215     return CurDAG->getMachineNode(Hexagon::CONST64_Float_Real, dl, MVT::f64,
1216               CurDAG->getTargetConstantFP(APF.convertToDouble(), MVT::f64));
1217   }
1218
1219   return SelectCode(N);
1220 }
1221
1222
1223 //
1224 // Map predicate true (encoded as -1 in LLVM) to a XOR.
1225 //
1226 SDNode *HexagonDAGToDAGISel::SelectConstant(SDNode *N) {
1227   SDLoc dl(N);
1228   if (N->getValueType(0) == MVT::i1) {
1229     SDNode* Result;
1230     int32_t Val = cast<ConstantSDNode>(N)->getSExtValue();
1231     if (Val == -1) {
1232       // Create the IntReg = 1 node.
1233       SDNode* IntRegTFR =
1234         CurDAG->getMachineNode(Hexagon::A2_tfrsi, dl, MVT::i32,
1235                                CurDAG->getTargetConstant(0, MVT::i32));
1236
1237       // Pd = IntReg
1238       SDNode* Pd = CurDAG->getMachineNode(Hexagon::C2_tfrrp, dl, MVT::i1,
1239                                           SDValue(IntRegTFR, 0));
1240
1241       // not(Pd)
1242       SDNode* NotPd = CurDAG->getMachineNode(Hexagon::C2_not, dl, MVT::i1,
1243                                              SDValue(Pd, 0));
1244
1245       // xor(not(Pd))
1246       Result = CurDAG->getMachineNode(Hexagon::C2_xor, dl, MVT::i1,
1247                                       SDValue(Pd, 0), SDValue(NotPd, 0));
1248
1249       // We have just built:
1250       // Rs = Pd
1251       // Pd = xor(not(Pd), Pd)
1252
1253       ReplaceUses(N, Result);
1254       return Result;
1255     }
1256   }
1257
1258   return SelectCode(N);
1259 }
1260
1261
1262 //
1263 // Map add followed by a asr -> asr +=.
1264 //
1265 SDNode *HexagonDAGToDAGISel::SelectAdd(SDNode *N) {
1266   SDLoc dl(N);
1267   if (N->getValueType(0) != MVT::i32) {
1268     return SelectCode(N);
1269   }
1270   // Identify nodes of the form: add(asr(...)).
1271   SDNode* Src1 = N->getOperand(0).getNode();
1272   if (Src1->getOpcode() != ISD::SRA || !Src1->hasOneUse()
1273       || Src1->getValueType(0) != MVT::i32) {
1274     return SelectCode(N);
1275   }
1276
1277   // Build Rd = Rd' + asr(Rs, Rt). The machine constraints will ensure that
1278   // Rd and Rd' are assigned to the same register
1279   SDNode* Result = CurDAG->getMachineNode(Hexagon::S2_asr_r_r_acc, dl, MVT::i32,
1280                                           N->getOperand(1),
1281                                           Src1->getOperand(0),
1282                                           Src1->getOperand(1));
1283   ReplaceUses(N, Result);
1284
1285   return Result;
1286 }
1287
1288
1289 SDNode *HexagonDAGToDAGISel::Select(SDNode *N) {
1290   if (N->isMachineOpcode()) {
1291     N->setNodeId(-1);
1292     return nullptr;   // Already selected.
1293   }
1294
1295
1296   switch (N->getOpcode()) {
1297   case ISD::Constant:
1298     return SelectConstant(N);
1299
1300   case ISD::ConstantFP:
1301     return SelectConstantFP(N);
1302
1303   case ISD::ADD:
1304     return SelectAdd(N);
1305
1306   case ISD::SHL:
1307     return SelectSHL(N);
1308
1309   case ISD::LOAD:
1310     return SelectLoad(N);
1311
1312   case ISD::STORE:
1313     return SelectStore(N);
1314
1315   case ISD::SELECT:
1316     return SelectSelect(N);
1317
1318   case ISD::TRUNCATE:
1319     return SelectTruncate(N);
1320
1321   case ISD::MUL:
1322     return SelectMul(N);
1323
1324   case ISD::ZERO_EXTEND:
1325     return SelectZeroExtend(N);
1326
1327   case ISD::INTRINSIC_WO_CHAIN:
1328     return SelectIntrinsicWOChain(N);
1329   }
1330
1331   return SelectCode(N);
1332 }
1333
1334
1335 //
1336 // Hexagon_TODO: Five functions for ADDRri?! Surely there must be a better way
1337 // to define these instructions.
1338 //
1339 bool HexagonDAGToDAGISel::SelectADDRri(SDValue& Addr, SDValue &Base,
1340                                        SDValue &Offset) {
1341   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1342       Addr.getOpcode() == ISD::TargetGlobalAddress)
1343     return false;  // Direct calls.
1344
1345   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1346     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1347     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1348     return true;
1349   }
1350   Base = Addr;
1351   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1352   return true;
1353 }
1354
1355
1356 bool HexagonDAGToDAGISel::SelectADDRriS11_0(SDValue& Addr, SDValue &Base,
1357                                             SDValue &Offset) {
1358   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1359       Addr.getOpcode() == ISD::TargetGlobalAddress)
1360     return false;  // Direct calls.
1361
1362   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1363     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1364     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1365     return (IsS11_0_Offset(Offset.getNode()));
1366   }
1367   Base = Addr;
1368   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1369   return (IsS11_0_Offset(Offset.getNode()));
1370 }
1371
1372
1373 bool HexagonDAGToDAGISel::SelectADDRriS11_1(SDValue& Addr, SDValue &Base,
1374                                             SDValue &Offset) {
1375   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1376       Addr.getOpcode() == ISD::TargetGlobalAddress)
1377     return false;  // Direct calls.
1378
1379   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1380     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1381     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1382     return (IsS11_1_Offset(Offset.getNode()));
1383   }
1384   Base = Addr;
1385   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1386   return (IsS11_1_Offset(Offset.getNode()));
1387 }
1388
1389
1390 bool HexagonDAGToDAGISel::SelectADDRriS11_2(SDValue& Addr, SDValue &Base,
1391                                             SDValue &Offset) {
1392   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1393       Addr.getOpcode() == ISD::TargetGlobalAddress)
1394     return false;  // Direct calls.
1395
1396   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1397     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1398     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1399     return (IsS11_2_Offset(Offset.getNode()));
1400   }
1401   Base = Addr;
1402   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1403   return (IsS11_2_Offset(Offset.getNode()));
1404 }
1405
1406
1407 bool HexagonDAGToDAGISel::SelectADDRriU6_0(SDValue& Addr, SDValue &Base,
1408                                             SDValue &Offset) {
1409   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1410       Addr.getOpcode() == ISD::TargetGlobalAddress)
1411     return false;  // Direct calls.
1412
1413   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1414     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1415     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1416     return (IsU6_0_Offset(Offset.getNode()));
1417   }
1418   Base = Addr;
1419   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1420   return (IsU6_0_Offset(Offset.getNode()));
1421 }
1422
1423
1424 bool HexagonDAGToDAGISel::SelectADDRriU6_1(SDValue& Addr, SDValue &Base,
1425                                             SDValue &Offset) {
1426   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1427       Addr.getOpcode() == ISD::TargetGlobalAddress)
1428     return false;  // Direct calls.
1429
1430   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1431     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1432     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1433     return (IsU6_1_Offset(Offset.getNode()));
1434   }
1435   Base = Addr;
1436   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1437   return (IsU6_1_Offset(Offset.getNode()));
1438 }
1439
1440
1441 bool HexagonDAGToDAGISel::SelectADDRriU6_2(SDValue& Addr, SDValue &Base,
1442                                             SDValue &Offset) {
1443   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1444       Addr.getOpcode() == ISD::TargetGlobalAddress)
1445     return false;  // Direct calls.
1446
1447   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1448     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1449     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1450     return (IsU6_2_Offset(Offset.getNode()));
1451   }
1452   Base = Addr;
1453   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1454   return (IsU6_2_Offset(Offset.getNode()));
1455 }
1456
1457
1458 bool HexagonDAGToDAGISel::SelectMEMriS11_2(SDValue& Addr, SDValue &Base,
1459                                            SDValue &Offset) {
1460
1461   if (Addr.getOpcode() != ISD::ADD) {
1462     return(SelectADDRriS11_2(Addr, Base, Offset));
1463   }
1464
1465   return SelectADDRriS11_2(Addr, Base, Offset);
1466 }
1467
1468
1469 bool HexagonDAGToDAGISel::SelectADDRriS11_3(SDValue& Addr, SDValue &Base,
1470                                             SDValue &Offset) {
1471   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1472       Addr.getOpcode() == ISD::TargetGlobalAddress)
1473     return false;  // Direct calls.
1474
1475   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1476     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1477     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1478     return (IsS11_3_Offset(Offset.getNode()));
1479   }
1480   Base = Addr;
1481   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1482   return (IsS11_3_Offset(Offset.getNode()));
1483 }
1484
1485 bool HexagonDAGToDAGISel::SelectADDRrr(SDValue &Addr, SDValue &R1,
1486                                        SDValue &R2) {
1487   if (Addr.getOpcode() == ISD::FrameIndex) return false;
1488   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1489       Addr.getOpcode() == ISD::TargetGlobalAddress)
1490     return false;  // Direct calls.
1491
1492   if (Addr.getOpcode() == ISD::ADD) {
1493     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
1494       if (isInt<13>(CN->getSExtValue()))
1495         return false;  // Let the reg+imm pattern catch this!
1496     R1 = Addr.getOperand(0);
1497     R2 = Addr.getOperand(1);
1498     return true;
1499   }
1500
1501   R1 = Addr;
1502
1503   return true;
1504 }
1505
1506
1507 // Handle generic address case. It is accessed from inlined asm =m constraints,
1508 // which could have any kind of pointer.
1509 bool HexagonDAGToDAGISel::SelectAddr(SDNode *Op, SDValue Addr,
1510                                           SDValue &Base, SDValue &Offset) {
1511   if (Addr.getOpcode() == ISD::TargetExternalSymbol ||
1512       Addr.getOpcode() == ISD::TargetGlobalAddress)
1513     return false;  // Direct calls.
1514
1515   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
1516     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
1517     Offset = CurDAG->getTargetConstant(0, MVT::i32);
1518     return true;
1519   }
1520
1521   if (Addr.getOpcode() == ISD::ADD) {
1522     Base = Addr.getOperand(0);
1523     Offset = Addr.getOperand(1);
1524     return true;
1525   }
1526
1527   Base = Addr;
1528   Offset = CurDAG->getTargetConstant(0, MVT::i32);
1529   return true;
1530 }
1531
1532
1533 bool HexagonDAGToDAGISel::
1534 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
1535                              std::vector<SDValue> &OutOps) {
1536   SDValue Op0, Op1;
1537
1538   switch (ConstraintCode) {
1539   case 'o':   // Offsetable.
1540   case 'v':   // Not offsetable.
1541   default: return true;
1542   case 'm':   // Memory.
1543     if (!SelectAddr(Op.getNode(), Op, Op0, Op1))
1544       return true;
1545     break;
1546   }
1547
1548   OutOps.push_back(Op0);
1549   OutOps.push_back(Op1);
1550   return false;
1551 }
1552
1553 bool HexagonDAGToDAGISel::isConstExtProfitable(SDNode *N) const {
1554   unsigned UseCount = 0;
1555   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1556     UseCount++;
1557   }
1558
1559   return (UseCount <= 1);
1560
1561 }
1562
1563 //===--------------------------------------------------------------------===//
1564 // Return 'true' if use count of the global address is below threshold.
1565 //===--------------------------------------------------------------------===//
1566 bool HexagonDAGToDAGISel::hasNumUsesBelowThresGA(SDNode *N) const {
1567   assert(N->getOpcode() == ISD::TargetGlobalAddress &&
1568          "Expecting a target global address");
1569
1570   // Always try to fold the address.
1571   if (TM.getOptLevel() == CodeGenOpt::Aggressive)
1572     return true;
1573
1574   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
1575   DenseMap<const GlobalValue *, unsigned>::const_iterator GI =
1576     GlobalAddressUseCountMap.find(GA->getGlobal());
1577
1578   if (GI == GlobalAddressUseCountMap.end())
1579     return false;
1580
1581   return GI->second <= MaxNumOfUsesForConstExtenders;
1582 }
1583
1584 //===--------------------------------------------------------------------===//
1585 // Return true if the non-GP-relative global address can be folded.
1586 //===--------------------------------------------------------------------===//
1587 inline bool HexagonDAGToDAGISel::foldGlobalAddress(SDValue &N, SDValue &R) {
1588   return foldGlobalAddressImpl(N, R, false);
1589 }
1590
1591 //===--------------------------------------------------------------------===//
1592 // Return true if the GP-relative global address can be folded.
1593 //===--------------------------------------------------------------------===//
1594 inline bool HexagonDAGToDAGISel::foldGlobalAddressGP(SDValue &N, SDValue &R) {
1595   return foldGlobalAddressImpl(N, R, true);
1596 }
1597
1598 //===--------------------------------------------------------------------===//
1599 // Fold offset of the global address if number of uses are below threshold.
1600 //===--------------------------------------------------------------------===//
1601 bool HexagonDAGToDAGISel::foldGlobalAddressImpl(SDValue &N, SDValue &R,
1602                                                 bool ShouldLookForGP) {
1603   if (N.getOpcode() == ISD::ADD) {
1604     SDValue N0 = N.getOperand(0);
1605     SDValue N1 = N.getOperand(1);
1606     if ((ShouldLookForGP && (N0.getOpcode() == HexagonISD::CONST32_GP)) ||
1607         (!ShouldLookForGP && (N0.getOpcode() == HexagonISD::CONST32))) {
1608       ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1);
1609       GlobalAddressSDNode *GA =
1610         dyn_cast<GlobalAddressSDNode>(N0.getOperand(0));
1611
1612       if (Const && GA &&
1613           (GA->getOpcode() == ISD::TargetGlobalAddress)) {
1614         if ((N0.getOpcode() == HexagonISD::CONST32) &&
1615                 !hasNumUsesBelowThresGA(GA))
1616             return false;
1617         R = CurDAG->getTargetGlobalAddress(GA->getGlobal(),
1618                                           SDLoc(Const),
1619                                           N.getValueType(),
1620                                           GA->getOffset() +
1621                                           (uint64_t)Const->getSExtValue());
1622         return true;
1623       }
1624     }
1625   }
1626   return false;
1627 }
1628
1629 bool HexagonDAGToDAGISel::SelectAddrFI(SDValue& N, SDValue &R) {
1630   if (N.getOpcode() != ISD::FrameIndex)
1631     return false;
1632   FrameIndexSDNode *FX = cast<FrameIndexSDNode>(N);
1633   R = CurDAG->getTargetFrameIndex(FX->getIndex(), MVT::i32);
1634   return true;
1635 }
1636
1637 inline bool HexagonDAGToDAGISel::SelectAddrGA(SDValue &N, SDValue &R) {
1638   return SelectGlobalAddress(N, R, false);
1639 }
1640
1641 inline bool HexagonDAGToDAGISel::SelectAddrGP(SDValue &N, SDValue &R) {
1642   return SelectGlobalAddress(N, R, true);
1643 }
1644
1645 bool HexagonDAGToDAGISel::SelectGlobalAddress(SDValue &N, SDValue &R,
1646                                               bool UseGP) {
1647   switch (N.getOpcode()) {
1648   case ISD::ADD: {
1649     SDValue N0 = N.getOperand(0);
1650     SDValue N1 = N.getOperand(1);
1651     unsigned GAOpc = N0.getOpcode();
1652     if (UseGP && GAOpc != HexagonISD::CONST32_GP)
1653       return false;
1654     if (!UseGP && GAOpc != HexagonISD::CONST32)
1655       return false;
1656     if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N1)) {
1657       SDValue Addr = N0.getOperand(0);
1658       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Addr)) {
1659         if (GA->getOpcode() == ISD::TargetGlobalAddress) {
1660           uint64_t NewOff = GA->getOffset() + (uint64_t)Const->getSExtValue();
1661           R = CurDAG->getTargetGlobalAddress(GA->getGlobal(), SDLoc(Const),
1662                                              N.getValueType(), NewOff);
1663           return true;
1664         }
1665       }
1666     }
1667     break;
1668   }
1669   case HexagonISD::CONST32:
1670     // The operand(0) of CONST32 is TargetGlobalAddress, which is what we
1671     // want in the instruction.
1672     if (!UseGP)
1673       R = N.getOperand(0);
1674     return !UseGP;
1675   case HexagonISD::CONST32_GP:
1676     if (UseGP)
1677       R = N.getOperand(0);
1678     return UseGP;
1679   default:
1680     return false;
1681   }
1682
1683   return false;
1684 }
1685
1686 bool HexagonDAGToDAGISel::isValueExtension(SDValue const &Val,
1687                                            unsigned FromBits, SDValue &Src) {
1688   unsigned Opc = Val.getOpcode();
1689   switch (Opc) {
1690   case ISD::SIGN_EXTEND:
1691   case ISD::ZERO_EXTEND:
1692   case ISD::ANY_EXTEND: {
1693     SDValue const &Op0 = Val.getOperand(0);
1694     EVT T = Op0.getValueType();
1695     if (T.isInteger() && T.getSizeInBits() == FromBits) {
1696       Src = Op0;
1697       return true;
1698     }
1699     break;
1700   }
1701   case ISD::SIGN_EXTEND_INREG:
1702   case ISD::AssertSext:
1703   case ISD::AssertZext:
1704     if (Val.getOperand(0).getValueType().isInteger()) {
1705       VTSDNode *T = cast<VTSDNode>(Val.getOperand(1));
1706       if (T->getVT().getSizeInBits() == FromBits) {
1707         Src = Val.getOperand(0);
1708         return true;
1709       }
1710     }
1711     break;
1712   case ISD::AND: {
1713     // Check if this is an AND with "FromBits" of lower bits set to 1.
1714     uint64_t FromMask = (1 << FromBits) - 1;
1715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1716       if (C->getZExtValue() == FromMask) {
1717         Src = Val.getOperand(1);
1718         return true;
1719       }
1720     }
1721     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1722       if (C->getZExtValue() == FromMask) {
1723         Src = Val.getOperand(0);
1724         return true;
1725       }
1726     }
1727     break;
1728   }
1729   case ISD::OR:
1730   case ISD::XOR: {
1731     // OR/XOR with the lower "FromBits" bits set to 0.
1732     uint64_t FromMask = (1 << FromBits) - 1;
1733     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(0))) {
1734       if ((C->getZExtValue() & FromMask) == 0) {
1735         Src = Val.getOperand(1);
1736         return true;
1737       }
1738     }
1739     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val.getOperand(1))) {
1740       if ((C->getZExtValue() & FromMask) == 0) {
1741         Src = Val.getOperand(0);
1742         return true;
1743       }
1744     }
1745   }
1746   default:
1747     break;
1748   }
1749   return false;
1750 }