xref: /freebsd/sys/contrib/dev/acpica/compiler/aslopt.c (revision 722b16673c40aedf280895f2f2f676bb494518d7)
1 /******************************************************************************
2  *
3  * Module Name: aslopt- Compiler optimizations
4  *
5  *****************************************************************************/
6 
7 /******************************************************************************
8  *
9  * 1. Copyright Notice
10  *
11  * Some or all of this work - Copyright (c) 1999 - 2023, Intel Corp.
12  * All rights reserved.
13  *
14  * 2. License
15  *
16  * 2.1. This is your license from Intel Corp. under its intellectual property
17  * rights. You may have additional license terms from the party that provided
18  * you this software, covering your right to use that party's intellectual
19  * property rights.
20  *
21  * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
22  * copy of the source code appearing in this file ("Covered Code") an
23  * irrevocable, perpetual, worldwide license under Intel's copyrights in the
24  * base code distributed originally by Intel ("Original Intel Code") to copy,
25  * make derivatives, distribute, use and display any portion of the Covered
26  * Code in any form, with the right to sublicense such rights; and
27  *
28  * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
29  * license (with the right to sublicense), under only those claims of Intel
30  * patents that are infringed by the Original Intel Code, to make, use, sell,
31  * offer to sell, and import the Covered Code and derivative works thereof
32  * solely to the minimum extent necessary to exercise the above copyright
33  * license, and in no event shall the patent license extend to any additions
34  * to or modifications of the Original Intel Code. No other license or right
35  * is granted directly or by implication, estoppel or otherwise;
36  *
37  * The above copyright and patent license is granted only if the following
38  * conditions are met:
39  *
40  * 3. Conditions
41  *
42  * 3.1. Redistribution of Source with Rights to Further Distribute Source.
43  * Redistribution of source code of any substantial portion of the Covered
44  * Code or modification with rights to further distribute source must include
45  * the above Copyright Notice, the above License, this list of Conditions,
46  * and the following Disclaimer and Export Compliance provision. In addition,
47  * Licensee must cause all Covered Code to which Licensee contributes to
48  * contain a file documenting the changes Licensee made to create that Covered
49  * Code and the date of any change. Licensee must include in that file the
50  * documentation of any changes made by any predecessor Licensee. Licensee
51  * must include a prominent statement that the modification is derived,
52  * directly or indirectly, from Original Intel Code.
53  *
54  * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
55  * Redistribution of source code of any substantial portion of the Covered
56  * Code or modification without rights to further distribute source must
57  * include the following Disclaimer and Export Compliance provision in the
58  * documentation and/or other materials provided with distribution. In
59  * addition, Licensee may not authorize further sublicense of source of any
60  * portion of the Covered Code, and must include terms to the effect that the
61  * license from Licensee to its licensee is limited to the intellectual
62  * property embodied in the software Licensee provides to its licensee, and
63  * not to intellectual property embodied in modifications its licensee may
64  * make.
65  *
66  * 3.3. Redistribution of Executable. Redistribution in executable form of any
67  * substantial portion of the Covered Code or modification must reproduce the
68  * above Copyright Notice, and the following Disclaimer and Export Compliance
69  * provision in the documentation and/or other materials provided with the
70  * distribution.
71  *
72  * 3.4. Intel retains all right, title, and interest in and to the Original
73  * Intel Code.
74  *
75  * 3.5. Neither the name Intel nor any other trademark owned or controlled by
76  * Intel shall be used in advertising or otherwise to promote the sale, use or
77  * other dealings in products derived from or relating to the Covered Code
78  * without prior written authorization from Intel.
79  *
80  * 4. Disclaimer and Export Compliance
81  *
82  * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
83  * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
84  * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
85  * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
86  * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
87  * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
88  * PARTICULAR PURPOSE.
89  *
90  * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
91  * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
92  * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
93  * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
94  * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
95  * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
96  * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
97  * LIMITED REMEDY.
98  *
99  * 4.3. Licensee shall not export, either directly or indirectly, any of this
100  * software or system incorporating such software without first obtaining any
101  * required license or other approval from the U. S. Department of Commerce or
102  * any other agency or department of the United States Government. In the
103  * event Licensee exports any such software from the United States or
104  * re-exports any such software from a foreign destination, Licensee shall
105  * ensure that the distribution and export/re-export of the software is in
106  * compliance with all laws, regulations, orders, or other restrictions of the
107  * U.S. Export Administration Regulations. Licensee agrees that neither it nor
108  * any of its subsidiaries will export/re-export any technical data, process,
109  * software, or service, directly or indirectly, to any country for which the
110  * United States government or any agency thereof requires an export license,
111  * other governmental approval, or letter of assurance, without first obtaining
112  * such license, approval or letter.
113  *
114  *****************************************************************************
115  *
116  * Alternatively, you may choose to be licensed under the terms of the
117  * following license:
118  *
119  * Redistribution and use in source and binary forms, with or without
120  * modification, are permitted provided that the following conditions
121  * are met:
122  * 1. Redistributions of source code must retain the above copyright
123  *    notice, this list of conditions, and the following disclaimer,
124  *    without modification.
125  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
126  *    substantially similar to the "NO WARRANTY" disclaimer below
127  *    ("Disclaimer") and any redistribution must be conditioned upon
128  *    including a substantially similar Disclaimer requirement for further
129  *    binary redistribution.
130  * 3. Neither the names of the above-listed copyright holders nor the names
131  *    of any contributors may be used to endorse or promote products derived
132  *    from this software without specific prior written permission.
133  *
134  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
135  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
136  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
137  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
138  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
139  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
140  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
141  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
142  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
143  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
144  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
145  *
146  * Alternatively, you may choose to be licensed under the terms of the
147  * GNU General Public License ("GPL") version 2 as published by the Free
148  * Software Foundation.
149  *
150  *****************************************************************************/
151 
152 #include <contrib/dev/acpica/compiler/aslcompiler.h>
153 #include "aslcompiler.y.h"
154 
155 #include <contrib/dev/acpica/include/acparser.h>
156 #include <contrib/dev/acpica/include/amlcode.h>
157 #include <contrib/dev/acpica/include/acnamesp.h>
158 
159 
160 #define _COMPONENT          ACPI_COMPILER
161         ACPI_MODULE_NAME    ("aslopt")
162 
163 
164 static UINT32               OptTotal = 0;
165 
166 /* Local prototypes */
167 
168 static ACPI_STATUS
169 OptSearchToRoot (
170     ACPI_PARSE_OBJECT       *Op,
171     ACPI_WALK_STATE         *WalkState,
172     ACPI_NAMESPACE_NODE     *CurrentNode,
173     ACPI_NAMESPACE_NODE     *TargetNode,
174     ACPI_BUFFER             *TargetPath,
175     char                    **NewPath);
176 
177 static ACPI_STATUS
178 OptBuildShortestPath (
179     ACPI_PARSE_OBJECT       *Op,
180     ACPI_WALK_STATE         *WalkState,
181     ACPI_NAMESPACE_NODE     *CurrentNode,
182     ACPI_NAMESPACE_NODE     *TargetNode,
183     ACPI_BUFFER             *CurrentPath,
184     ACPI_BUFFER             *TargetPath,
185     ACPI_SIZE               AmlNameStringLength,
186     UINT8                   IsDeclaration,
187     char                    **ReturnNewPath);
188 
189 static ACPI_STATUS
190 OptOptimizeNameDeclaration (
191     ACPI_PARSE_OBJECT       *Op,
192     ACPI_WALK_STATE         *WalkState,
193     ACPI_NAMESPACE_NODE     *CurrentNode,
194     ACPI_NAMESPACE_NODE     *TargetNode,
195     char                    *AmlNameString,
196     char                    **NewPath);
197 
198 
199 /*******************************************************************************
200  *
201  * FUNCTION:    OptSearchToRoot
202  *
203  * PARAMETERS:  Op                  - Current parser op
204  *              WalkState           - Current state
205  *              CurrentNode         - Where we are in the namespace
206  *              TargetNode          - Node to which we are referring
207  *              TargetPath          - External full path to the target node
208  *              NewPath             - Where the optimized path is returned
209  *
210  * RETURN:      Status
211  *
212  * DESCRIPTION: Attempt to optimize a reference to a single 4-character ACPI
213  *              name utilizing the search-to-root name resolution algorithm
214  *              that is used by AML interpreters.
215  *
216  ******************************************************************************/
217 
218 static ACPI_STATUS
OptSearchToRoot(ACPI_PARSE_OBJECT * Op,ACPI_WALK_STATE * WalkState,ACPI_NAMESPACE_NODE * CurrentNode,ACPI_NAMESPACE_NODE * TargetNode,ACPI_BUFFER * TargetPath,char ** NewPath)219 OptSearchToRoot (
220     ACPI_PARSE_OBJECT       *Op,
221     ACPI_WALK_STATE         *WalkState,
222     ACPI_NAMESPACE_NODE     *CurrentNode,
223     ACPI_NAMESPACE_NODE     *TargetNode,
224     ACPI_BUFFER             *TargetPath,
225     char                    **NewPath)
226 {
227     ACPI_NAMESPACE_NODE     *Node;
228     ACPI_GENERIC_STATE      ScopeInfo;
229     ACPI_STATUS             Status;
230     char                    *Path;
231 
232 
233     ACPI_FUNCTION_NAME (OptSearchToRoot);
234 
235 
236     /*
237      * Check if search-to-root can be utilized. Use the last NameSeg of
238      * the NamePath and 1) See if can be found and 2) If found, make
239      * sure that it is the same node that we want. If there is another
240      * name in the search path before the one we want, the nodes will
241      * not match, and we cannot use this optimization.
242      */
243     Path = &(((char *) TargetPath->Pointer)[
244         TargetPath->Length - ACPI_NAMESEG_SIZE]);
245     ScopeInfo.Scope.Node = CurrentNode;
246 
247     /* Lookup the NameSeg using SEARCH_PARENT (search-to-root) */
248 
249     Status = AcpiNsLookup (&ScopeInfo, Path, ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
250         ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE,
251         WalkState, &(Node));
252     if (ACPI_FAILURE (Status))
253     {
254         return (Status);
255     }
256 
257     /*
258      * We found the name, but we must check to make sure that the node
259      * matches. Otherwise, there is another identical name in the search
260      * path that precludes the use of this optimization.
261      */
262     if (Node != TargetNode)
263     {
264         /*
265          * This means that another object with the same name was found first,
266          * and we cannot use this optimization.
267          */
268         return (AE_NOT_FOUND);
269     }
270 
271     /* Found the node, we can use this optimization */
272 
273     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
274         "NAMESEG:   %-24s", Path));
275 
276     /* We must allocate a new string for the name (TargetPath gets deleted) */
277 
278     *NewPath = UtLocalCacheCalloc (ACPI_NAMESEG_SIZE + 1);
279     strcpy (*NewPath, Path);
280 
281     if (strncmp (*NewPath, "_T_", 3))
282     {
283         AslError (ASL_OPTIMIZATION, ASL_MSG_SINGLE_NAME_OPTIMIZATION,
284             Op, *NewPath);
285     }
286 
287     return (AE_OK);
288 }
289 
290 
291 /*******************************************************************************
292  *
293  * FUNCTION:    OptBuildShortestPath
294  *
295  * PARAMETERS:  Op                  - Current parser op
296  *              WalkState           - Current state
297  *              CurrentNode         - Where we are in the namespace
298  *              TargetNode          - Node to which we are referring
299  *              CurrentPath         - External full path to the current node
300  *              TargetPath          - External full path to the target node
301  *              AmlNameStringLength - Length of the original namepath
302  *              IsDeclaration       - TRUE for declaration, FALSE for reference
303  *              ReturnNewPath       - Where the optimized path is returned
304  *
305  * RETURN:      Status
306  *
307  * DESCRIPTION: Build an optimal NamePath using carats
308  *
309  ******************************************************************************/
310 
311 static ACPI_STATUS
OptBuildShortestPath(ACPI_PARSE_OBJECT * Op,ACPI_WALK_STATE * WalkState,ACPI_NAMESPACE_NODE * CurrentNode,ACPI_NAMESPACE_NODE * TargetNode,ACPI_BUFFER * CurrentPath,ACPI_BUFFER * TargetPath,ACPI_SIZE AmlNameStringLength,UINT8 IsDeclaration,char ** ReturnNewPath)312 OptBuildShortestPath (
313     ACPI_PARSE_OBJECT       *Op,
314     ACPI_WALK_STATE         *WalkState,
315     ACPI_NAMESPACE_NODE     *CurrentNode,
316     ACPI_NAMESPACE_NODE     *TargetNode,
317     ACPI_BUFFER             *CurrentPath,
318     ACPI_BUFFER             *TargetPath,
319     ACPI_SIZE               AmlNameStringLength,
320     UINT8                   IsDeclaration,
321     char                    **ReturnNewPath)
322 {
323     UINT32                  NumCommonSegments;
324     UINT32                  MaxCommonSegments;
325     UINT32                  Index;
326     UINT32                  NumCarats;
327     UINT32                  i;
328     char                    *NewPathInternal;
329     char                    *NewPathExternal;
330     ACPI_NAMESPACE_NODE     *Node;
331     ACPI_GENERIC_STATE      ScopeInfo;
332     ACPI_STATUS             Status;
333     BOOLEAN                 SubPath = FALSE;
334 
335 
336     ACPI_FUNCTION_NAME (OptBuildShortestPath);
337 
338 
339     ScopeInfo.Scope.Node = CurrentNode;
340 
341     /*
342      * Determine the maximum number of NameSegs that the Target and Current paths
343      * can possibly have in common. (To optimize, we have to have at least 1)
344      *
345      * Note: The external NamePath string lengths are always a multiple of 5
346      * (ACPI_NAMESEG_SIZE + separator)
347      */
348     MaxCommonSegments = TargetPath->Length / ACPI_PATH_SEGMENT_LENGTH;
349     if (CurrentPath->Length < TargetPath->Length)
350     {
351         MaxCommonSegments = CurrentPath->Length / ACPI_PATH_SEGMENT_LENGTH;
352     }
353 
354     /*
355      * Determine how many NameSegs the two paths have in common.
356      * (Starting from the root)
357      */
358     for (NumCommonSegments = 0;
359          NumCommonSegments < MaxCommonSegments;
360          NumCommonSegments++)
361     {
362         /* Compare two single NameSegs */
363 
364         Index = (NumCommonSegments * ACPI_PATH_SEGMENT_LENGTH) + 1;
365 
366         if (!ACPI_COMPARE_NAMESEG (
367             &(ACPI_CAST_PTR (char, TargetPath->Pointer)) [Index],
368             &(ACPI_CAST_PTR (char, CurrentPath->Pointer)) [Index]))
369         {
370             /* Mismatch */
371 
372             break;
373         }
374     }
375 
376     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " COMMON: %u",
377         NumCommonSegments));
378 
379     /* There must be at least 1 common NameSeg in order to optimize */
380 
381     if (NumCommonSegments == 0)
382     {
383         return (AE_NOT_FOUND);
384     }
385 
386     if (NumCommonSegments == MaxCommonSegments)
387     {
388         if (CurrentPath->Length == TargetPath->Length)
389         {
390             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " SAME PATH"));
391             return (AE_NOT_FOUND);
392         }
393         else
394         {
395             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " SUBPATH"));
396             SubPath = TRUE;
397         }
398     }
399 
400     /* Determine how many prefix Carats are required */
401 
402     NumCarats = (CurrentPath->Length / ACPI_PATH_SEGMENT_LENGTH) -
403         NumCommonSegments;
404 
405     /*
406      * Construct a new target string
407      */
408     NewPathExternal =
409         UtLocalCacheCalloc (TargetPath->Length + NumCarats + 1);
410 
411     /* Insert the Carats into the Target string */
412 
413     for (i = 0; i < NumCarats; i++)
414     {
415         NewPathExternal[i] = AML_PARENT_PREFIX;
416     }
417 
418     /*
419      * Copy only the necessary (optimal) segments from the original
420      * target string
421      */
422     Index = (NumCommonSegments * ACPI_PATH_SEGMENT_LENGTH) + 1;
423 
424     /* Special handling for exact subpath in a name declaration */
425 
426     if (IsDeclaration && SubPath &&
427         (CurrentPath->Length > TargetPath->Length))
428     {
429         /*
430          * The current path is longer than the target, and the target is a
431          * subpath of the current path. We must include one more NameSeg of
432          * the target path
433          */
434         Index -= ACPI_PATH_SEGMENT_LENGTH;
435 
436         /* Special handling for Scope() operator */
437 
438         if (Op->Asl.AmlOpcode == AML_SCOPE_OP)
439         {
440             NewPathExternal[i] = AML_PARENT_PREFIX;
441             i++;
442             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "(EXTRA ^)"));
443         }
444     }
445 
446     /* Make sure we haven't gone off the end of the target path */
447 
448     if (Index > TargetPath->Length)
449     {
450         Index = TargetPath->Length;
451     }
452 
453     strcpy (&NewPathExternal[i],
454         &(ACPI_CAST_PTR (char, TargetPath->Pointer))[Index]);
455     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " %-24s", NewPathExternal));
456 
457     /*
458      * Internalize the new target string and check it against the original
459      * string to make sure that this is in fact an optimization. If the
460      * original string is already optimal, there is no point in continuing.
461      */
462     Status = AcpiNsInternalizeName (NewPathExternal, &NewPathInternal);
463     if (ACPI_FAILURE (Status))
464     {
465         AslCoreSubsystemError (Op, Status, "Internalizing new NamePath",
466             ASL_NO_ABORT);
467         goto Cleanup;
468     }
469 
470     if (strlen (NewPathInternal) >= AmlNameStringLength)
471     {
472         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
473             " NOT SHORTER (New %u old %u)",
474             (UINT32) strlen (NewPathInternal),
475             (UINT32) AmlNameStringLength));
476 
477         ACPI_FREE (NewPathInternal);
478         Status = AE_NOT_FOUND;
479         goto Cleanup;
480     }
481 
482     /*
483      * Check to make sure that the optimization finds the node we are
484      * looking for. This is simply a sanity check on the new
485      * path that has been created.
486      */
487     Status = AcpiNsLookup (&ScopeInfo, NewPathInternal,
488         ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
489         ACPI_NS_DONT_OPEN_SCOPE, WalkState, &(Node));
490     if (ACPI_SUCCESS (Status))
491     {
492         /* Found the namepath, but make sure the node is correct */
493 
494         if (Node == TargetNode)
495         {
496             /* The lookup matched the node, accept this optimization */
497 
498             AslError (ASL_OPTIMIZATION, ASL_MSG_NAME_OPTIMIZATION,
499                 Op, NewPathExternal);
500             *ReturnNewPath = NewPathInternal;
501         }
502         else
503         {
504             /* Node is not correct, do not use this optimization */
505 
506             Status = AE_NOT_FOUND;
507             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ***** WRONG NODE"));
508             AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
509                 "Not using optimized name - found wrong node");
510         }
511     }
512     else
513     {
514         /* The lookup failed, we obviously cannot use this optimization */
515 
516         ACPI_FREE (NewPathInternal);
517 
518         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ***** NOT FOUND"));
519         AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
520             "Not using optimized name - did not find node");
521     }
522 
523 Cleanup:
524 
525     return (Status);
526 }
527 
528 
529 /*******************************************************************************
530  *
531  * FUNCTION:    OptOptimizeNameDeclaration
532  *
533  * PARAMETERS:  Op                  - Current parser op
534  *              WalkState           - Current state
535  *              CurrentNode         - Where we are in the namespace
536  *              AmlNameString       - Unoptimized namepath
537  *              NewPath             - Where the optimized path is returned
538  *
539  * RETURN:      Status. AE_OK If path is optimized
540  *
541  * DESCRIPTION: Perform a simple optimization of removing an extraneous
542  *              backslash prefix if we are already at the root scope.
543  *
544  ******************************************************************************/
545 
546 static ACPI_STATUS
OptOptimizeNameDeclaration(ACPI_PARSE_OBJECT * Op,ACPI_WALK_STATE * WalkState,ACPI_NAMESPACE_NODE * CurrentNode,ACPI_NAMESPACE_NODE * TargetNode,char * AmlNameString,char ** NewPath)547 OptOptimizeNameDeclaration (
548     ACPI_PARSE_OBJECT       *Op,
549     ACPI_WALK_STATE         *WalkState,
550     ACPI_NAMESPACE_NODE     *CurrentNode,
551     ACPI_NAMESPACE_NODE     *TargetNode,
552     char                    *AmlNameString,
553     char                    **NewPath)
554 {
555     ACPI_STATUS             Status;
556     char                    *NewPathExternal;
557     ACPI_NAMESPACE_NODE     *Node;
558 
559 
560     ACPI_FUNCTION_TRACE (OptOptimizeNameDeclaration);
561 
562 
563     if (((CurrentNode == AcpiGbl_RootNode) ||
564         (Op->Common.Parent->Asl.ParseOpcode == PARSEOP_DEFINITION_BLOCK)) &&
565             (ACPI_IS_ROOT_PREFIX (AmlNameString[0])))
566     {
567         /*
568          * The current scope is the root, and the namepath has a root prefix
569          * that is therefore extraneous. Remove it.
570          */
571         *NewPath = &AmlNameString[1];
572 
573         /* Debug output */
574 
575         Status = AcpiNsExternalizeName (ACPI_UINT32_MAX, *NewPath,
576             NULL, &NewPathExternal);
577         if (ACPI_FAILURE (Status))
578         {
579             AslCoreSubsystemError (Op, Status, "Externalizing NamePath",
580                 ASL_NO_ABORT);
581             return (Status);
582         }
583 
584         /*
585          * Check to make sure that the optimization finds the node we are
586          * looking for. This is simply a sanity check on the new
587          * path that has been created.
588          *
589          * We know that we are at the root, so NULL is used for the scope.
590          */
591         Status = AcpiNsLookup (NULL, *NewPath,
592             ACPI_TYPE_ANY, ACPI_IMODE_EXECUTE,
593             ACPI_NS_DONT_OPEN_SCOPE, WalkState, &(Node));
594         if (ACPI_SUCCESS (Status))
595         {
596             /* Found the namepath, but make sure the node is correct */
597 
598             if (Node == TargetNode)
599             {
600                 /* The lookup matched the node, accept this optimization */
601 
602                 AslError (ASL_OPTIMIZATION, ASL_MSG_NAME_OPTIMIZATION,
603                     Op, NewPathExternal);
604 
605                 ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
606                     "AT ROOT:   %-24s", NewPathExternal));
607             }
608             else
609             {
610                 /* Node is not correct, do not use this optimization */
611 
612                 Status = AE_NOT_FOUND;
613                 ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
614                     " ***** WRONG NODE"));
615                 AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
616                     "Not using optimized name - found wrong node");
617             }
618         }
619         else
620         {
621             /* The lookup failed, we obviously cannot use this optimization */
622 
623             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
624                 " ***** NOT FOUND"));
625             AslError (ASL_WARNING, ASL_MSG_COMPILER_INTERNAL, Op,
626                 "Not using optimized name - did not find node");
627         }
628 
629         ACPI_FREE (NewPathExternal);
630         return (Status);
631     }
632 
633     /* Could not optimize */
634 
635     return (AE_NOT_FOUND);
636 }
637 
638 
639 /*******************************************************************************
640  *
641  * FUNCTION:    OptOptimizeNamePath
642  *
643  * PARAMETERS:  Op                  - Current parser op
644  *              Flags               - Opcode info flags
645  *              WalkState           - Current state
646  *              AmlNameString       - Unoptimized namepath
647  *              TargetNode          - Node to which AmlNameString refers
648  *
649  * RETURN:      None. If path is optimized, the Op is updated with new path
650  *
651  * DESCRIPTION: Optimize a Named Declaration or Reference to the minimal length.
652  *              Must take into account both the current location in the
653  *              namespace and the actual reference path.
654  *
655  ******************************************************************************/
656 
657 void
OptOptimizeNamePath(ACPI_PARSE_OBJECT * Op,UINT32 Flags,ACPI_WALK_STATE * WalkState,char * AmlNameString,ACPI_NAMESPACE_NODE * TargetNode)658 OptOptimizeNamePath (
659     ACPI_PARSE_OBJECT       *Op,
660     UINT32                  Flags,
661     ACPI_WALK_STATE         *WalkState,
662     char                    *AmlNameString,
663     ACPI_NAMESPACE_NODE     *TargetNode)
664 {
665     ACPI_STATUS             Status;
666     ACPI_BUFFER             TargetPath;
667     ACPI_BUFFER             CurrentPath;
668     ACPI_SIZE               AmlNameStringLength;
669     ACPI_NAMESPACE_NODE     *CurrentNode;
670     char                    *ExternalNameString;
671     char                    *NewPath = NULL;
672     ACPI_SIZE               HowMuchShorter;
673     ACPI_PARSE_OBJECT       *NextOp;
674 
675 
676     ACPI_FUNCTION_TRACE (OptOptimizeNamePath);
677 
678 
679     /* This is an optional optimization */
680 
681     if (!AslGbl_ReferenceOptimizationFlag)
682     {
683         return_VOID;
684     }
685 
686     /* Various required items */
687 
688     if (!TargetNode || !WalkState || !AmlNameString || !Op->Common.Parent)
689     {
690         return_VOID;
691     }
692 
693     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
694         "PATH OPTIMIZE: Line %5d ParentOp [%12.12s] ThisOp [%12.12s] ",
695         Op->Asl.LogicalLineNumber,
696         AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode),
697         AcpiPsGetOpcodeName (Op->Common.AmlOpcode)));
698 
699     if (!(Flags & (AML_NAMED | AML_CREATE)))
700     {
701         if (Op->Asl.CompileFlags & OP_IS_NAME_DECLARATION)
702         {
703             /* We don't want to fuss with actual name declaration nodes here */
704 
705             ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
706                 "******* NAME DECLARATION\n"));
707             return_VOID;
708         }
709     }
710 
711     /*
712      * The original path must be longer than one NameSeg (4 chars) for there
713      * to be any possibility that it can be optimized to a shorter string
714      */
715     AmlNameStringLength = strlen (AmlNameString);
716     if (AmlNameStringLength <= ACPI_NAMESEG_SIZE)
717     {
718         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
719             "NAMESEG %4.4s\n", AmlNameString));
720         return_VOID;
721     }
722 
723     /*
724      * We need to obtain the node that represents the current scope -- where
725      * we are right now in the namespace. We will compare this path
726      * against the Namepath, looking for commonality.
727      */
728     CurrentNode = AcpiGbl_RootNode;
729     if (WalkState->ScopeInfo)
730     {
731         CurrentNode = WalkState->ScopeInfo->Scope.Node;
732     }
733 
734     if (Flags & (AML_NAMED | AML_CREATE))
735     {
736         /* This is the declaration of a new name */
737 
738         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "NAME\n"));
739 
740         /*
741          * The node of interest is the parent of this node (the containing
742          * scope). The actual namespace node may be up more than one level
743          * of parse op or it may not exist at all (if we traverse back
744          * up to the root.)
745          */
746         NextOp = Op->Asl.Parent;
747         while (NextOp && (!NextOp->Asl.Node))
748         {
749             NextOp = NextOp->Asl.Parent;
750         }
751 
752         if (NextOp && NextOp->Asl.Node)
753         {
754             CurrentNode = NextOp->Asl.Node;
755         }
756         else
757         {
758             CurrentNode = AcpiGbl_RootNode;
759         }
760     }
761     else
762     {
763         /* This is a reference to an existing named object */
764 
765         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "REFERENCE\n"));
766     }
767 
768     /*
769      * Obtain the full paths to the two nodes that we are interested in
770      * (Target and current namespace location) in external
771      * format -- something we can easily manipulate
772      */
773     TargetPath.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
774     Status = AcpiNsHandleToPathname (TargetNode, &TargetPath, FALSE);
775     if (ACPI_FAILURE (Status))
776     {
777         AslCoreSubsystemError (Op, Status, "Getting Target NamePath",
778             ASL_NO_ABORT);
779         return_VOID;
780     }
781 
782     TargetPath.Length--;    /* Subtract one for null terminator */
783 
784     /* CurrentPath is the path to this scope (where we are in the namespace) */
785 
786     CurrentPath.Length = ACPI_ALLOCATE_LOCAL_BUFFER;
787     Status = AcpiNsHandleToPathname (CurrentNode, &CurrentPath, FALSE);
788     if (ACPI_FAILURE (Status))
789     {
790         AslCoreSubsystemError (Op, Status, "Getting Current NamePath",
791             ASL_NO_ABORT);
792         return_VOID;
793     }
794 
795     CurrentPath.Length--;   /* Subtract one for null terminator */
796 
797     /* Debug output only */
798 
799     Status = AcpiNsExternalizeName (ACPI_UINT32_MAX, AmlNameString,
800         NULL, &ExternalNameString);
801     if (ACPI_FAILURE (Status))
802     {
803         AslCoreSubsystemError (Op, Status, "Externalizing NamePath",
804             ASL_NO_ABORT);
805         return_VOID;
806     }
807 
808     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
809         "CURRENT SCOPE: (%2u) %-37s FULL PATH TO NAME: (%2u) %-32s ACTUAL AML:%-32s\n",
810         (UINT32) CurrentPath.Length, (char *) CurrentPath.Pointer,
811         (UINT32) TargetPath.Length, (char *) TargetPath.Pointer,
812         ExternalNameString));
813 
814     ACPI_FREE (ExternalNameString);
815 
816     /*
817      * Attempt an optimization depending on the type of namepath
818      */
819     if (Flags & (AML_NAMED | AML_CREATE))
820     {
821         /*
822          * This is a named opcode and the namepath is a name declaration, not
823          * a reference.
824          */
825         Status = OptOptimizeNameDeclaration (Op, WalkState, CurrentNode,
826             TargetNode, AmlNameString, &NewPath);
827         if (ACPI_FAILURE (Status))
828         {
829             /*
830              * 2) now attempt to
831              *    optimize the namestring with carats (up-arrow)
832              */
833             Status = OptBuildShortestPath (Op, WalkState, CurrentNode,
834                 TargetNode, &CurrentPath, &TargetPath,
835                 AmlNameStringLength, 1, &NewPath);
836         }
837     }
838     else
839     {
840         /*
841          * This is a reference to an existing named object
842          *
843          * 1) Check if search-to-root can be utilized using the last
844          *    NameSeg of the NamePath
845          */
846         Status = OptSearchToRoot (Op, WalkState, CurrentNode,
847             TargetNode, &TargetPath, &NewPath);
848         if (ACPI_FAILURE (Status))
849         {
850             /*
851              * 2) Search-to-root could not be used, now attempt to
852              *    optimize the namestring with carats (up-arrow)
853              */
854             Status = OptBuildShortestPath (Op, WalkState, CurrentNode,
855                 TargetNode, &CurrentPath, &TargetPath,
856                 AmlNameStringLength, 0, &NewPath);
857         }
858     }
859 
860     /*
861      * Success from above indicates that the NamePath was successfully
862      * optimized. We need to update the parse op with the new name
863      */
864     if (ACPI_SUCCESS (Status))
865     {
866         HowMuchShorter = (AmlNameStringLength - strlen (NewPath));
867         OptTotal += HowMuchShorter;
868 
869         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS,
870             " REDUCED BY %2u (TOTAL SAVED %2u)",
871             (UINT32) HowMuchShorter, OptTotal));
872 
873         if (Flags & AML_NAMED)
874         {
875             if (Op->Asl.AmlOpcode == AML_ALIAS_OP)
876             {
877                 /*
878                  * ALIAS is the only oddball opcode, the name declaration
879                  * (alias name) is the second operand
880                  */
881                 Op->Asl.Child->Asl.Next->Asl.Value.String = NewPath;
882                 Op->Asl.Child->Asl.Next->Asl.AmlLength = strlen (NewPath);
883             }
884             else
885             {
886                 Op->Asl.Child->Asl.Value.String = NewPath;
887                 Op->Asl.Child->Asl.AmlLength = strlen (NewPath);
888             }
889         }
890         else if (Flags & AML_CREATE)
891         {
892             /* Name must appear as the last parameter */
893 
894             NextOp = Op->Asl.Child;
895             while (!(NextOp->Asl.CompileFlags & OP_IS_NAME_DECLARATION))
896             {
897                 NextOp = NextOp->Asl.Next;
898             }
899             /* Update the parse node with the new NamePath */
900 
901             NextOp->Asl.Value.String = NewPath;
902             NextOp->Asl.AmlLength = strlen (NewPath);
903         }
904         else
905         {
906             /* Update the parse node with the new NamePath */
907 
908             Op->Asl.Value.String = NewPath;
909             Op->Asl.AmlLength = strlen (NewPath);
910         }
911     }
912     else
913     {
914         ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, " ALREADY OPTIMAL"));
915     }
916 
917     /* Cleanup path buffers */
918 
919     ACPI_FREE (TargetPath.Pointer);
920     ACPI_FREE (CurrentPath.Pointer);
921 
922     ACPI_DEBUG_PRINT_RAW ((ACPI_DB_OPTIMIZATIONS, "\n"));
923     return_VOID;
924 }
925