1 /*
2  * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #ifndef SHARE_ADLC_FORMSOPT_HPP
26 #define SHARE_ADLC_FORMSOPT_HPP
27 
28 // FORMSOPT.HPP - ADL Parser Target Specific Optimization Forms Classes
29 
30 // Class List
31 class Form;
32 class InstructForm;
33 class OperandForm;
34 class OpClassForm;
35 class AttributeForm;
36 class RegisterForm;
37 class PipelineForm;
38 class SourceForm;
39 class EncodeForm;
40 class Component;
41 class Constraint;
42 class Predicate;
43 class MatchRule;
44 class Attribute;
45 class Effect;
46 class ExpandRule;
47 class RewriteRule;
48 class ConstructRule;
49 class FormatRule;
50 class Peephole;
51 class PeepMatch;
52 class PeepConstraint;
53 class EncClass;
54 class Interface;
55 class RegInterface;
56 class ConstInterface;
57 class MemInterface;
58 class CondInterface;
59 class Opcode;
60 class InsEncode;
61 class RegDef;
62 class RegClass;
63 class CodeSnippetRegClass;
64 class ConditionalRegClass;
65 class AllocClass;
66 class ResourceForm;
67 class PipeClassForm;
68 class PipeClassOperandForm;
69 class PipeClassResourceForm;
70 class PeepMatch;
71 class PeepConstraint;
72 class PeepReplace;
73 class MatchList;
74 
75 class ArchDesc;
76 
77 //==============================Register Allocation============================
78 //------------------------------RegisterForm-----------------------------------
79 class RegisterForm : public Form {
80 private:
81   AllocClass *_current_ac;         // State used by iter_RegDefs()
82 
83 public:
84   // Public Data
85   NameList    _rdefs;              // List of register definition names
86   Dict        _regDef;             // map register name to RegDef*
87 
88   NameList    _rclasses;           // List of register class names
89   Dict        _regClass;           // map register class name to RegClass*
90 
91   NameList    _aclasses;           // List of allocation class names
92   Dict        _allocClass;         // Dictionary of allocation classes
93 
94   static int  _reg_ctr;         // Register counter
95   static int  RegMask_Size();   // Compute RegMask size
96 
97   // Public Methods
98   RegisterForm();
99   ~RegisterForm();
100 
101   void        addRegDef(char *regName, char *callingConv, char *c_conv,
102                         char * idealtype, char *encoding, char* concreteName);
103   template<typename T> T* addRegClass(const char* className);
104 
105   AllocClass *addAllocClass(char *allocName);
106   void        addSpillRegClass();
107   void        addDynamicRegClass();
108 
109   // Provide iteration over all register definitions
110   // in the order used by the register allocator
111   void        reset_RegDefs();
112   RegDef     *iter_RegDefs();
113   RegDef     *getRegDef  (const char *regName);
114 
115   RegClass   *getRegClass(const char *className);
116 
117   // Return register mask, compressed chunk and register #
118   uint       reg_mask(char *register_class);
119 
120   // Check that register classes are compatible with chunks
121   bool       verify();
122 
123   void dump();                     // Debug printer
124   void output(FILE *fp);           // Write info to output files
125 };
126 
127 //------------------------------RegDef-----------------------------------------
128 class RegDef : public Form {
129 public:
130   // Public Data
131   const char *_regname;            // ADLC (Opto) Register name
132   const char *_callconv;           // Calling convention
133   const char *_c_conv;             // Native calling convention, 'C'
134   const char *_idealtype;          // Ideal Type for register save/restore
135   const char *_concrete;           // concrete register name
136 
137 private:
138   const char *_register_encode;   // The register encoding
139   // The chunk and register mask bits define info for register allocation
140   uint32      _register_num;      // Which register am I
141 
142 public:
143   // Public Methods
144   RegDef(char  *regname, char *callconv, char *c_conv,
145          char *idealtype, char *encoding, char *concrete);
146   ~RegDef();                       // Destructor
147 
148   // Interface to define/redefine the register number
149   void     set_register_num(uint32 new_register_num);
150 
151   // Bit pattern used for generating machine code
152   const char *register_encode()   const;
153   // Register number used in machine-independent code
154   uint32   register_num()      const;
155 
156   void dump();                     // Debug printer
157   void output(FILE *fp);           // Write info to output files
158 };
159 
160 //------------------------------RegClass---------------------------------------
161 // Generic register class. This register class is the internal representation
162 // for the following .ad file format:
163 //
164 //  reg_class ptr(RAX, RBX, ...);
165 //
166 // where ptr is the name of the register class, RAX and RBX are registers.
167 //
168 // This register class allows registers to be spilled onto the stack. Spilling
169 // is allowed is field _stack_or_reg is true.
170 class RegClass : public Form {
171 public:
172   // Public Data
173   const char *_classid;         // Name of class
174   NameList    _regDefs;         // List of registers in class
175   Dict        _regDef;          // Dictionary of registers in class
176 protected:
177   bool        _stack_or_reg;    // Allowed on any stack slot
178 
179 public:
180   // Public Methods
181   RegClass(const char *classid);// Constructor
182   virtual ~RegClass();
183 
184   void addReg(RegDef *regDef);  // Add a register to this class
185 
186   uint size() const;            // Number of registers in class
187   int regs_in_word( int wordnum, bool stack_also );
188 
189   const RegDef *get_RegDef(const char *regDef_name) const;
190 
191   // Returns the lowest numbered register in the mask.
192   const RegDef* find_first_elem();
193 
194   // Iteration support
195   void          reset();        // Reset the following two iterators
196   RegDef       *RegDef_iter();  // which move jointly,
197   const char   *rd_name_iter(); // invoking either advances both.
198 
199   void dump();                  // Debug printer
200   void output(FILE *fp);        // Write info to output files
201 
has_stack_version()202   virtual bool has_stack_version() {
203     return _stack_or_reg;
204   }
set_stack_version(bool flag)205   virtual void set_stack_version(bool flag) {
206     _stack_or_reg = flag;
207   }
208 
209   virtual void declare_register_masks(FILE* fp);
210   virtual void build_register_masks(FILE* fp);
211 };
212 
213 //------------------------------CodeSnippetRegClass----------------------------
214 // Register class that has an user-defined C++ code snippet attached to it
215 // to determine at runtime which register class to use. This register class is
216 // the internal representation for the following .ad file format:
217 //
218 //  reg_class actual_dflt_reg %{
219 //      if (VM_Version::has_vfp3_32()) {
220 //          return DFLT_REG_mask();
221 //      } else {
222 //          return DFLT_LOW_REG_mask();
223 //      }
224 //  %}
225 //
226 // where DFLT_REG_mask() and DFLT_LOW_REG_mask() are the internal names of the
227 // masks of register classes dflt_reg and dflt_low_reg.
228 //
229 // The attached code snippet can select also between more than two register classes.
230 // This register class can be, however, used only if the register class is not
231 // cisc-spillable (i.e., the registers of this class are not allowed on the stack,
232 // which is equivalent with _stack_or_reg being false).
233 class CodeSnippetRegClass : public RegClass {
234 protected:
235   char* _code_snippet;
236 public:
237   CodeSnippetRegClass(const char* classid);// Constructor
238   ~CodeSnippetRegClass();
239 
set_code_snippet(char * code)240   void set_code_snippet(char* code) {
241     _code_snippet = code;
242   }
code_snippet()243   char* code_snippet() {
244     return _code_snippet;
245   }
246   void declare_register_masks(FILE* fp);
build_register_masks(FILE * fp)247   void build_register_masks(FILE* fp) {
248     // We do not need to generate register masks because we select at runtime
249     // between register masks generated for other register classes.
250     return;
251   }
252 };
253 
254 //------------------------------ConditionalRegClass----------------------------
255 // Register class that has two register classes and a runtime condition attached
256 // to it. The condition is evaluated at runtime and either one of the register
257 // attached register classes is selected. This register class is the internal
258 // representation for the following .ad format:
259 //
260 //  reg_class_dynamic actual_dflt_reg(dflt_reg, low_reg,
261 //                                    %{ VM_Version::has_vfp3_32() }%
262 //                                    );
263 //
264 // This example is equivalent to the example used with the CodeSnippetRegClass
265 // register class. A ConditionalRegClass works also if a register class is cisc-spillable
266 // (i.e., _stack_or_reg is true), but if can select only between two register classes.
267 class ConditionalRegClass : public RegClass {
268 protected:
269   // reference to condition code
270   char* _condition_code;  // C++ condition code to dynamically determine which register class to use.
271 
272                           // Example syntax (equivalent to previous example):
273                           //
274                           //  reg_class actual_dflt_reg(dflt_reg, low_reg,
275                           //                            %{ VM_Version::has_vfp3_32() }%
276                           //                            );
277   // reference to conditional register classes
278   RegClass* _rclasses[2]; // 0 is the register class selected if the condition code returns true
279                           // 1 is the register class selected if the condition code returns false
280 public:
281   ConditionalRegClass(const char* classid);// Constructor
282   ~ConditionalRegClass();
283 
set_stack_version(bool flag)284   virtual void set_stack_version(bool flag) {
285     RegClass::set_stack_version(flag);
286     assert((_rclasses[0] != NULL), "Register class NULL for condition code == true");
287     assert((_rclasses[1] != NULL), "Register class NULL for condition code == false");
288     _rclasses[0]->set_stack_version(flag);
289     _rclasses[1]->set_stack_version(flag);
290   }
291   void declare_register_masks(FILE* fp);
build_register_masks(FILE * fp)292   void build_register_masks(FILE* fp) {
293     // We do not need to generate register masks because we select at runtime
294     // between register masks generated for other register classes.
295     return;
296   }
set_rclass_at_index(int index,RegClass * rclass)297   void set_rclass_at_index(int index, RegClass* rclass) {
298     assert((0 <= index && index < 2), "Condition code can select only between two register classes");
299     _rclasses[index] = rclass;
300   }
set_condition_code(char * code)301   void set_condition_code(char* code) {
302     _condition_code = code;
303   }
condition_code()304   char* condition_code() {
305     return _condition_code;
306   }
307 };
308 
309 //------------------------------AllocClass-------------------------------------
310 class AllocClass : public Form {
311 private:
312 
313 public:
314   // Public Data
315   char    *_classid;            // Name of class
316   NameList _regDefs;            // List of registers in class
317   Dict     _regDef;             // Dictionary of registers in class
318 
319   // Public Methods
320   AllocClass(char *classid);    // Constructor
321 
322   void addReg(RegDef *regDef);  // Add a register to this class
size()323   uint size() {return _regDef.Size();} // Number of registers in class
324 
325   void dump();                  // Debug printer
326   void output(FILE *fp);        // Write info to output files
327 };
328 
329 
330 //==============================Frame Handling================================
331 //------------------------------FrameForm-------------------------------------
332 class FrameForm : public Form {
333 private:
334 
335 public:
336   // Public Data
337   bool  _direction;                // Direction of stack growth
338   char *_sync_stack_slots;
339   char *_inline_cache_reg;
340   char *_interpreter_method_oop_reg;
341   char *_interpreter_frame_pointer_reg;
342   char *_cisc_spilling_operand_name;
343   char *_frame_pointer;
344   char *_c_frame_pointer;
345   char *_alignment;
346   bool  _return_addr_loc;
347   bool  _c_return_addr_loc;
348   char *_return_addr;
349   char *_c_return_addr;
350   char *_in_preserve_slots;
351   char *_varargs_C_out_slots_killed;
352   char *_calling_convention;
353   char *_c_calling_convention;
354   char *_return_value;
355   char *_c_return_value;
356 
357   // Public Methods
358   FrameForm();
359   ~FrameForm();
360 
361   void dump();                     // Debug printer
362   void output(FILE *fp);           // Write info to output files
363 };
364 
365 
366 //==============================Scheduling=====================================
367 //------------------------------PipelineForm-----------------------------------
368 class PipelineForm : public Form {
369 private:
370 
371 public:
372   // Public Data
373   NameList   _reslist;            // List of pipeline resources
374   FormDict   _resdict;            // Resource Name -> ResourceForm mapping
375   int        _rescount;           // Number of resources (ignores OR cases)
376   int        _maxcycleused;       // Largest cycle used relative to beginning of instruction
377 
378   NameList   _stages;             // List of pipeline stages on architecture
379   int        _stagecnt;           // Number of stages listed
380 
381   NameList   _classlist;          // List of pipeline classes
382   FormDict   _classdict;          // Class Name -> PipeClassForm mapping
383   int        _classcnt;           // Number of classes
384 
385   NameList   _noplist;            // List of NOP instructions
386   int        _nopcnt;             // Number of nop instructions
387 
388   bool       _variableSizeInstrs; // Indicates if this architecture has variable sized instructions
389   bool       _branchHasDelaySlot; // Indicates that branches have delay slot instructions
390   int        _maxInstrsPerBundle; // Indicates the maximum number of instructions for ILP
391   int        _maxBundlesPerCycle; // Indicates the maximum number of bundles for ILP
392   int        _instrUnitSize;      // The minimum instruction unit size, in bytes
393   int        _bundleUnitSize;     // The bundle unit size, in bytes
394   int        _instrFetchUnitSize; // The size of the I-fetch unit, in bytes [must be power of 2]
395   int        _instrFetchUnits;    // The number of I-fetch units processed per cycle
396 
397   // Public Methods
398   PipelineForm();
399   ~PipelineForm();
400 
401   void dump();                    // Debug printer
402   void output(FILE *fp);          // Write info to output files
403 };
404 
405 //------------------------------ResourceForm-----------------------------------
406 class ResourceForm : public Form {
407 public:
mask() const408   unsigned mask() const { return _resmask; };
409 
410 private:
411   // Public Data
412   unsigned _resmask;         // Resource Mask (OR of resource specifier bits)
413 
414 public:
415 
416   // Virtual Methods
417   virtual ResourceForm  *is_resource()    const;
418 
419   // Public Methods
420   ResourceForm(unsigned resmask); // Constructor
421   ~ResourceForm();                // Destructor
422 
423   void dump();                    // Debug printer
424   void output(FILE *fp);          // Write info to output files
425 };
426 
427 //------------------------------PipeClassOperandForm-----------------------------
428 class PipeClassOperandForm : public Form {
429 private:
430 
431 public:
432   // Public Data
433   const char *_stage;             // Name of Stage
434   unsigned _iswrite;              // Read or Write
435   unsigned _more_instrs;          // Additional Instructions
436 
437   // Public Methods
PipeClassOperandForm(const char * stage,unsigned iswrite,unsigned more_instrs)438   PipeClassOperandForm(const char *stage, unsigned iswrite, unsigned more_instrs)
439   : _stage(stage)
440   , _iswrite(iswrite)
441   , _more_instrs(more_instrs)
442  {};
443 
~PipeClassOperandForm()444   ~PipeClassOperandForm() {};     // Destructor
445 
isWrite() const446   bool isWrite() const { return _iswrite != 0; }
447 
448   void dump();                    // Debug printer
449   void output(FILE *fp);          // Write info to output files
450 };
451 
452 //------------------------------PipeClassResourceForm--------------------------
453 class PipeClassResourceForm : public Form {
454 private:
455 
456 public:
457   // Public Data
458   const char *_resource;          // Resource
459   const char *_stage;             // Stage the resource is used in
460   int         _cycles;            // Number of cycles the resource is used
461 
462   // Public Methods
PipeClassResourceForm(const char * resource,const char * stage,int cycles)463   PipeClassResourceForm(const char *resource, const char *stage, int cycles)
464                                   // Constructor
465     : _resource(resource)
466     , _stage(stage)
467     , _cycles(cycles)
468     {};
469 
~PipeClassResourceForm()470   ~PipeClassResourceForm() {};    // Destructor
471 
472   void dump();                    // Debug printer
473   void output(FILE *fp);          // Write info to output files
474 };
475 
476 //------------------------------PipeClassForm----------------------------------
477 class PipeClassForm : public Form {
478 private:
479 
480 public:
481 
482   // Public Data
483   const char       *_ident;             // Name of class
484   int               _num;               // Used in name of MachNode subclass
485   NameList          _parameters;        // Locally defined names
486   FormDict          _localNames;        // Table of operands & their types
487   FormDict          _localUsage;        // Table of operand usage
488   FormList          _resUsage;          // List of resource usage
489   NameList          _instructs;         // List of instructions and machine nodes that use this pipeline class
490   bool              _has_fixed_latency; // Always takes this number of cycles
491   int               _fixed_latency;     // Always takes this number of cycles
492   int               _instruction_count; // Number of instructions in first bundle
493   bool              _has_multiple_bundles;  // Indicates if 1 or multiple bundles
494   bool              _has_branch_delay_slot; // Has branch delay slot as last instruction
495   bool              _force_serialization;   // This node serializes relative to surrounding nodes
496   bool              _may_have_no_code;      // This node may generate no code based on register allocation
497 
498   // Virtual Methods
499   virtual PipeClassForm  *is_pipeclass()    const;
500 
501   // Public Methods
502   PipeClassForm(const char *id, int num);
503                                   // Constructor
504   ~PipeClassForm();               // Destructor
505 
hasFixedLatency()506   bool hasFixedLatency() { return _has_fixed_latency; }
fixedLatency()507   int fixedLatency() { return _fixed_latency; }
508 
setFixedLatency(int fixed_latency)509   void setFixedLatency(int fixed_latency) { _has_fixed_latency = 1; _fixed_latency = fixed_latency; }
510 
setInstructionCount(int i)511   void setInstructionCount(int i)    { _instruction_count = i; }
setMultipleBundles(bool b)512   void setMultipleBundles(bool b)    { _has_multiple_bundles = b; }
setBranchDelay(bool s)513   void setBranchDelay(bool s)        { _has_branch_delay_slot = s; }
setForceSerialization(bool s)514   void setForceSerialization(bool s) { _force_serialization = s; }
setMayHaveNoCode(bool s)515   void setMayHaveNoCode(bool s)      { _may_have_no_code = s; }
516 
InstructionCount() const517   int  InstructionCount()   const { return _instruction_count; }
hasMultipleBundles() const518   bool hasMultipleBundles() const { return _has_multiple_bundles; }
hasBranchDelay() const519   bool hasBranchDelay()     const { return _has_branch_delay_slot; }
forceSerialization() const520   bool forceSerialization() const { return _force_serialization; }
mayHaveNoCode() const521   bool mayHaveNoCode()      const { return _may_have_no_code; }
522 
523   void dump();                    // Debug printer
524   void output(FILE *fp);          // Write info to output files
525 };
526 
527 
528 //==============================Peephole Optimization==========================
529 //------------------------------Peephole---------------------------------------
530 class Peephole : public Form {
531 private:
532   static int      _peephole_counter;// Incremented by each peephole rule parsed
533   int             _peephole_number;// Remember my order in architecture description
534   PeepMatch      *_match;          // Instruction pattern to match
535   PeepConstraint *_constraint;     // List of additional constraints
536   PeepReplace    *_replace;        // Instruction pattern to substitute in
537 
538   Peephole *_next;
539 
540 public:
541   // Public Methods
542   Peephole();
543   ~Peephole();
544 
545   // Append a peephole rule with the same root instruction
546   void append_peephole(Peephole *next_peephole);
547 
548   // Store the components of this peephole rule
549   void add_match(PeepMatch *only_one_match);
550   void append_constraint(PeepConstraint *next_constraint);
551   void add_replace(PeepReplace *only_one_replacement);
552 
553   // Access the components of this peephole rule
peephole_number()554   int             peephole_number() { return _peephole_number; }
match()555   PeepMatch      *match()       { return _match; }
constraints()556   PeepConstraint *constraints() { return _constraint; }
replacement()557   PeepReplace    *replacement() { return _replace; }
next()558   Peephole       *next()        { return _next; }
559 
560   void dump();                     // Debug printer
561   void output(FILE *fp);           // Write info to output files
562 };
563 
564 
565 class PeepMatch : public Form {
566 private:
567   char *_rule;
568   // NameList  _depth;                // Depth of this instruction
569   NameList  _parent;
570   NameList  _position;
571   NameList  _instrs;               // List of instructions in match rule
572   NameList  _input;                // input position in parent's instruction
573   int       _max_position;
574 
575 public:
576   // Public Methods
577   PeepMatch(char *rule);
578   ~PeepMatch();
579 
580   // Insert info into the match-rule
581   void  add_instruction(int parent, int position, const char *name, int input);
582 
583   // Access info about instructions in the peep-match rule
584   int   max_position();
585   const char *instruction_name(int position);
586   // Iterate through all info on matched instructions
587   void  reset();
588   void  next_instruction(int &parent, int &position, const char* &name, int &input);
589   // 'true' if current position in iteration is a placeholder, not matched.
590   bool  is_placeholder();
591 
592   void dump();
593   void output(FILE *fp);
594 };
595 
596 
597 class PeepConstraint : public Form {
598 private:
599   PeepConstraint *_next;           // Additional constraints ANDed together
600 
601 public:
602   const int   _left_inst;
603   const char* _left_op;
604   const char* _relation;
605   const int   _right_inst;
606   const char* _right_op;
607 
608 public:
609   // Public Methods
610   PeepConstraint(int left_inst,  char* left_op, char* relation,
611                  int right_inst, char* right_op);
612   ~PeepConstraint();
613 
614   // Check if constraints use instruction at position
615   bool constrains_instruction(int position);
616 
617   // Add another constraint
618   void append(PeepConstraint *next_peep_constraint);
619   // Access the next constraint in the list
620   PeepConstraint *next();
621 
622   void dump();
623   void output(FILE *fp);
624 };
625 
626 
627 class PeepReplace : public Form {
628 private:
629   char *_rule;
630   NameList _instruction;
631   NameList _operand_inst_num;
632   NameList _operand_op_name;
633 
634 public:
635 
636   // Public Methods
637   PeepReplace(char *rule);
638   ~PeepReplace();
639 
640   // Add contents of peepreplace
641   void  add_instruction(char *root);
642   void  add_operand( int inst_num, char *inst_operand );
643 
644   // Access contents of peepreplace
645   void  reset();
646   void  next_instruction(const char * &root);
647   void  next_operand(int &inst_num, const char * &inst_operand );
648 
649   // Utilities
650   void dump();
651   void output(FILE *fp);
652 };
653 
654 
655 class PeepChild : public Form {
656 public:
657   const int   _inst_num;         // Number of instruction (-1 if only named)
658   const char *_inst_op;          // Instruction's operand, NULL if number == -1
659   const char *_inst_name;        // Name of the instruction
660 
661 public:
PeepChild(char * inst_name)662   PeepChild(char *inst_name)
663     : _inst_num(-1), _inst_op(NULL), _inst_name(inst_name) {};
PeepChild(int inst_num,char * inst_op,char * inst_name)664   PeepChild(int inst_num, char *inst_op, char *inst_name)
665     : _inst_num(inst_num), _inst_op(inst_op), _inst_name(inst_name) {};
666   ~PeepChild();
667 
use_leaf_operand()668   bool  use_leaf_operand()        { return _inst_num != -1; };
generate_an_instruction()669   bool  generate_an_instruction() { return _inst_num == -1; }
670 
671   void dump();
672   void output(FILE *fp);
673 };
674 
675 #endif // SHARE_ADLC_FORMSOPT_HPP
676