xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Target/GlobalISel/Combine.td (revision 725a9f47324d42037db93c27ceb40d4956872f3e)
1//===- Combine.td - Combine rule definitions ---------------*- tablegen -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Declare GlobalISel combine rules and provide mechanisms to opt-out.
10//
11//===----------------------------------------------------------------------===//
12
13
14//===----------------------------------------------------------------------===//
15// Base Classes
16//
17// These are the core classes that the combiner backend relies on.
18//===----------------------------------------------------------------------===//
19
20/// All arguments of the defs operator must be subclasses of GIDefKind or
21/// sub-dags whose operator is GIDefKindWithArgs.
22class GIDefKind;
23class GIDefKindWithArgs;
24
25/// Declare a root node. There must be at least one of these in every combine
26/// rule.
27def root : GIDefKind;
28
29def defs;
30
31def pattern;
32def match;
33def apply;
34
35def wip_match_opcode;
36
37// Common base class for GICombineRule and GICombineGroup.
38class GICombine {
39  // See GICombineGroup. We only declare it here to make the tablegen pass
40  // simpler.
41  list<GICombine> Rules = ?;
42}
43
44// A group of combine rules that can be added to a GICombiner or another group.
45class GICombineGroup<list<GICombine> rules> : GICombine {
46  // The rules contained in this group. The rules in a group are flattened into
47  // a single list and sorted into whatever order is most efficient. However,
48  // they will never be re-ordered such that behaviour differs from the
49  // specified order. It is therefore possible to use the order of rules in this
50  // list to describe priorities.
51  let Rules = rules;
52}
53
54// Declares a combiner implementation class
55class GICombiner<string classname, list<GICombine> rules>
56    : GICombineGroup<rules> {
57  // The class name to use in the generated output.
58  string Classname = classname;
59  // Combiners can use this so they're free to define tryCombineAll themselves
60  // and do extra work before/after calling the TableGen-erated code.
61  string CombineAllMethodName = "tryCombineAll";
62}
63
64/// Declares data that is passed from the match stage to the apply stage.
65class GIDefMatchData<string type>  {
66  /// A C++ type name indicating the storage type.
67  string Type = type;
68}
69
70class GICombineRule<dag defs, dag match, dag apply> : GICombine {
71  /// Defines the external interface of the match rule. This includes:
72  /// * The names of the root nodes (requires at least one)
73  /// See GIDefKind for details.
74  dag Defs = defs;
75
76  /// Defines the things which must be true for the pattern to match
77  dag Match = match;
78
79  /// Defines the things which happen after the decision is made to apply a
80  /// combine rule.
81  dag Apply = apply;
82
83  /// Defines the predicates that are checked before the match function
84  /// is called. Targets can use this to, for instance, check Subtarget
85  /// features.
86  list<Predicate> Predicates = [];
87
88  // Maximum number of permutations of this rule that can be emitted.
89  // Set to -1 to disable the limit.
90  int MaxPermutations = 16;
91}
92
93def gi_mo;
94def gi_imm;
95
96// This is an equivalent of PatFrags but for MIR Patterns.
97//
98// GICombinePatFrags can be used in place of instructions for 'match' patterns.
99// Much like normal instructions, the defs (outs) come first, and the ins second
100//
101// Out operands can only be of type "root" or "gi_mo", and they must be defined
102// by an instruction pattern in all alternatives.
103//
104// In operands can be gi_imm or gi_mo. They cannot be redefined in any alternative
105// pattern and may only appear in the C++ code, or in the output operand of an
106// instruction pattern.
107class GICombinePatFrag<dag outs, dag ins, list<dag> alts> {
108  dag InOperands = ins;
109  dag OutOperands = outs;
110  list<dag> Alternatives = alts;
111}
112
113//===----------------------------------------------------------------------===//
114// Pattern Special Types
115//===----------------------------------------------------------------------===//
116
117class GISpecialType;
118
119// In an apply pattern, GITypeOf can be used to set the type of a new temporary
120// register to match the type of a matched register.
121//
122// This can only be used on temporary registers defined by the apply pattern.
123//
124// TODO: Make this work in matchers as well?
125//
126// FIXME: Syntax is very ugly.
127class GITypeOf<string opName> : GISpecialType {
128  string OpName = opName;
129}
130
131//===----------------------------------------------------------------------===//
132// Pattern Builtins
133//===----------------------------------------------------------------------===//
134
135// "Magic" Builtin instructions for MIR patterns.
136// The definitions that implement
137class GIBuiltinInst;
138
139// Replace all references to a register with another one.
140//
141// Usage:
142//    (apply (GIReplaceReg $old, $new))
143//
144// Operands:
145// - $old (out) register defined by a matched instruction
146// - $new (in)  register
147//
148// Semantics:
149// - Can only appear in an 'apply' pattern.
150// - If both old/new are operands of matched instructions,
151//   "canReplaceReg" is checked before applying the rule.
152def GIReplaceReg : GIBuiltinInst;
153
154// Apply action that erases the match root.
155//
156// Usage:
157//    (apply (GIEraseRoot))
158//
159// Semantics:
160// - Can only appear as the only pattern of an 'apply' pattern list.
161// - The root cannot have any output operands.
162// - The root must be a CodeGenInstruction
163//
164// TODO: Allow using this directly, like (apply GIEraseRoot)
165def GIEraseRoot : GIBuiltinInst;
166
167//===----------------------------------------------------------------------===//
168// Pattern MIFlags
169//===----------------------------------------------------------------------===//
170
171class MIFlagEnum<string enumName> {
172  string EnumName = "MachineInstr::" # enumName;
173}
174
175def FmNoNans    : MIFlagEnum<"FmNoNans">;
176def FmNoInfs    : MIFlagEnum<"FmNoInfs">;
177def FmNsz       : MIFlagEnum<"FmNsz">;
178def FmArcp      : MIFlagEnum<"FmArcp">;
179def FmContract  : MIFlagEnum<"FmContract">;
180def FmAfn       : MIFlagEnum<"FmAfn">;
181def FmReassoc   : MIFlagEnum<"FmReassoc">;
182
183def MIFlags;
184// def not; -> Already defined as a SDNode
185
186//===----------------------------------------------------------------------===//
187
188def extending_load_matchdata : GIDefMatchData<"PreferredTuple">;
189def indexed_load_store_matchdata : GIDefMatchData<"IndexedLoadStoreMatchInfo">;
190def instruction_steps_matchdata: GIDefMatchData<"InstructionStepsMatchInfo">;
191
192def register_matchinfo: GIDefMatchData<"Register">;
193def int64_matchinfo: GIDefMatchData<"int64_t">;
194def apint_matchinfo : GIDefMatchData<"APInt">;
195def constantfp_matchinfo : GIDefMatchData<"ConstantFP*">;
196def build_fn_matchinfo :
197GIDefMatchData<"std::function<void(MachineIRBuilder &)>">;
198def unsigned_matchinfo: GIDefMatchData<"unsigned">;
199
200def copy_prop : GICombineRule<
201  (defs root:$d),
202  (match (COPY $d, $s):$mi,
203         [{ return Helper.matchCombineCopy(*${mi}); }]),
204  (apply [{ Helper.applyCombineCopy(*${mi}); }])>;
205
206// idempotent operations
207// Fold (freeze (freeze x)) -> (freeze x).
208// Fold (fabs (fabs x)) -> (fabs x).
209// Fold (fcanonicalize (fcanonicalize x)) -> (fcanonicalize x).
210def idempotent_prop_frags : GICombinePatFrag<
211  (outs root:$dst, $src), (ins),
212  !foreach(op, [G_FREEZE, G_FABS, G_FCANONICALIZE],
213           (pattern (op $dst, $src), (op $src, $x)))>;
214
215def idempotent_prop : GICombineRule<
216   (defs root:$dst),
217   (match (idempotent_prop_frags $dst, $src)),
218   (apply (GIReplaceReg $dst, $src))>;
219
220
221def extending_loads : GICombineRule<
222  (defs root:$root, extending_load_matchdata:$matchinfo),
223  (match (wip_match_opcode G_LOAD, G_SEXTLOAD, G_ZEXTLOAD):$root,
224         [{ return Helper.matchCombineExtendingLoads(*${root}, ${matchinfo}); }]),
225  (apply [{ Helper.applyCombineExtendingLoads(*${root}, ${matchinfo}); }])>;
226
227def load_and_mask : GICombineRule<
228  (defs root:$root, build_fn_matchinfo:$matchinfo),
229  (match (wip_match_opcode G_AND):$root,
230        [{ return Helper.matchCombineLoadWithAndMask(*${root}, ${matchinfo}); }]),
231  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
232def combines_for_extload: GICombineGroup<[extending_loads, load_and_mask]>;
233
234def sext_trunc_sextload : GICombineRule<
235  (defs root:$d),
236  (match (wip_match_opcode G_SEXT_INREG):$d,
237         [{ return Helper.matchSextTruncSextLoad(*${d}); }]),
238  (apply [{ Helper.applySextTruncSextLoad(*${d}); }])>;
239
240def sext_inreg_of_load_matchdata : GIDefMatchData<"std::tuple<Register, unsigned>">;
241def sext_inreg_of_load : GICombineRule<
242  (defs root:$root, sext_inreg_of_load_matchdata:$matchinfo),
243  (match (wip_match_opcode G_SEXT_INREG):$root,
244         [{ return Helper.matchSextInRegOfLoad(*${root}, ${matchinfo}); }]),
245  (apply [{ Helper.applySextInRegOfLoad(*${root}, ${matchinfo}); }])>;
246
247def sext_inreg_to_zext_inreg : GICombineRule<
248  (defs root:$dst),
249  (match
250    (G_SEXT_INREG $dst, $src, $imm):$root,
251      [{
252        unsigned BitWidth = MRI.getType(${src}.getReg()).getScalarSizeInBits();
253        return Helper.getKnownBits()->maskedValueIsZero(${src}.getReg(),
254                 APInt::getOneBitSet(BitWidth, ${imm}.getImm() - 1)); }]),
255    (apply [{
256      Helper.getBuilder().setInstrAndDebugLoc(*${root});
257      Helper.getBuilder().buildZExtInReg(${dst}, ${src}, ${imm}.getImm());
258      ${root}->eraseFromParent();
259  }])
260>;
261
262def combine_extracted_vector_load : GICombineRule<
263  (defs root:$root, build_fn_matchinfo:$matchinfo),
264  (match (wip_match_opcode G_EXTRACT_VECTOR_ELT):$root,
265        [{ return Helper.matchCombineExtractedVectorLoad(*${root}, ${matchinfo}); }]),
266  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
267
268def combine_indexed_load_store : GICombineRule<
269  (defs root:$root, indexed_load_store_matchdata:$matchinfo),
270  (match (wip_match_opcode G_LOAD, G_SEXTLOAD, G_ZEXTLOAD, G_STORE):$root,
271         [{ return Helper.matchCombineIndexedLoadStore(*${root}, ${matchinfo}); }]),
272  (apply [{ Helper.applyCombineIndexedLoadStore(*${root}, ${matchinfo}); }])>;
273
274def opt_brcond_by_inverting_cond_matchdata : GIDefMatchData<"MachineInstr *">;
275def opt_brcond_by_inverting_cond : GICombineRule<
276  (defs root:$root, opt_brcond_by_inverting_cond_matchdata:$matchinfo),
277  (match (wip_match_opcode G_BR):$root,
278         [{ return Helper.matchOptBrCondByInvertingCond(*${root}, ${matchinfo}); }]),
279  (apply [{ Helper.applyOptBrCondByInvertingCond(*${root}, ${matchinfo}); }])>;
280
281def ptr_add_immed_matchdata : GIDefMatchData<"PtrAddChain">;
282def ptr_add_immed_chain : GICombineRule<
283  (defs root:$d, ptr_add_immed_matchdata:$matchinfo),
284  (match (wip_match_opcode G_PTR_ADD):$d,
285         [{ return Helper.matchPtrAddImmedChain(*${d}, ${matchinfo}); }]),
286  (apply [{ Helper.applyPtrAddImmedChain(*${d}, ${matchinfo}); }])>;
287
288def shifts_too_big : GICombineRule<
289  (defs root:$root),
290  (match (wip_match_opcode G_SHL, G_ASHR, G_LSHR):$root,
291         [{ return Helper.matchShiftsTooBig(*${root}); }]),
292  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
293
294// Fold shift (shift base x), y -> shift base, (x+y), if shifts are same
295def shift_immed_matchdata : GIDefMatchData<"RegisterImmPair">;
296def shift_immed_chain : GICombineRule<
297  (defs root:$d, shift_immed_matchdata:$matchinfo),
298  (match (wip_match_opcode G_SHL, G_ASHR, G_LSHR, G_SSHLSAT, G_USHLSAT):$d,
299         [{ return Helper.matchShiftImmedChain(*${d}, ${matchinfo}); }]),
300  (apply [{ Helper.applyShiftImmedChain(*${d}, ${matchinfo}); }])>;
301
302// Transform shift (logic (shift X, C0), Y), C1
303//        -> logic (shift X, (C0+C1)), (shift Y, C1), if shifts are same
304def shift_of_shifted_logic_matchdata : GIDefMatchData<"ShiftOfShiftedLogic">;
305def shift_of_shifted_logic_chain : GICombineRule<
306  (defs root:$d, shift_of_shifted_logic_matchdata:$matchinfo),
307  (match (wip_match_opcode G_SHL, G_ASHR, G_LSHR, G_USHLSAT, G_SSHLSAT):$d,
308         [{ return Helper.matchShiftOfShiftedLogic(*${d}, ${matchinfo}); }]),
309  (apply [{ Helper.applyShiftOfShiftedLogic(*${d}, ${matchinfo}); }])>;
310
311def mul_to_shl_matchdata : GIDefMatchData<"unsigned">;
312def mul_to_shl : GICombineRule<
313  (defs root:$d, mul_to_shl_matchdata:$matchinfo),
314  (match (G_MUL $d, $op1, $op2):$mi,
315         [{ return Helper.matchCombineMulToShl(*${mi}, ${matchinfo}); }]),
316  (apply [{ Helper.applyCombineMulToShl(*${mi}, ${matchinfo}); }])>;
317
318// shl ([asz]ext x), y => zext (shl x, y), if shift does not overflow int
319def reduce_shl_of_extend_matchdata : GIDefMatchData<"RegisterImmPair">;
320def reduce_shl_of_extend : GICombineRule<
321  (defs root:$dst, reduce_shl_of_extend_matchdata:$matchinfo),
322  (match (G_SHL $dst, $src0, $src1):$mi,
323         [{ return Helper.matchCombineShlOfExtend(*${mi}, ${matchinfo}); }]),
324  (apply [{ Helper.applyCombineShlOfExtend(*${mi}, ${matchinfo}); }])>;
325
326// Combine (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
327// Combine (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
328def commute_shift : GICombineRule<
329  (defs root:$d, build_fn_matchinfo:$matchinfo),
330  (match (wip_match_opcode G_SHL):$d,
331         [{ return Helper.matchCommuteShift(*${d}, ${matchinfo}); }]),
332  (apply [{ Helper.applyBuildFn(*${d}, ${matchinfo}); }])>;
333
334def narrow_binop_feeding_and : GICombineRule<
335  (defs root:$root, build_fn_matchinfo:$matchinfo),
336  (match (wip_match_opcode G_AND):$root,
337         [{ return Helper.matchNarrowBinopFeedingAnd(*${root}, ${matchinfo}); }]),
338  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${matchinfo}); }])>;
339
340// [us]itofp(undef) = 0, because the result value is bounded.
341def undef_to_fp_zero : GICombineRule<
342  (defs root:$root),
343  (match (wip_match_opcode G_UITOFP, G_SITOFP):$root,
344         [{ return Helper.matchAnyExplicitUseIsUndef(*${root}); }]),
345  (apply [{ Helper.replaceInstWithFConstant(*${root}, 0.0); }])>;
346
347def undef_to_int_zero: GICombineRule<
348  (defs root:$root),
349  (match (wip_match_opcode G_AND, G_MUL):$root,
350         [{ return Helper.matchAnyExplicitUseIsUndef(*${root}); }]),
351  (apply [{ Helper.replaceInstWithConstant(*${root}, 0); }])>;
352
353def undef_to_negative_one: GICombineRule<
354  (defs root:$root),
355  (match (wip_match_opcode G_OR):$root,
356         [{ return Helper.matchAnyExplicitUseIsUndef(*${root}); }]),
357  (apply [{ Helper.replaceInstWithConstant(*${root}, -1); }])>;
358
359def binop_left_undef_to_zero: GICombineRule<
360  (defs root:$root),
361  (match (wip_match_opcode G_SHL, G_UDIV, G_UREM):$root,
362         [{ return Helper.matchOperandIsUndef(*${root}, 1); }]),
363  (apply [{ Helper.replaceInstWithConstant(*${root}, 0); }])>;
364
365def binop_right_undef_to_undef: GICombineRule<
366  (defs root:$root),
367  (match (wip_match_opcode G_SHL, G_ASHR, G_LSHR):$root,
368         [{ return Helper.matchOperandIsUndef(*${root}, 2); }]),
369  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
370
371def unary_undef_to_zero: GICombineRule<
372  (defs root:$root),
373  (match (wip_match_opcode G_ABS):$root,
374         [{ return Helper.matchOperandIsUndef(*${root}, 1); }]),
375  (apply [{ Helper.replaceInstWithConstant(*${root}, 0); }])>;
376
377// Instructions where if any source operand is undef, the instruction can be
378// replaced with undef.
379def propagate_undef_any_op: GICombineRule<
380  (defs root:$root),
381  (match (wip_match_opcode G_ADD, G_FPTOSI, G_FPTOUI, G_SUB, G_XOR, G_TRUNC):$root,
382         [{ return Helper.matchAnyExplicitUseIsUndef(*${root}); }]),
383  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
384
385// Instructions where if all source operands are undef, the instruction can be
386// replaced with undef.
387def propagate_undef_all_ops: GICombineRule<
388  (defs root:$root),
389  (match (wip_match_opcode G_SHUFFLE_VECTOR):$root,
390          [{ return Helper.matchAllExplicitUsesAreUndef(*${root}); }]),
391  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
392
393// Replace a G_SHUFFLE_VECTOR with an undef mask with a G_IMPLICIT_DEF.
394def propagate_undef_shuffle_mask: GICombineRule<
395  (defs root:$root),
396  (match (wip_match_opcode G_SHUFFLE_VECTOR):$root,
397         [{ return Helper.matchUndefShuffleVectorMask(*${root}); }]),
398  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
399
400// Replace a G_SHUFFLE_VECTOR with a G_EXTRACT_VECTOR_ELT.
401def shuffle_to_extract: GICombineRule<
402  (defs root:$root),
403  (match (wip_match_opcode G_SHUFFLE_VECTOR):$root,
404         [{ return Helper.matchShuffleToExtract(*${root}); }]),
405  (apply [{ Helper.applyShuffleToExtract(*${root}); }])>;
406
407  // Replace an insert/extract element of an out of bounds index with undef.
408  def insert_extract_vec_elt_out_of_bounds : GICombineRule<
409  (defs root:$root),
410  (match (wip_match_opcode G_INSERT_VECTOR_ELT, G_EXTRACT_VECTOR_ELT):$root,
411         [{ return Helper.matchInsertExtractVecEltOutOfBounds(*${root}); }]),
412  (apply [{ Helper.replaceInstWithUndef(*${root}); }])>;
413
414// Fold (cond ? x : x) -> x
415def select_same_val: GICombineRule<
416  (defs root:$root),
417  (match (wip_match_opcode G_SELECT):$root,
418    [{ return Helper.matchSelectSameVal(*${root}); }]),
419  (apply [{ Helper.replaceSingleDefInstWithOperand(*${root}, 2); }])
420>;
421
422// Fold (undef ? x : y) -> y
423def select_undef_cmp: GICombineRule<
424  (defs root:$dst),
425  (match (G_IMPLICIT_DEF $undef),
426         (G_SELECT $dst, $undef, $x, $y)),
427  (apply (GIReplaceReg $dst, $y))
428>;
429
430// Fold (true ? x : y) -> x
431// Fold (false ? x : y) -> y
432def select_constant_cmp_matchdata : GIDefMatchData<"unsigned">;
433def select_constant_cmp: GICombineRule<
434  (defs root:$root, select_constant_cmp_matchdata:$matchinfo),
435  (match (wip_match_opcode G_SELECT):$root,
436    [{ return Helper.matchConstantSelectCmp(*${root}, ${matchinfo}); }]),
437  (apply [{ Helper.replaceSingleDefInstWithOperand(*${root}, ${matchinfo}); }])
438>;
439
440// Fold (C op x) -> (x op C)
441// TODO: handle more isCommutable opcodes
442// TODO: handle compares (currently not marked as isCommutable)
443def commute_int_constant_to_rhs : GICombineRule<
444  (defs root:$root),
445  (match (wip_match_opcode G_ADD, G_MUL, G_AND, G_OR, G_XOR):$root,
446    [{ return Helper.matchCommuteConstantToRHS(*${root}); }]),
447  (apply [{ Helper.applyCommuteBinOpOperands(*${root}); }])
448>;
449
450def commute_fp_constant_to_rhs : GICombineRule<
451  (defs root:$root),
452  (match (wip_match_opcode G_FADD, G_FMUL):$root,
453    [{ return Helper.matchCommuteFPConstantToRHS(*${root}); }]),
454  (apply [{ Helper.applyCommuteBinOpOperands(*${root}); }])
455>;
456
457def commute_constant_to_rhs : GICombineGroup<[
458  commute_int_constant_to_rhs,
459  commute_fp_constant_to_rhs
460]>;
461
462// Fold x op 0 -> x
463def right_identity_zero_frags : GICombinePatFrag<
464  (outs root:$dst), (ins $x),
465  !foreach(op,
466           [G_SUB, G_ADD, G_OR, G_XOR, G_SHL, G_ASHR,
467            G_LSHR, G_PTR_ADD, G_ROTL, G_ROTR],
468           (pattern (op $dst, $x, 0)))>;
469def right_identity_zero: GICombineRule<
470  (defs root:$dst),
471  (match (right_identity_zero_frags $dst, $lhs)),
472  (apply (GIReplaceReg $dst, $lhs))
473>;
474
475def right_identity_neg_zero_fp: GICombineRule<
476  (defs root:$dst),
477  (match (G_FADD $dst, $x, $y):$root,
478    [{ return Helper.matchConstantFPOp(${y}, -0.0); }]),
479  (apply (GIReplaceReg $dst, $x))
480>;
481
482// Fold x op 1 -> x
483def right_identity_one_int: GICombineRule<
484  (defs root:$dst),
485  (match (G_MUL $dst, $x, 1)),
486  (apply (GIReplaceReg $dst, $x))
487>;
488
489def right_identity_one_fp: GICombineRule<
490  (defs root:$dst),
491  (match (G_FMUL $dst, $x, $y):$root,
492    [{ return Helper.matchConstantFPOp(${y}, 1.0); }]),
493  (apply (GIReplaceReg $dst, $x))
494>;
495
496def right_identity_one : GICombineGroup<[right_identity_one_int, right_identity_one_fp]>;
497
498// Fold (x op x) - > x
499def binop_same_val_frags : GICombinePatFrag<
500  (outs root:$dst), (ins $x),
501  [
502    (pattern (G_AND $dst, $x, $x)),
503    (pattern (G_OR $dst, $x, $x)),
504  ]
505>;
506def binop_same_val: GICombineRule<
507  (defs root:$dst),
508  (match (binop_same_val_frags $dst, $src)),
509  (apply (GIReplaceReg $dst, $src))
510>;
511
512// Fold (0 op x) - > 0
513def binop_left_to_zero: GICombineRule<
514  (defs root:$root),
515  (match (wip_match_opcode G_SDIV, G_UDIV, G_SREM, G_UREM):$root,
516    [{ return Helper.matchOperandIsZero(*${root}, 1); }]),
517  (apply [{ Helper.replaceSingleDefInstWithOperand(*${root}, 1); }])
518>;
519
520def urem_pow2_to_mask : GICombineRule<
521  (defs root:$root),
522  (match (wip_match_opcode G_UREM):$root,
523    [{ return Helper.matchOperandIsKnownToBeAPowerOfTwo(*${root}, 2); }]),
524  (apply [{ Helper.applySimplifyURemByPow2(*${root}); }])
525>;
526
527// Push a binary operator through a select on constants.
528//
529// binop (select cond, K0, K1), K2 ->
530//   select cond, (binop K0, K2), (binop K1, K2)
531
532// Every binary operator that has constant folding. We currently do
533// not have constant folding for G_FPOW, G_FMAXNUM_IEEE or
534// G_FMINNUM_IEEE.
535def fold_binop_into_select : GICombineRule<
536  (defs root:$root, unsigned_matchinfo:$select_op_no),
537  (match (wip_match_opcode
538    G_ADD, G_SUB, G_PTR_ADD, G_AND, G_OR, G_XOR,
539    G_SDIV, G_SREM, G_UDIV, G_UREM, G_LSHR, G_ASHR, G_SHL,
540    G_SMIN, G_SMAX, G_UMIN, G_UMAX,
541    G_FMUL, G_FADD, G_FSUB, G_FDIV, G_FREM,
542    G_FMINNUM, G_FMAXNUM, G_FMINIMUM, G_FMAXIMUM):$root,
543    [{ return Helper.matchFoldBinOpIntoSelect(*${root}, ${select_op_no}); }]),
544  (apply [{ Helper.applyFoldBinOpIntoSelect(*${root}, ${select_op_no}); }])
545>;
546
547// Transform d = [su]div(x, y) and r = [su]rem(x, y) - > d, r = [su]divrem(x, y)
548def div_rem_to_divrem_matchdata : GIDefMatchData<"MachineInstr *">;
549def div_rem_to_divrem : GICombineRule<
550  (defs root:$root, div_rem_to_divrem_matchdata:$matchinfo),
551  (match (wip_match_opcode G_SDIV, G_UDIV, G_SREM, G_UREM):$root,
552    [{ return Helper.matchCombineDivRem(*${root}, ${matchinfo}); }]),
553  (apply [{ Helper.applyCombineDivRem(*${root}, ${matchinfo}); }])
554>;
555
556// Fold (x op 0) - > 0
557def binop_right_to_zero: GICombineRule<
558  (defs root:$dst),
559  (match (G_MUL $dst, $lhs, 0:$zero)),
560  (apply (GIReplaceReg $dst, $zero))
561>;
562
563// Erase stores of undef values.
564def erase_undef_store : GICombineRule<
565  (defs root:$root),
566  (match (wip_match_opcode G_STORE):$root,
567    [{ return Helper.matchUndefStore(*${root}); }]),
568  (apply [{ Helper.eraseInst(*${root}); }])
569>;
570
571def simplify_add_to_sub_matchinfo: GIDefMatchData<"std::tuple<Register, Register>">;
572def simplify_add_to_sub: GICombineRule <
573  (defs root:$root, simplify_add_to_sub_matchinfo:$info),
574  (match (wip_match_opcode G_ADD):$root,
575    [{ return Helper.matchSimplifyAddToSub(*${root}, ${info}); }]),
576  (apply [{ Helper.applySimplifyAddToSub(*${root}, ${info});}])
577>;
578
579// Fold fp_op(cst) to the constant result of the floating point operation.
580class constant_fold_unary_fp_op_rule<Instruction opcode> : GICombineRule <
581  (defs root:$dst),
582  (match (opcode $dst, $src0):$root, (G_FCONSTANT $src0, $cst)),
583  (apply [{ Helper.applyCombineConstantFoldFpUnary(*${root}, ${cst}.getFPImm()); }])
584>;
585
586def constant_fold_fneg : constant_fold_unary_fp_op_rule<G_FNEG>;
587def constant_fold_fabs : constant_fold_unary_fp_op_rule<G_FABS>;
588def constant_fold_fsqrt : constant_fold_unary_fp_op_rule<G_FSQRT>;
589def constant_fold_flog2 : constant_fold_unary_fp_op_rule<G_FLOG2>;
590def constant_fold_fptrunc : constant_fold_unary_fp_op_rule<G_FPTRUNC>;
591
592// Fold constant zero int to fp conversions.
593class itof_const_zero_fold_rule<Instruction opcode> : GICombineRule <
594  (defs root:$dst),
595  (match (opcode $dst, 0)),
596  // Can't use COPY $dst, 0 here because the 0 operand may be a smaller type
597  // than the destination for itofp.
598  (apply [{ Helper.replaceInstWithFConstant(*${dst}.getParent(), 0.0); }])
599>;
600def itof_const_zero_fold_si : itof_const_zero_fold_rule<G_SITOFP>;
601def itof_const_zero_fold_ui : itof_const_zero_fold_rule<G_UITOFP>;
602
603def constant_fold_fp_ops : GICombineGroup<[
604  constant_fold_fneg,
605  constant_fold_fabs,
606  constant_fold_fsqrt,
607  constant_fold_flog2,
608  constant_fold_fptrunc,
609  itof_const_zero_fold_si,
610  itof_const_zero_fold_ui
611]>;
612
613// Fold int2ptr(ptr2int(x)) -> x
614def p2i_to_i2p: GICombineRule<
615  (defs root:$root, register_matchinfo:$info),
616  (match (wip_match_opcode G_INTTOPTR):$root,
617    [{ return Helper.matchCombineI2PToP2I(*${root}, ${info}); }]),
618  (apply [{ Helper.applyCombineI2PToP2I(*${root}, ${info}); }])
619>;
620
621// Fold ptr2int(int2ptr(x)) -> x
622def i2p_to_p2i: GICombineRule<
623  (defs root:$dst, register_matchinfo:$info),
624  (match (G_INTTOPTR $t, $ptr),
625         (G_PTRTOINT $dst, $t):$mi,
626    [{ ${info} = ${ptr}.getReg(); return true; }]),
627  (apply [{ Helper.applyCombineP2IToI2P(*${mi}, ${info}); }])
628>;
629
630// Fold add ptrtoint(x), y -> ptrtoint (ptr_add x), y
631def add_p2i_to_ptradd_matchinfo : GIDefMatchData<"std::pair<Register, bool>">;
632def add_p2i_to_ptradd : GICombineRule<
633  (defs root:$root, add_p2i_to_ptradd_matchinfo:$info),
634  (match (wip_match_opcode G_ADD):$root,
635    [{ return Helper.matchCombineAddP2IToPtrAdd(*${root}, ${info}); }]),
636  (apply [{ Helper.applyCombineAddP2IToPtrAdd(*${root}, ${info}); }])
637>;
638
639// Fold (ptr_add (int2ptr C1), C2) -> C1 + C2
640def const_ptradd_to_i2p_matchinfo : GIDefMatchData<"APInt">;
641def const_ptradd_to_i2p: GICombineRule<
642  (defs root:$root, const_ptradd_to_i2p_matchinfo:$info),
643  (match (wip_match_opcode G_PTR_ADD):$root,
644    [{ return Helper.matchCombineConstPtrAddToI2P(*${root}, ${info}); }]),
645  (apply [{ Helper.applyCombineConstPtrAddToI2P(*${root}, ${info}); }])
646>;
647
648// Simplify: (logic_op (op x...), (op y...)) -> (op (logic_op x, y))
649def hoist_logic_op_with_same_opcode_hands: GICombineRule <
650  (defs root:$root, instruction_steps_matchdata:$info),
651  (match (wip_match_opcode G_AND, G_OR, G_XOR):$root,
652    [{ return Helper.matchHoistLogicOpWithSameOpcodeHands(*${root}, ${info}); }]),
653  (apply [{ Helper.applyBuildInstructionSteps(*${root}, ${info});}])
654>;
655
656// Fold ashr (shl x, C), C -> sext_inreg (C)
657def shl_ashr_to_sext_inreg_matchinfo : GIDefMatchData<"std::tuple<Register, int64_t>">;
658def shl_ashr_to_sext_inreg : GICombineRule<
659  (defs root:$root, shl_ashr_to_sext_inreg_matchinfo:$info),
660  (match (wip_match_opcode G_ASHR): $root,
661    [{ return Helper.matchAshrShlToSextInreg(*${root}, ${info}); }]),
662  (apply [{ Helper.applyAshShlToSextInreg(*${root}, ${info});}])
663>;
664
665// Fold and(and(x, C1), C2) -> C1&C2 ? and(x, C1&C2) : 0
666def overlapping_and: GICombineRule <
667  (defs root:$root, build_fn_matchinfo:$info),
668  (match (wip_match_opcode G_AND):$root,
669         [{ return Helper.matchOverlappingAnd(*${root}, ${info}); }]),
670  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])
671>;
672
673// Fold (x & y) -> x or (x & y) -> y when (x & y) is known to equal x or equal y.
674def redundant_and: GICombineRule <
675  (defs root:$root, register_matchinfo:$matchinfo),
676  (match (wip_match_opcode G_AND):$root,
677         [{ return Helper.matchRedundantAnd(*${root}, ${matchinfo}); }]),
678  (apply [{ Helper.replaceSingleDefInstWithReg(*${root}, ${matchinfo}); }])
679>;
680
681// Fold (x | y) -> x or (x | y) -> y when (x | y) is known to equal x or equal y.
682def redundant_or: GICombineRule <
683  (defs root:$root, register_matchinfo:$matchinfo),
684  (match (wip_match_opcode G_OR):$root,
685         [{ return Helper.matchRedundantOr(*${root}, ${matchinfo}); }]),
686  (apply [{ Helper.replaceSingleDefInstWithReg(*${root}, ${matchinfo}); }])
687>;
688
689// If the input is already sign extended, just drop the extension.
690// sext_inreg x, K ->
691//   if computeNumSignBits(x) >= (x.getScalarSizeInBits() - K + 1)
692def redundant_sext_inreg: GICombineRule <
693  (defs root:$root),
694  (match (wip_match_opcode G_SEXT_INREG):$root,
695         [{ return Helper.matchRedundantSExtInReg(*${root}); }]),
696     (apply [{ Helper.replaceSingleDefInstWithOperand(*${root}, 1); }])
697>;
698
699// Fold (anyext (trunc x)) -> x if the source type is same as
700// the destination type.
701def anyext_trunc_fold: GICombineRule <
702  (defs root:$root, register_matchinfo:$matchinfo),
703  (match (wip_match_opcode G_ANYEXT):$root,
704         [{ return Helper.matchCombineAnyExtTrunc(*${root}, ${matchinfo}); }]),
705  (apply [{ Helper.replaceSingleDefInstWithReg(*${root}, ${matchinfo}); }])
706>;
707
708// Fold (zext (trunc x)) -> x if the source type is same as the destination type
709// and truncated bits are known to be zero.
710def zext_trunc_fold_matchinfo : GIDefMatchData<"Register">;
711def zext_trunc_fold: GICombineRule <
712  (defs root:$root, zext_trunc_fold_matchinfo:$matchinfo),
713  (match (wip_match_opcode G_ZEXT):$root,
714         [{ return Helper.matchCombineZextTrunc(*${root}, ${matchinfo}); }]),
715  (apply [{ Helper.replaceSingleDefInstWithReg(*${root}, ${matchinfo}); }])
716>;
717
718// Fold ([asz]ext ([asz]ext x)) -> ([asz]ext x).
719def ext_ext_fold_matchinfo : GIDefMatchData<"std::tuple<Register, unsigned>">;
720def ext_ext_fold: GICombineRule <
721  (defs root:$root, ext_ext_fold_matchinfo:$matchinfo),
722  (match (wip_match_opcode G_ANYEXT, G_SEXT, G_ZEXT):$root,
723         [{ return Helper.matchCombineExtOfExt(*${root}, ${matchinfo}); }]),
724  (apply [{ Helper.applyCombineExtOfExt(*${root}, ${matchinfo}); }])
725>;
726
727def not_cmp_fold_matchinfo : GIDefMatchData<"SmallVector<Register, 4>">;
728def not_cmp_fold : GICombineRule<
729  (defs root:$d, not_cmp_fold_matchinfo:$info),
730  (match (wip_match_opcode G_XOR): $d,
731  [{ return Helper.matchNotCmp(*${d}, ${info}); }]),
732  (apply [{ Helper.applyNotCmp(*${d}, ${info}); }])
733>;
734
735// Fold (fneg (fneg x)) -> x.
736def fneg_fneg_fold: GICombineRule <
737  (defs root:$dst),
738  (match (G_FNEG $t, $src),
739         (G_FNEG $dst, $t)),
740  (apply (GIReplaceReg $dst, $src))
741>;
742
743// Fold (unmerge(merge x, y, z)) -> z, y, z.
744def unmerge_merge_matchinfo : GIDefMatchData<"SmallVector<Register, 8>">;
745def unmerge_merge : GICombineRule<
746  (defs root:$d, unmerge_merge_matchinfo:$info),
747  (match (wip_match_opcode G_UNMERGE_VALUES): $d,
748  [{ return Helper.matchCombineUnmergeMergeToPlainValues(*${d}, ${info}); }]),
749  (apply [{ Helper.applyCombineUnmergeMergeToPlainValues(*${d}, ${info}); }])
750>;
751
752// Fold merge(unmerge).
753def merge_unmerge : GICombineRule<
754  (defs root:$d, register_matchinfo:$matchinfo),
755  (match (wip_match_opcode G_MERGE_VALUES):$d,
756  [{ return Helper.matchCombineMergeUnmerge(*${d}, ${matchinfo}); }]),
757  (apply [{ Helper.replaceSingleDefInstWithReg(*${d}, ${matchinfo}); }])
758>;
759
760// Fold (fabs (fneg x)) -> (fabs x).
761def fabs_fneg_fold: GICombineRule <
762  (defs root:$dst),
763  (match  (G_FNEG $tmp, $x),
764          (G_FABS $dst, $tmp)),
765  (apply (G_FABS $dst, $x))>;
766
767// Fold (unmerge cst) -> cst1, cst2, ...
768def unmerge_cst_matchinfo : GIDefMatchData<"SmallVector<APInt, 8>">;
769def unmerge_cst : GICombineRule<
770  (defs root:$d, unmerge_cst_matchinfo:$info),
771  (match (wip_match_opcode G_UNMERGE_VALUES): $d,
772  [{ return Helper.matchCombineUnmergeConstant(*${d}, ${info}); }]),
773  (apply [{ Helper.applyCombineUnmergeConstant(*${d}, ${info}); }])
774>;
775
776// Fold (unmerge undef) -> undef, undef, ...
777def unmerge_undef : GICombineRule<
778  (defs root:$root, build_fn_matchinfo:$info),
779  (match (wip_match_opcode G_UNMERGE_VALUES): $root,
780         [{ return Helper.matchCombineUnmergeUndef(*${root}, ${info}); }]),
781  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])
782>;
783
784// Transform x,y<dead> = unmerge z -> x = trunc z.
785def unmerge_dead_to_trunc : GICombineRule<
786  (defs root:$d),
787  (match (wip_match_opcode G_UNMERGE_VALUES): $d,
788  [{ return Helper.matchCombineUnmergeWithDeadLanesToTrunc(*${d}); }]),
789  (apply [{ Helper.applyCombineUnmergeWithDeadLanesToTrunc(*${d}); }])
790>;
791
792// Transform x,y = unmerge(zext(z)) -> x = zext z; y = 0.
793def unmerge_zext_to_zext : GICombineRule<
794  (defs root:$d),
795  (match (wip_match_opcode G_UNMERGE_VALUES): $d,
796  [{ return Helper.matchCombineUnmergeZExtToZExt(*${d}); }]),
797  (apply [{ Helper.applyCombineUnmergeZExtToZExt(*${d}); }])
798>;
799
800// Fold trunc ([asz]ext x) -> x or ([asz]ext x) or (trunc x).
801def trunc_ext_fold_matchinfo : GIDefMatchData<"std::pair<Register, unsigned>">;
802def trunc_ext_fold: GICombineRule <
803  (defs root:$root, trunc_ext_fold_matchinfo:$matchinfo),
804  (match (wip_match_opcode G_TRUNC):$root,
805         [{ return Helper.matchCombineTruncOfExt(*${root}, ${matchinfo}); }]),
806  (apply [{ Helper.applyCombineTruncOfExt(*${root}, ${matchinfo}); }])
807>;
808
809// Under certain conditions, transform:
810//  trunc (shl x, K)     -> shl (trunc x), K//
811//  trunc ([al]shr x, K) -> (trunc ([al]shr (trunc x), K))
812def trunc_shift_matchinfo : GIDefMatchData<"std::pair<MachineInstr*, LLT>">;
813def trunc_shift: GICombineRule <
814  (defs root:$root, trunc_shift_matchinfo:$matchinfo),
815  (match (wip_match_opcode G_TRUNC):$root,
816         [{ return Helper.matchCombineTruncOfShift(*${root}, ${matchinfo}); }]),
817  (apply [{ Helper.applyCombineTruncOfShift(*${root}, ${matchinfo}); }])
818>;
819
820// Transform (mul x, -1) -> (sub 0, x)
821def mul_by_neg_one: GICombineRule <
822  (defs root:$dst),
823  (match (G_MUL $dst, $x, -1)),
824  (apply (G_SUB $dst, 0, $x))
825>;
826
827// Fold (xor (and x, y), y) -> (and (not x), y)
828def xor_of_and_with_same_reg_matchinfo :
829    GIDefMatchData<"std::pair<Register, Register>">;
830def xor_of_and_with_same_reg: GICombineRule <
831  (defs root:$root, xor_of_and_with_same_reg_matchinfo:$matchinfo),
832  (match (wip_match_opcode G_XOR):$root,
833         [{ return Helper.matchXorOfAndWithSameReg(*${root}, ${matchinfo}); }]),
834  (apply [{ Helper.applyXorOfAndWithSameReg(*${root}, ${matchinfo}); }])
835>;
836
837// Transform (ptr_add 0, x) -> (int_to_ptr x)
838def ptr_add_with_zero: GICombineRule<
839  (defs root:$root),
840  (match (wip_match_opcode G_PTR_ADD):$root,
841         [{ return Helper.matchPtrAddZero(*${root}); }]),
842  (apply [{ Helper.applyPtrAddZero(*${root}); }])>;
843
844def regs_small_vec : GIDefMatchData<"SmallVector<Register, 4>">;
845def combine_insert_vec_elts_build_vector : GICombineRule<
846  (defs root:$root, regs_small_vec:$info),
847  (match (wip_match_opcode G_INSERT_VECTOR_ELT):$root,
848    [{ return Helper.matchCombineInsertVecElts(*${root}, ${info}); }]),
849  (apply [{ Helper.applyCombineInsertVecElts(*${root}, ${info}); }])>;
850
851def load_or_combine : GICombineRule<
852  (defs root:$root, build_fn_matchinfo:$info),
853  (match (wip_match_opcode G_OR):$root,
854    [{ return Helper.matchLoadOrCombine(*${root}, ${info}); }]),
855  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
856
857def extend_through_phis_matchdata: GIDefMatchData<"MachineInstr*">;
858def extend_through_phis : GICombineRule<
859  (defs root:$root, extend_through_phis_matchdata:$matchinfo),
860  (match (wip_match_opcode G_PHI):$root,
861    [{ return Helper.matchExtendThroughPhis(*${root}, ${matchinfo}); }]),
862  (apply [{ Helper.applyExtendThroughPhis(*${root}, ${matchinfo}); }])>;
863
864// Currently only the one combine above.
865def insert_vec_elt_combines : GICombineGroup<
866                            [combine_insert_vec_elts_build_vector]>;
867
868def extract_vec_elt_build_vec : GICombineRule<
869  (defs root:$root, register_matchinfo:$matchinfo),
870  (match (wip_match_opcode G_EXTRACT_VECTOR_ELT):$root,
871    [{ return Helper.matchExtractVecEltBuildVec(*${root}, ${matchinfo}); }]),
872  (apply [{ Helper.applyExtractVecEltBuildVec(*${root}, ${matchinfo}); }])>;
873
874// Fold away full elt extracts from a build_vector.
875def extract_all_elts_from_build_vector_matchinfo :
876  GIDefMatchData<"SmallVector<std::pair<Register, MachineInstr*>>">;
877def extract_all_elts_from_build_vector : GICombineRule<
878  (defs root:$root, extract_all_elts_from_build_vector_matchinfo:$matchinfo),
879  (match (wip_match_opcode G_BUILD_VECTOR):$root,
880    [{ return Helper.matchExtractAllEltsFromBuildVector(*${root}, ${matchinfo}); }]),
881  (apply [{ Helper.applyExtractAllEltsFromBuildVector(*${root}, ${matchinfo}); }])>;
882
883def extract_vec_elt_combines : GICombineGroup<[
884  extract_vec_elt_build_vec,
885  extract_all_elts_from_build_vector]>;
886
887def funnel_shift_from_or_shift : GICombineRule<
888  (defs root:$root, build_fn_matchinfo:$info),
889  (match (wip_match_opcode G_OR):$root,
890    [{ return Helper.matchOrShiftToFunnelShift(*${root}, ${info}); }]),
891  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])
892>;
893
894def funnel_shift_to_rotate : GICombineRule<
895  (defs root:$root),
896  (match (wip_match_opcode G_FSHL, G_FSHR):$root,
897    [{ return Helper.matchFunnelShiftToRotate(*${root}); }]),
898  (apply [{ Helper.applyFunnelShiftToRotate(*${root}); }])
899>;
900
901// Fold fshr x, y, 0 -> y
902def funnel_shift_right_zero: GICombineRule<
903  (defs root:$root),
904  (match (G_FSHR $x, $y, $z, 0):$root),
905  (apply (COPY $x, $z))
906>;
907
908// Fold fshl x, y, 0 -> x
909def funnel_shift_left_zero: GICombineRule<
910  (defs root:$root),
911  (match (G_FSHL $x, $y, $z, 0):$root),
912  (apply (COPY $x, $y))
913>;
914
915// Fold fsh(l/r) x, y, C -> fsh(l/r) x, y, C % bw
916def funnel_shift_overshift: GICombineRule<
917  (defs root:$root),
918  (match (wip_match_opcode G_FSHL, G_FSHR):$root,
919    [{ return Helper.matchConstantLargerBitWidth(*${root}, 3); }]),
920  (apply [{ Helper.applyFunnelShiftConstantModulo(*${root}); }])
921>;
922
923def rotate_out_of_range : GICombineRule<
924  (defs root:$root),
925  (match (wip_match_opcode G_ROTR, G_ROTL):$root,
926    [{ return Helper.matchRotateOutOfRange(*${root}); }]),
927  (apply [{ Helper.applyRotateOutOfRange(*${root}); }])
928>;
929
930def icmp_to_true_false_known_bits : GICombineRule<
931  (defs root:$d, int64_matchinfo:$matchinfo),
932  (match (wip_match_opcode G_ICMP):$d,
933         [{ return Helper.matchICmpToTrueFalseKnownBits(*${d}, ${matchinfo}); }]),
934  (apply [{ Helper.replaceInstWithConstant(*${d}, ${matchinfo}); }])>;
935
936def icmp_to_lhs_known_bits : GICombineRule<
937  (defs root:$root, build_fn_matchinfo:$info),
938  (match (wip_match_opcode G_ICMP):$root,
939         [{ return Helper.matchICmpToLHSKnownBits(*${root}, ${info}); }]),
940  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
941
942def redundant_binop_in_equality : GICombineRule<
943  (defs root:$root, build_fn_matchinfo:$info),
944  (match (wip_match_opcode G_ICMP):$root,
945         [{ return Helper.matchRedundantBinOpInEquality(*${root}, ${info}); }]),
946  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
947
948def and_or_disjoint_mask : GICombineRule<
949  (defs root:$root, build_fn_matchinfo:$info),
950  (match (wip_match_opcode G_AND):$root,
951         [{ return Helper.matchAndOrDisjointMask(*${root}, ${info}); }]),
952  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${info}); }])>;
953
954def bitfield_extract_from_and : GICombineRule<
955  (defs root:$root, build_fn_matchinfo:$info),
956  (match (wip_match_opcode G_AND):$root,
957    [{ return Helper.matchBitfieldExtractFromAnd(*${root}, ${info}); }]),
958  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
959
960def funnel_shift_combines : GICombineGroup<[funnel_shift_from_or_shift,
961                                            funnel_shift_to_rotate,
962                                            funnel_shift_right_zero,
963                                            funnel_shift_left_zero,
964                                            funnel_shift_overshift]>;
965
966def bitfield_extract_from_sext_inreg : GICombineRule<
967  (defs root:$root, build_fn_matchinfo:$info),
968  (match (wip_match_opcode G_SEXT_INREG):$root,
969    [{ return Helper.matchBitfieldExtractFromSExtInReg(*${root}, ${info}); }]),
970  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
971
972def bitfield_extract_from_shr : GICombineRule<
973  (defs root:$root, build_fn_matchinfo:$info),
974  (match (wip_match_opcode G_ASHR, G_LSHR):$root,
975    [{ return Helper.matchBitfieldExtractFromShr(*${root}, ${info}); }]),
976  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
977
978def bitfield_extract_from_shr_and : GICombineRule<
979  (defs root:$root, build_fn_matchinfo:$info),
980  (match (wip_match_opcode G_ASHR, G_LSHR):$root,
981    [{ return Helper.matchBitfieldExtractFromShrAnd(*${root}, ${info}); }]),
982  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
983
984def form_bitfield_extract : GICombineGroup<[bitfield_extract_from_sext_inreg,
985                                            bitfield_extract_from_and,
986                                            bitfield_extract_from_shr,
987                                            bitfield_extract_from_shr_and]>;
988
989def udiv_by_const : GICombineRule<
990  (defs root:$root),
991  (match (wip_match_opcode G_UDIV):$root,
992   [{ return Helper.matchUDivByConst(*${root}); }]),
993  (apply [{ Helper.applyUDivByConst(*${root}); }])>;
994
995def sdiv_by_const : GICombineRule<
996  (defs root:$root),
997  (match (wip_match_opcode G_SDIV):$root,
998   [{ return Helper.matchSDivByConst(*${root}); }]),
999  (apply [{ Helper.applySDivByConst(*${root}); }])>;
1000
1001def intdiv_combines : GICombineGroup<[udiv_by_const, sdiv_by_const]>;
1002
1003def reassoc_ptradd : GICombineRule<
1004  (defs root:$root, build_fn_matchinfo:$matchinfo),
1005  (match (wip_match_opcode G_PTR_ADD):$root,
1006    [{ return Helper.matchReassocPtrAdd(*${root}, ${matchinfo}); }]),
1007  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${matchinfo}); }])>;
1008
1009def reassoc_comm_binops : GICombineRule<
1010  (defs root:$root, build_fn_matchinfo:$matchinfo),
1011  (match (G_ADD $root, $src1, $src2):$root,
1012    [{ return Helper.matchReassocCommBinOp(*${root}, ${matchinfo}); }]),
1013  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
1014
1015def reassocs : GICombineGroup<[reassoc_ptradd, reassoc_comm_binops]>;
1016
1017// Constant fold operations.
1018def constant_fold_binop : GICombineRule<
1019  (defs root:$d, apint_matchinfo:$matchinfo),
1020  (match (wip_match_opcode G_ADD, G_SUB, G_MUL, G_AND, G_OR, G_XOR, G_SHL, G_LSHR, G_ASHR):$d,
1021   [{ return Helper.matchConstantFoldBinOp(*${d}, ${matchinfo}); }]),
1022  (apply [{ Helper.replaceInstWithConstant(*${d}, ${matchinfo}); }])>;
1023
1024def constant_fold_fp_binop : GICombineRule<
1025  (defs root:$d, constantfp_matchinfo:$matchinfo),
1026  (match (wip_match_opcode G_FADD, G_FSUB, G_FMUL, G_FDIV):$d,
1027   [{ return Helper.matchConstantFoldFPBinOp(*${d}, ${matchinfo}); }]),
1028  (apply [{ Helper.replaceInstWithFConstant(*${d}, ${matchinfo}); }])>;
1029
1030
1031def constant_fold_fma : GICombineRule<
1032  (defs root:$d, constantfp_matchinfo:$matchinfo),
1033  (match (wip_match_opcode G_FMAD, G_FMA):$d,
1034   [{ return Helper.matchConstantFoldFMA(*${d}, ${matchinfo}); }]),
1035  (apply [{ Helper.replaceInstWithFConstant(*${d}, ${matchinfo}); }])>;
1036
1037def constant_fold_cast_op : GICombineRule<
1038  (defs root:$d, apint_matchinfo:$matchinfo),
1039  (match (wip_match_opcode G_ZEXT, G_SEXT, G_ANYEXT):$d,
1040   [{ return Helper.matchConstantFoldCastOp(*${d}, ${matchinfo}); }]),
1041  (apply [{ Helper.replaceInstWithConstant(*${d}, ${matchinfo}); }])>;
1042
1043def mulo_by_2: GICombineRule<
1044  (defs root:$root, build_fn_matchinfo:$matchinfo),
1045  (match (wip_match_opcode G_UMULO, G_SMULO):$root,
1046         [{ return Helper.matchMulOBy2(*${root}, ${matchinfo}); }]),
1047  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${matchinfo}); }])>;
1048
1049def mulo_by_0: GICombineRule<
1050  (defs root:$root, build_fn_matchinfo:$matchinfo),
1051  (match (wip_match_opcode G_UMULO, G_SMULO):$root,
1052         [{ return Helper.matchMulOBy0(*${root}, ${matchinfo}); }]),
1053  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
1054
1055def addo_by_0: GICombineRule<
1056  (defs root:$root, build_fn_matchinfo:$matchinfo),
1057  (match (wip_match_opcode G_UADDO, G_SADDO):$root,
1058         [{ return Helper.matchAddOBy0(*${root}, ${matchinfo}); }]),
1059  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
1060
1061// Transform (uadde x, y, 0) -> (uaddo x, y)
1062//           (sadde x, y, 0) -> (saddo x, y)
1063//           (usube x, y, 0) -> (usubo x, y)
1064//           (ssube x, y, 0) -> (ssubo x, y)
1065def adde_to_addo: GICombineRule<
1066  (defs root:$root, build_fn_matchinfo:$matchinfo),
1067  (match (wip_match_opcode G_UADDE, G_SADDE, G_USUBE, G_SSUBE):$root,
1068         [{ return Helper.matchAddEToAddO(*${root}, ${matchinfo}); }]),
1069  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${matchinfo}); }])>;
1070
1071def mulh_to_lshr : GICombineRule<
1072  (defs root:$root),
1073  (match (wip_match_opcode G_UMULH):$root,
1074         [{ return Helper.matchUMulHToLShr(*${root}); }]),
1075  (apply [{ Helper.applyUMulHToLShr(*${root}); }])>;
1076
1077def mulh_combines : GICombineGroup<[mulh_to_lshr]>;
1078
1079def redundant_neg_operands: GICombineRule<
1080  (defs root:$root, build_fn_matchinfo:$matchinfo),
1081  (match (wip_match_opcode G_FADD, G_FSUB, G_FMUL, G_FDIV, G_FMAD, G_FMA):$root,
1082    [{ return Helper.matchRedundantNegOperands(*${root}, ${matchinfo}); }]),
1083  (apply [{ Helper.applyBuildFnNoErase(*${root}, ${matchinfo}); }])>;
1084
1085// Transform (fsub +-0.0, X) -> (fneg X)
1086def fsub_to_fneg: GICombineRule<
1087  (defs root:$root, register_matchinfo:$matchinfo),
1088  (match (wip_match_opcode G_FSUB):$root,
1089    [{ return Helper.matchFsubToFneg(*${root}, ${matchinfo}); }]),
1090  (apply [{ Helper.applyFsubToFneg(*${root}, ${matchinfo}); }])>;
1091
1092// Transform (fadd x, (fmul y, z)) -> (fma y, z, x)
1093//           (fadd x, (fmul y, z)) -> (fmad y, z, x)
1094// Transform (fadd (fmul x, y), z) -> (fma x, y, z)
1095//           (fadd (fmul x, y), z) -> (fmad x, y, z)
1096def combine_fadd_fmul_to_fmad_or_fma: GICombineRule<
1097  (defs root:$root, build_fn_matchinfo:$info),
1098  (match (wip_match_opcode G_FADD):$root,
1099         [{ return Helper.matchCombineFAddFMulToFMadOrFMA(*${root},
1100                                                          ${info}); }]),
1101  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1102
1103// Transform (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
1104//                                         -> (fmad (fpext x), (fpext y), z)
1105// Transform (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
1106//                                         -> (fmad (fpext y), (fpext z), x)
1107def combine_fadd_fpext_fmul_to_fmad_or_fma: GICombineRule<
1108  (defs root:$root, build_fn_matchinfo:$info),
1109  (match (wip_match_opcode G_FADD):$root,
1110         [{ return Helper.matchCombineFAddFpExtFMulToFMadOrFMA(*${root},
1111                                                               ${info}); }]),
1112  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1113
1114// Transform (fadd (fma x, y, (fmul z, u)), v)  -> (fma x, y, (fma z, u, v))
1115//           (fadd (fmad x, y, (fmul z, u)), v) -> (fmad x, y, (fmad z, u, v))
1116// Transform (fadd v, (fma x, y, (fmul z, u)))  -> (fma x, y, (fma z, u, v))
1117//           (fadd v, (fmad x, y, (fmul z, u))) -> (fmad x, y, (fmad z, u, v))
1118def combine_fadd_fma_fmul_to_fmad_or_fma: GICombineRule<
1119  (defs root:$root, build_fn_matchinfo:$info),
1120  (match (wip_match_opcode G_FADD):$root,
1121         [{ return Helper.matchCombineFAddFMAFMulToFMadOrFMA(*${root},
1122                                                             ${info}); }]),
1123  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1124
1125// Transform (fadd (fma x, y, (fpext (fmul u, v))), z) ->
1126//           (fma x, y, (fma (fpext u), (fpext v), z))
1127def combine_fadd_fpext_fma_fmul_to_fmad_or_fma: GICombineRule<
1128  (defs root:$root, build_fn_matchinfo:$info),
1129  (match (wip_match_opcode G_FADD):$root,
1130         [{ return Helper.matchCombineFAddFpExtFMulToFMadOrFMAAggressive(
1131                                                  *${root}, ${info}); }]),
1132  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1133
1134// Transform (fsub (fmul x, y), z) -> (fma x, y, -z)
1135//                                 -> (fmad x, y, -z)
1136def combine_fsub_fmul_to_fmad_or_fma: GICombineRule<
1137  (defs root:$root, build_fn_matchinfo:$info),
1138  (match (wip_match_opcode G_FSUB):$root,
1139         [{ return Helper.matchCombineFSubFMulToFMadOrFMA(*${root},
1140                                                          ${info}); }]),
1141  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1142
1143// Transform (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
1144//           (fsub x, (fneg (fmul, y, z))) -> (fma y, z, x)
1145def combine_fsub_fneg_fmul_to_fmad_or_fma: GICombineRule<
1146  (defs root:$root, build_fn_matchinfo:$info),
1147  (match (wip_match_opcode G_FSUB):$root,
1148         [{ return Helper.matchCombineFSubFNegFMulToFMadOrFMA(*${root},
1149                                                              ${info}); }]),
1150  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1151
1152// Transform (fsub (fpext (fmul x, y)), z) ->
1153//           (fma (fpext x), (fpext y), (fneg z))
1154def combine_fsub_fpext_fmul_to_fmad_or_fma: GICombineRule<
1155  (defs root:$root, build_fn_matchinfo:$info),
1156  (match (wip_match_opcode G_FSUB):$root,
1157         [{ return Helper.matchCombineFSubFpExtFMulToFMadOrFMA(*${root},
1158                                                               ${info}); }]),
1159  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1160
1161// Transform (fsub (fneg (fpext (fmul x, y))), z) ->
1162//           (fneg (fma (fpext x), (fpext y), z))
1163def combine_fsub_fpext_fneg_fmul_to_fmad_or_fma: GICombineRule<
1164  (defs root:$root, build_fn_matchinfo:$info),
1165  (match (wip_match_opcode G_FSUB):$root,
1166         [{ return Helper.matchCombineFSubFpExtFNegFMulToFMadOrFMA(
1167                                            *${root}, ${info}); }]),
1168  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1169
1170def combine_minmax_nan: GICombineRule<
1171  (defs root:$root, unsigned_matchinfo:$info),
1172  (match (wip_match_opcode G_FMINNUM, G_FMAXNUM, G_FMINIMUM, G_FMAXIMUM):$root,
1173         [{ return Helper.matchCombineFMinMaxNaN(*${root}, ${info}); }]),
1174  (apply [{ Helper.replaceSingleDefInstWithOperand(*${root}, ${info}); }])>;
1175
1176// Transform (add x, (sub y, x)) -> y
1177// Transform (add (sub y, x), x) -> y
1178def add_sub_reg_frags : GICombinePatFrag<
1179  (outs root:$dst), (ins $src),
1180  [
1181    (pattern (G_ADD $dst, $x, $tmp), (G_SUB $tmp, $src, $x)),
1182    (pattern (G_ADD $dst, $tmp, $x), (G_SUB $tmp, $src, $x))
1183  ]>;
1184def add_sub_reg: GICombineRule <
1185  (defs root:$dst),
1186  (match (add_sub_reg_frags $dst, $src)),
1187  (apply (GIReplaceReg $dst, $src))>;
1188
1189def buildvector_identity_fold : GICombineRule<
1190  (defs root:$build_vector, register_matchinfo:$matchinfo),
1191  (match (wip_match_opcode G_BUILD_VECTOR_TRUNC, G_BUILD_VECTOR):$build_vector,
1192         [{ return Helper.matchBuildVectorIdentityFold(*${build_vector}, ${matchinfo}); }]),
1193  (apply [{ Helper.replaceSingleDefInstWithReg(*${build_vector}, ${matchinfo}); }])>;
1194
1195def trunc_buildvector_fold : GICombineRule<
1196  (defs root:$op, register_matchinfo:$matchinfo),
1197  (match (wip_match_opcode G_TRUNC):$op,
1198      [{ return Helper.matchTruncBuildVectorFold(*${op}, ${matchinfo}); }]),
1199  (apply [{ Helper.replaceSingleDefInstWithReg(*${op}, ${matchinfo}); }])>;
1200
1201def trunc_lshr_buildvector_fold : GICombineRule<
1202  (defs root:$op, register_matchinfo:$matchinfo),
1203  (match (wip_match_opcode G_TRUNC):$op,
1204      [{ return Helper.matchTruncLshrBuildVectorFold(*${op}, ${matchinfo}); }]),
1205  (apply [{ Helper.replaceSingleDefInstWithReg(*${op}, ${matchinfo}); }])>;
1206
1207// Transform:
1208//   (x + y) - y -> x
1209//   (x + y) - x -> y
1210//   x - (y + x) -> 0 - y
1211//   x - (x + z) -> 0 - z
1212def sub_add_reg: GICombineRule <
1213  (defs root:$root, build_fn_matchinfo:$matchinfo),
1214  (match (wip_match_opcode G_SUB):$root,
1215         [{ return Helper.matchSubAddSameReg(*${root}, ${matchinfo}); }]),
1216  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
1217
1218def bitcast_bitcast_fold : GICombineRule<
1219  (defs root:$dst),
1220  (match (G_BITCAST $dst, $src1):$op, (G_BITCAST $src1, $src0),
1221      [{ return MRI.getType(${src0}.getReg()) == MRI.getType(${dst}.getReg()); }]),
1222  (apply [{ Helper.replaceSingleDefInstWithReg(*${op}, ${src0}.getReg()); }])>;
1223
1224
1225def fptrunc_fpext_fold : GICombineRule<
1226  (defs root:$dst),
1227  (match (G_FPTRUNC $dst, $src1):$op, (G_FPEXT $src1, $src0),
1228      [{ return MRI.getType(${src0}.getReg()) == MRI.getType(${dst}.getReg()); }]),
1229  (apply [{ Helper.replaceSingleDefInstWithReg(*${op}, ${src0}.getReg()); }])>;
1230
1231
1232def select_to_minmax: GICombineRule<
1233  (defs root:$root, build_fn_matchinfo:$info),
1234  (match (wip_match_opcode G_SELECT):$root,
1235         [{ return Helper.matchSimplifySelectToMinMax(*${root}, ${info}); }]),
1236  (apply [{ Helper.applyBuildFn(*${root}, ${info}); }])>;
1237
1238def match_selects : GICombineRule<
1239  (defs root:$root, build_fn_matchinfo:$matchinfo),
1240  (match (wip_match_opcode G_SELECT):$root,
1241        [{ return Helper.matchSelect(*${root}, ${matchinfo}); }]),
1242  (apply [{ Helper.applyBuildFn(*${root}, ${matchinfo}); }])>;
1243
1244// FIXME: These should use the custom predicate feature once it lands.
1245def undef_combines : GICombineGroup<[undef_to_fp_zero, undef_to_int_zero,
1246                                     undef_to_negative_one,
1247                                     binop_left_undef_to_zero,
1248                                     binop_right_undef_to_undef,
1249                                     unary_undef_to_zero,
1250                                     propagate_undef_any_op,
1251                                     propagate_undef_all_ops,
1252                                     propagate_undef_shuffle_mask,
1253                                     erase_undef_store,
1254                                     unmerge_undef,
1255                                     insert_extract_vec_elt_out_of_bounds]>;
1256
1257def identity_combines : GICombineGroup<[select_same_val, right_identity_zero,
1258                                        binop_same_val, binop_left_to_zero,
1259                                        binop_right_to_zero, p2i_to_i2p,
1260                                        i2p_to_p2i, anyext_trunc_fold,
1261                                        fneg_fneg_fold, right_identity_one,
1262                                        add_sub_reg, buildvector_identity_fold,
1263                                        trunc_buildvector_fold,
1264                                        trunc_lshr_buildvector_fold,
1265                                        bitcast_bitcast_fold, fptrunc_fpext_fold,
1266                                        right_identity_neg_zero_fp]>;
1267
1268def const_combines : GICombineGroup<[constant_fold_fp_ops, const_ptradd_to_i2p,
1269                                     overlapping_and, mulo_by_2, mulo_by_0,
1270                                     addo_by_0, adde_to_addo,
1271                                     combine_minmax_nan]>;
1272
1273def known_bits_simplifications : GICombineGroup<[
1274  redundant_and, redundant_sext_inreg, redundant_or, urem_pow2_to_mask,
1275  zext_trunc_fold, icmp_to_true_false_known_bits, icmp_to_lhs_known_bits,
1276  sext_inreg_to_zext_inreg]>;
1277
1278def width_reduction_combines : GICombineGroup<[reduce_shl_of_extend,
1279                                               narrow_binop_feeding_and]>;
1280
1281def phi_combines : GICombineGroup<[extend_through_phis]>;
1282
1283def select_combines : GICombineGroup<[select_undef_cmp, select_constant_cmp,
1284                                      match_selects]>;
1285
1286def trivial_combines : GICombineGroup<[copy_prop, mul_to_shl, add_p2i_to_ptradd,
1287                                       mul_by_neg_one, idempotent_prop]>;
1288
1289def fma_combines : GICombineGroup<[combine_fadd_fmul_to_fmad_or_fma,
1290  combine_fadd_fpext_fmul_to_fmad_or_fma, combine_fadd_fma_fmul_to_fmad_or_fma,
1291  combine_fadd_fpext_fma_fmul_to_fmad_or_fma, combine_fsub_fmul_to_fmad_or_fma,
1292  combine_fsub_fneg_fmul_to_fmad_or_fma, combine_fsub_fpext_fmul_to_fmad_or_fma,
1293  combine_fsub_fpext_fneg_fmul_to_fmad_or_fma]>;
1294
1295def constant_fold_binops : GICombineGroup<[constant_fold_binop,
1296                                           constant_fold_fp_binop]>;
1297
1298def all_combines : GICombineGroup<[trivial_combines, insert_vec_elt_combines,
1299    extract_vec_elt_combines, combines_for_extload, combine_extracted_vector_load,
1300    undef_combines, identity_combines, phi_combines,
1301    simplify_add_to_sub, hoist_logic_op_with_same_opcode_hands, shifts_too_big,
1302    reassocs, ptr_add_immed_chain,
1303    shl_ashr_to_sext_inreg, sext_inreg_of_load,
1304    width_reduction_combines, select_combines,
1305    known_bits_simplifications, ext_ext_fold,
1306    not_cmp_fold, opt_brcond_by_inverting_cond,
1307    unmerge_merge, unmerge_cst, unmerge_dead_to_trunc,
1308    unmerge_zext_to_zext, merge_unmerge, trunc_ext_fold, trunc_shift,
1309    const_combines, xor_of_and_with_same_reg, ptr_add_with_zero,
1310    shift_immed_chain, shift_of_shifted_logic_chain, load_or_combine,
1311    div_rem_to_divrem, funnel_shift_combines, commute_shift,
1312    form_bitfield_extract, constant_fold_binops, constant_fold_fma,
1313    constant_fold_cast_op, fabs_fneg_fold,
1314    intdiv_combines, mulh_combines, redundant_neg_operands,
1315    and_or_disjoint_mask, fma_combines, fold_binop_into_select,
1316    sub_add_reg, select_to_minmax, redundant_binop_in_equality,
1317    fsub_to_fneg, commute_constant_to_rhs]>;
1318
1319// A combine group used to for prelegalizer combiners at -O0. The combines in
1320// this group have been selected based on experiments to balance code size and
1321// compile time performance.
1322def optnone_combines : GICombineGroup<[trivial_combines,
1323    ptr_add_immed_chain, combines_for_extload,
1324    not_cmp_fold, opt_brcond_by_inverting_cond]>;
1325