1 /*
2  * Copyright (c) 1997, 2010, 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_VM_ADLC_ARCHDESC_HPP
26 #define SHARE_VM_ADLC_ARCHDESC_HPP
27 
28 // Definitions for Error Flags
29 #define  WARN   0
30 #define  SYNERR 1
31 #define  SEMERR 2
32 #define  INTERNAL_ERR 3
33 
34 // Minimal declarations for include files
35 class  OutputMap;
36 class  ProductionState;
37 class  Expr;
38 
39 // STRUCTURE FOR HANDLING INPUT AND OUTPUT FILES
40 typedef BufferedFile ADLFILE;
41 
42 //---------------------------ChainList-----------------------------------------
43 class ChainList {
44   NameList _name;
45   NameList _cost;
46   NameList _rule;
47 
48 public:
49   void insert(const char *name, const char *cost, const char *rule);
50   bool search(const char *name);
51 
52   void reset();
53   bool iter(const char * &name, const char * &cost, const char * &rule);
54 
55   void dump();
56   void output(FILE *fp);
57 
58   ChainList();
59   ~ChainList();
60 };
61 
62 //---------------------------MatchList-----------------------------------------
63 class MatchList {
64 private:
65   MatchList  *_next;
66   Predicate  *_pred;          // Predicate which applies to this match rule
67   const char *_cost;
68 
69 public:
70   const char *_opcode;
71   const char *_resultStr;
72   const char *_lchild;
73   const char *_rchild;
74 
MatchList(MatchList * nxt,Predicate * prd)75   MatchList(MatchList *nxt, Predicate *prd): _next(nxt), _pred(prd), _cost(NULL){
76     _resultStr = _lchild = _rchild = _opcode = NULL; }
77 
MatchList(MatchList * nxt,Predicate * prd,const char * cost,const char * opcode,const char * resultStr,const char * lchild,const char * rchild)78   MatchList(MatchList *nxt, Predicate *prd, const char *cost,
79             const char *opcode, const char *resultStr, const char *lchild,
80             const char *rchild)
81     : _next(nxt), _pred(prd), _cost(cost), _opcode(opcode),
82       _resultStr(resultStr), _lchild(lchild), _rchild(rchild) { }
83 
get_next(void)84   MatchList  *get_next(void)  { return _next; }
get_pred(void)85   char       *get_pred(void)  { return (_pred?_pred->_pred:NULL); }
get_pred_obj(void)86   Predicate  *get_pred_obj(void)  { return _pred; }
get_cost(void)87   const char *get_cost(void) { return _cost == NULL ? "0" :_cost; }
88   bool        search(const char *opc, const char *res, const char *lch,
89                     const char *rch, Predicate *pr);
90 
91   void        dump();
92   void        output(FILE *fp);
93 };
94 
95 //---------------------------ArchDesc------------------------------------------
96 class ArchDesc {
97 private:
98   FormDict      _globalNames;        // Global names
99   Dict          _idealIndex;         // Map ideal names to index in enumeration
100   ExprDict      _globalDefs;         // Global definitions, #defines
101   int           _internalOpCounter;  // Internal Operand Counter
102 
103   FormList      _header;             // List of Source Code Forms for hpp file
104   FormList      _pre_header;         // ditto for the very top of the hpp file
105   FormList      _source;             // List of Source Code Forms for output
106   FormList      _instructions;       // List of Instruction Forms for output
107   FormList      _machnodes;          // List of Node Classes (special for pipelining)
108   FormList      _operands;           // List of Operand Forms for output
109   FormList      _opclass;            // List of Operand Class Forms for output
110   FormList      _attributes;         // List of Attribute Forms for parsing
111   RegisterForm *_register;           // Only one Register Form allowed
112   FrameForm    *_frame;              // Describe stack-frame layout
113   EncodeForm   *_encode;             // Only one Encode Form allowed
114   PipelineForm *_pipeline;           // Pipeline Form for output
115 
116   bool _has_match_rule[_last_opcode];  // found AD rule for ideal node in <arch>.ad
117 
118   MatchList    *_mlistab[_last_opcode]; // Array of MatchLists
119 
120   // The Architecture Description identifies which user-defined operand can be used
121   // to access [stack_pointer + offset]
122   OperandForm  *_cisc_spill_operand;
123 
124   // If a Call node uses $constanttablebase, it gets MachConstantBaseNode
125   // by the matcher and the matcher will modify the jvms. If so, jvm states
126   // always have to be cloned when a node is cloned.  Adlc generates
127   // Compile::needs_clone_jvms() accordingly.
128   bool _needs_clone_jvms;
129 
130   // Methods for outputting the DFA
131   void gen_match(FILE *fp, MatchList &mlist, ProductionState &status, Dict &operands_chained_from);
132   void chain_rule(FILE *fp, const char *indent, const char *ideal,
133                   const Expr *icost, const char *irule,
134                   Dict &operands_chained_from, ProductionState &status);
135   void expand_opclass(FILE *fp, const char *indent, const Expr *cost,
136                       const char *result_type, ProductionState &status);
137   Expr *calc_cost(FILE *fp, const char *spaces, MatchList &mList, ProductionState &status);
138   void prune_matchlist(Dict &minimize, MatchList &mlist);
139 
140   // Helper function that outputs code to generate an instruction in MachNodeGenerator
141   void buildMachNode(FILE *fp_cpp, InstructForm *inst, const char *indent);
142 
143 public:
144   ArchDesc();
145   ~ArchDesc();
146 
147   // Option flags which control miscellaneous behaviors throughout the code
148   int   _TotalLines;                    // Line Counter
149   int   _no_output;                     // Flag to disable output of DFA, etc.
150   int   _quiet_mode;                    // Do not output banner messages, etc.
151   int   _disable_warnings;              // Do not output warning messages
152   int   _dfa_debug;                     // Debug Flag for generated DFA
153   int   _dfa_small;                     // Debug Flag for generated DFA
154   int   _adl_debug;                     // Debug Flag for ADLC
155   int   _adlocation_debug;              // Debug Flag to use ad file locations
156   bool  _cisc_spill_debug;              // Debug Flag to see cisc-spill-instructions
157   bool  _short_branch_debug;            // Debug Flag to see short branch instructions
158 
159   // Error/Warning Counts
160   int _syntax_errs;                  // Count of syntax errors
161   int _semantic_errs;                // Count of semantic errors
162   int _warnings;                     // Count warnings
163   int _internal_errs;                // Count of internal errors
164 
165   // Accessor for private data.
has_match_rule(int opc,const bool b)166   void has_match_rule(int opc, const bool b) { _has_match_rule[opc] = b; }
167 
168   // I/O Files
169   ADLFILE  _ADL_file;          // Input Architecture Description File
170   // Machine dependent files, built from architecture definition
171   ADLFILE  _DFA_file;          // File for definition of Matcher::DFA
172   ADLFILE  _HPP_file;          // File for ArchNode class declarations
173   ADLFILE  _CPP_file;          // File for ArchNode class defintions
174   ADLFILE  _CPP_CLONE_file;    // File for MachNode/Oper clone defintions
175   ADLFILE  _CPP_EXPAND_file;   // File for MachNode expand methods
176   ADLFILE  _CPP_FORMAT_file;   // File for MachNode/Oper format defintions
177   ADLFILE  _CPP_GEN_file;      // File for MachNode/Oper generator methods
178   ADLFILE  _CPP_MISC_file;     // File for miscellaneous MachNode/Oper tables & methods
179   ADLFILE  _CPP_PEEPHOLE_file; // File for MachNode peephole methods
180   ADLFILE  _CPP_PIPELINE_file; // File for MachNode pipeline defintions
181   ADLFILE  _VM_file;           // File for constants needed in VM code
182   ADLFILE  _bug_file;          // DFA debugging file
183 
184   // I/O helper methods
185   int  open_file(bool required, ADLFILE & adf, const char *action);
186   void close_file(int delete_out, ADLFILE & adf);
187   int  open_files(void);
188   void close_files(int delete_out);
189 
190   Dict _chainRules;            // Maps user operand names to ChainRules
191   Dict _internalOps;           // Maps match strings to internal operand names
192   NameList _internalOpNames;   // List internal operand names
193   Dict _internalMatch;         // Map internal name to its MatchNode
194 
195   NameList      _preproc_list; // Preprocessor flag names
196   FormDict      _preproc_table;// Preprocessor flag bindings
197   char* get_preproc_def(const char* flag);
198   void  set_preproc_def(const char* flag, const char* def);
199 
globalNames()200   FormDict& globalNames() {return _globalNames;} // map global names to forms
201   void initKeywords(FormDict& globals);  // Add keywords to global name table
202 
globalDefs()203   ExprDict& globalDefs()  {return _globalDefs;}  // map global names to expressions
204 
205   OperandForm *constructOperand(const char *ident, bool ideal_only);
206   void initBaseOpTypes();            // Import predefined base types.
207 
208   void addForm(PreHeaderForm *ptr);  // Add objects to pre-header list
209   void addForm(HeaderForm *ptr);     // Add objects to header list
210   void addForm(SourceForm *ptr);     // Add objects to source list
211   void addForm(EncodeForm *ptr);     // Add objects to encode list
212   void addForm(InstructForm *ptr);   // Add objects to the instruct list
213   void addForm(OperandForm *ptr);    // Add objects to the operand list
214   void addForm(OpClassForm *ptr);    // Add objects to the opclasss list
215   void addForm(AttributeForm *ptr);  // Add objects to the attributes list
216   void addForm(RegisterForm *ptr);   // Add objects to the register list
217   void addForm(FrameForm    *ptr);   // Add objects to the frame list
218   void addForm(PipelineForm *ptr);   // Add objects to the pipeline list
219   void addForm(MachNodeForm *ptr);   // Add objects to the machnode list
220 
221   int  operandFormCount();           // Count number of OperandForms defined
222   int  opclassFormCount();           // Count number of OpClassForms defined
223   int  instructFormCount();          // Count number of InstructForms defined
224 
getForm(EncodeForm ** ptr)225   inline void getForm(EncodeForm **ptr)     { *ptr = _encode; }
226 
227   bool verify();
228   void dump();
229 
230   // Helper utility that gets MatchList components from inside MatchRule
231   void check_optype(MatchRule *mrule);
232   void build_chain_rule(OperandForm *oper);
233   void add_chain_rule_entry(const char *src, const char *cost,
234                             const char *result);
235   const char *getMatchListIndex(MatchRule &mrule);
236   void generateMatchLists();         // Build MatchList array and populate it
237   void inspectOperands();            // Build MatchLists for all operands
238   void inspectOpClasses();           // Build MatchLists for all operands
239   void inspectInstructions();        // Build MatchLists for all operands
240   void buildDFA(FILE *fp);           // Driver for constructing the DFA
241   void gen_dfa_state_body(FILE *fp, Dict &minmize, ProductionState &status, Dict &chained, int i);    // Driver for constructing the DFA state bodies
242 
243   // Helper utilities to generate reduction maps for internal operands
244   const char *reduceLeft (char *internalName);
245   const char *reduceRight(char *internalName);
246 
247   // Build enumerations, (1) dense operand index, (2) operands and opcodes
248   const char *machOperEnum(const char *opName);       // create dense index names using static function
249   static const char *getMachOperEnum(const char *opName);// create dense index name
250   void buildMachOperEnum(FILE *fp_hpp);// dense enumeration for operands
251   void buildMachOpcodesEnum(FILE *fp_hpp);// enumeration for MachOpers & MachNodes
252 
253   // Helper utilities to generate Register Masks
get_registers()254   RegisterForm *get_registers() { return _register; }
255   const char *reg_mask(OperandForm  &opForm);
256   const char *reg_mask(InstructForm &instForm);
257   const char *reg_class_to_reg_mask(const char *reg_class);
258   char *stack_or_reg_mask(OperandForm  &opForm);  // name of cisc_spillable version
259   // This register class should also generate a stack_or_reg_mask
260   void  set_stack_or_reg(const char *reg_class_name); // for cisc-spillable reg classes
261   // Generate an enumeration of register mask names and the RegMask objects.
262   void  declare_register_masks(FILE *fp_cpp);
263   void  build_register_masks(FILE *fp_cpp);
264   // Generate enumeration of machine register numbers
265   void  buildMachRegisterNumbers(FILE *fp_hpp);
266   // Generate enumeration of machine register encodings
267   void  buildMachRegisterEncodes(FILE *fp_hpp);
268   // Generate Regsiter Size Array
269   void  declareRegSizes(FILE *fp_hpp);
270   // Generate Pipeline Class information
271   void declare_pipe_classes(FILE *fp_hpp);
272   // Generate Pipeline definitions
273   void build_pipeline_enums(FILE *fp_cpp);
274   // Generate Pipeline Class information
275   void build_pipe_classes(FILE *fp_cpp);
276 
277   // Declare and define mappings from rules to result and input types
278   void build_map(OutputMap &map);
279   void buildReduceMaps(FILE *fp_hpp, FILE *fp_cpp);
280   // build flags for signaling that our machine needs this instruction cloned
281   void buildMustCloneMap(FILE *fp_hpp, FILE *fp_cpp);
282 
283   // output SUN copyright info
284   void addSunCopyright(char* legal, int size, FILE *fp);
285   // output the start of an include guard.
286   void addIncludeGuardStart(ADLFILE &adlfile, const char* guardString);
287   // output the end of an include guard.
288   void addIncludeGuardEnd(ADLFILE &adlfile, const char* guardString);
289   // output the #include line for this file.
290   void addInclude(ADLFILE &adlfile, const char* fileName);
291   void addInclude(ADLFILE &adlfile, const char* includeDir, const char* fileName);
292   // Output C preprocessor code to verify the backend compilation environment.
293   void addPreprocessorChecks(FILE *fp);
294   // Output C source and header (source_hpp) blocks.
295   void addPreHeaderBlocks(FILE *fp_hpp);
296   void addHeaderBlocks(FILE *fp_hpp);
297   void addSourceBlocks(FILE *fp_cpp);
298   void generate_needs_clone_jvms(FILE *fp_cpp);
299   void generate_adlc_verification(FILE *fp_cpp);
300 
301   // output declaration of class State
302   void defineStateClass(FILE *fp);
303 
304   // Generator for MachOper objects given integer type
305   void buildMachOperGenerator(FILE *fp_cpp);
306   // Generator for MachNode objects given integer type
307   void buildMachNodeGenerator(FILE *fp_cpp);
308 
309   // Generator for Expand methods for instructions with expand rules
310   void defineExpand      (FILE *fp, InstructForm *node);
311   // Generator for Peephole methods for instructions with peephole rules
312   void definePeephole    (FILE *fp, InstructForm *node);
313   // Generator for Size methods for instructions
314   void defineSize        (FILE *fp, InstructForm &node);
315 
316 public:
317   // Generator for EvalConstantValue methods for instructions
318   void defineEvalConstant(FILE *fp, InstructForm &node);
319   // Generator for Emit methods for instructions
320   void defineEmit        (FILE *fp, InstructForm &node);
321   // Generator for postalloc_expand methods for instructions.
322   void define_postalloc_expand(FILE *fp, InstructForm &node);
323 
324   // Define a MachOper encode method
325   void define_oper_interface(FILE *fp, OperandForm &oper, FormDict &globals,
326                              const char *name, const char *encoding);
327 
328   // Methods to construct the MachNode class hierarchy
329   // Return the type signature for the ideal operation
330   const char *getIdealType(const char *idealOp);
331   // Declare and define the classes derived from MachOper and MachNode
332   void declareClasses(FILE *fp_hpp);
333   void defineClasses(FILE *fp_cpp);
334 
335   // Emit an ADLC message
336   void internal_err( const char *fmt, ...);
337   void syntax_err  ( int lineno, const char *fmt, ...);
338   int  emit_msg(int quiet, int flag, int linenum, const char *fmt,
339        va_list args);
340 
341   // Generator for has_match_rule methods
342   void buildInstructMatchCheck(FILE *fp_cpp) const;
343 
344   // Generator for Frame Methods
345   void buildFrameMethods(FILE *fp_cpp);
346 
347   // Generate CISC_spilling oracle and MachNode::cisc_spill() methods
348   void          build_cisc_spill_instructions(FILE *fp_hpp, FILE *fp_cpp);
349   void          identify_cisc_spill_instructions();
350   void          identify_short_branches();
351   void          identify_unique_operands();
set_cisc_spill_operand(OperandForm * opForm)352   void          set_cisc_spill_operand(OperandForm *opForm) { _cisc_spill_operand = opForm; }
cisc_spill_operand()353   OperandForm  *cisc_spill_operand() { return _cisc_spill_operand; }
can_cisc_spill()354   bool          can_cisc_spill() { return _cisc_spill_operand != NULL; }
355 
356 
357 protected:
358   // build MatchList from MatchRule
359   void buildMatchList(MatchRule *mrule, const char *resultStr,
360                       const char *rootOp, Predicate *pred, const char *cost);
361 
362   void buildMList(MatchNode *node, const char *rootOp, const char *resultOp,
363                   Predicate *pred, const char *cost);
364 
365   friend class ADLParser;
366 
367 };
368 
369 
370 // -------------------------------- maps ------------------------------------
371 
372 // Base class for generating a mapping from rule number to value.
373 // Used with ArchDesc::build_map() for all maps except "enum MachOperands"
374 // A derived class defines the appropriate output for a specific mapping.
375 class OutputMap {
376 protected:
377   FILE       *_hpp;
378   FILE       *_cpp;
379   FormDict   &_globals;
380   ArchDesc   &_AD;
381   const char *_name;
382 public:
OutputMap(FILE * decl_file,FILE * def_file,FormDict & globals,ArchDesc & AD,const char * name)383   OutputMap (FILE *decl_file, FILE *def_file, FormDict &globals, ArchDesc &AD, const char *name)
384     : _hpp(decl_file), _cpp(def_file), _globals(globals), _AD(AD), _name(name) {};
385   // Access files used by this routine
decl_file()386   FILE        *decl_file() { return _hpp; }
def_file()387   FILE        *def_file()  { return _cpp; }
388   // Positions in iteration that derived class will be told about
389   enum position { BEGIN_OPERANDS,
390                   BEGIN_OPCLASSES,
391                   BEGIN_INTERNALS,
392                   BEGIN_INSTRUCTIONS,
393                   BEGIN_INST_CHAIN_RULES,
394                   END_INST_CHAIN_RULES,
395                   BEGIN_REMATERIALIZE,
396                   END_REMATERIALIZE,
397                   END_INSTRUCTIONS
398   };
399   // Output routines specific to the derived class
declaration()400   virtual void declaration() {}
definition()401   virtual void definition()  {}
closing()402   virtual void closing()     {  fprintf(_cpp, "};\n"); }
map(OperandForm & oper)403   virtual void map(OperandForm  &oper) { }
map(OpClassForm & opc)404   virtual void map(OpClassForm  &opc)  { }
map(char * internal_name)405   virtual void map(char         *internal_name) { }
406   // Allow enum-MachOperands to turn-off instructions
do_instructions()407   virtual bool do_instructions()       { return true; }
map(InstructForm & inst)408   virtual void map(InstructForm &inst) { }
409   // Allow derived class to output name and position specific info
record_position(OutputMap::position place,int index)410   virtual void record_position(OutputMap::position place, int index) {}
411 };
412 
413 #endif // SHARE_VM_ADLC_ARCHDESC_HPP
414