
    pi24                         d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ  G d d      Z G d	 d
      Z edg d      Zd Z G d d      Z edddg      Z G d de      Zy)    N)
namedtuple)Sequence)contextmanager)cached_property)configc                   (    e Zd ZdZdgZd Zd Zd Zy)RecordLLVMPassTimingsLegacy9A helper context manager to track LLVM pass timings.
    _datac                 0    t        j                  d       | S ))Enables the pass timing in LLVM.
        T)llvmset_time_passesselfs    ^/opt/services/ai/voice_agent/venv/lib/python3.12/site-packages/numba/misc/llvm_pass_timings.py	__enter__z%RecordLLVMPassTimingsLegacy.__enter__   s     	T"    c                 `    t        j                         | _        t        j                  d       y)2Reset timings and save report internally.
        FN)r   report_and_reset_timingsr   r   r   exc_valexc_typeexc_tbs       r   __exit__z$RecordLLVMPassTimingsLegacy.__exit__   s%     224
U#r   c                 ,    t        | j                        S ztRetrieve timing data for processing.

        Returns
        -------
        timings: ProcessedPassTimings
        ProcessedPassTimingsr   r   s    r   getzRecordLLVMPassTimingsLegacy.get!        $DJJ//r   N)__name__
__module____qualname____doc__	__slots__r   r   r!    r   r   r	   r	      s     	I0r   r	   c                   0    e Zd ZdZddgZd Zd Zd Zd Zy)	RecordLLVMPassTimingsr
   r   _pbc                      || _         d | _        y N)r+   r   )r   pbs     r   __init__zRecordLLVMPassTimings.__init__1   s    
r   c                 :    | j                   j                          | S )r   )r+   start_pass_timingr   s    r   r   zRecordLLVMPassTimings.__enter__5   s     	""$r   c                 B    | j                   j                         | _        y)r   N)r+   finish_pass_timingr   r   s       r   r   zRecordLLVMPassTimings.__exit__;   s     XX002
r   c                 ,    t        | j                        S r   r   r   s    r   r!   zRecordLLVMPassTimings.getA   r"   r   N)	r#   r$   r%   r&   r'   r/   r   r   r!   r(   r   r   r*   r*   +   s'     % I0r   r*   PassTimingRecord)
	user_timeuser_percentsystem_timesystem_percentuser_system_timeuser_system_percent	wall_timewall_percent	pass_nameinstructionc                     | d   j                   dk(  sJ fd}dD cg c]
  } ||       c}t        d |       }fd}t        t        ||            S c c}w )zAdjust timing records because of truncated information.

    Details: The percent information can be used to improve the timing
    information.

    Returns
    -------
    res: List[PassTimingRecord]
    Totalc                 \    |  d|  dt        j                        fd}|S )N_time_percentc                 8           }||    z  dz  }|| <   | S )z'Compute percent x total_time = adjustedg{Gz?r(   )dtotaladjustedpercent_attr	time_attrtime_getter	total_recs      r   adjustz6_adjust_timings.<locals>.make_adjuster.<locals>.adjustn   s.    	*Eq.5H#AiLHr   )operator
attrgetter)attrrN   rJ   rK   rL   rM   s     @@@r   make_adjusterz&_adjust_timings.<locals>.make_adjusteri   s6    fEN	x()))4	 r   )usersystemuser_systemwallc                 "    | j                         S r-   )_asdictxs    r   <lambda>z!_adjust_timings.<locals>.<lambda>}   s    !))+ r   c                 8    D ]
  } ||       }  t        di | S )Nr(   )r5   )rG   fnadj_fnss     r   chainedz _adjust_timings.<locals>.chained   s+     	B1A	  $!$$r   )r>   maplist)recordsrR   rZ   dictsr_   r^   rM   s        @@r   _adjust_timingsrd   \   sq     I')))  #LaG
 %w/E% GU#$$s   Ac                   R    e Zd ZdZd Zd Zd Zd Zd Zd Z	ddZ
ed	        Zd
 Zy)r    zA class for processing raw timing report from LLVM.

    The processing is done lazily so we don't waste time processing unused
    timing information.
    c                     || _         y r-   	_raw_data)r   raw_datas     r   r/   zProcessedPassTimings.__init__   s	    !r   c                 ,    t        | j                        S r-   )boolrh   r   s    r   __bool__zProcessedPassTimings.__bool__   s    DNN##r   c                     | j                   S )zWReturns the raw string data.

        Returns
        -------
        res: str
        rg   r   s    r   get_raw_dataz!ProcessedPassTimings.get_raw_data   s     ~~r   c                 <    | j                         d   j                  S )zhCompute the total time spend in all passes.

        Returns
        -------
        res: float
        rA   )list_recordsr<   r   s    r   get_total_timez#ProcessedPassTimings.get_total_time   s       "2&000r   c                     | j                   S )z{Get the processed data for the timing report.

        Returns
        -------
        res: List[PassTimingRecord]
        )
_processedr   s    r   rp   z!ProcessedPassTimings.list_records   s     r   c                     | j                         }t        j                  d      }t        j                  ||dd |      S )a  Returns the top(n) most time-consuming (by wall-time) passes.

        Parameters
        ----------
        n: int
            This limits the maximum number of items to show.
            This function will show the ``n`` most time-consuming passes.

        Returns
        -------
        res: List[PassTimingRecord]
            Returns the top(n) most time-consuming passes in descending order.
        r<   NrA   )rp   rO   rP   heapqnlargest)r   nrb   keys       r   list_topzProcessedPassTimings.list_top   s;     ##%!!+.~~a"s33r   c           	         g d|z  fd} |d| j                         dd        |d       | j                  |      D ]3  } |d|j                  dd|j                  d	d
|j                          5 dj                        S )a  Return a string summarizing the timing information.

        Parameters
        ----------
        topn: int; optional
            This limits the maximum number of items to show.
            This function will show the ``topn`` most time-consuming passes.
        indent: int; optional
            Set the indentation level. Defaults to 0 for no indentation.

        Returns
        -------
        res: str
         c                 0    j                   |         y r-   )append)argbufprefixs    r   apz(ProcessedPassTimings.summary.<locals>.ap   s    JJ&#'(r   zTotal .4fszTop timings:z  zs (5z%) 
)rq   ry   r<   r=   r>   join)r   topnindentr   pr   r   s        @@r   summaryzProcessedPassTimings.summary   s     v	) 	VD'')#.a01
>t$ 	LAAKK$Cq'9Q[[MJK	Lyy~r   c                 "    | j                         S )ztA cached property for lazily processing the data and returning it.

        See ``_process()`` for details.
        )_processr   s    r   rs   zProcessedPassTimings._processed   s     }}r   c                 T    d }t         || j                              }t        |      S )zParses the raw string data from LLVM timing report and attempts
        to improve the data by recomputing the times
        (See `_adjust_timings()``).
        c           	   3     K   | j                         }d}d| d}t        |      }dddddd	d
}|D ]R  }t        j                  ||      }|st        j                  d|      }|D 	cg c]  }	||	j                             }
}	 n 
d   d	k(  sJ g }d}d}|
dd D ]A  }	|	dk(  r||z  }|j                  |	 d       |j                  |	 d       |d| d| dz  }C i }t        j                  D ]  }	|	|vs|	d	k7  sd||	<    |dz  }|D ]  }t        j                  ||      }|t        |j                               } t        ||       D 	ci c]  \  }	}|	|t        |      nd }}	}|j                  |       | d   }t        dd	|i|}| |j                  dk(  s n dj                  |      }d|v ry|rt!        d|       yc c}	w c c}}	w w)zwA generator that parses the raw_data line-by-line to extract
            timing information for each pass.
            z[a-zA-Z+ ]+z(?:\s*-+z-+)+rS   rT   rU   rV   r?   r>   )z	User TimezSystem TimezUser+Systemz	Wall TimeInstrNamez[a-zA-Z][a-zA-Z+ ]+rA   z\s*((?:[0-9]+\.)?[0-9]+) NrD   rE   z\s+(?:z\s*\(z%\)|-+)g        z\s*(.*)rB   r   z Analysis execution timing reportz'unexpected text after parser finished:
r(   )
splitlinesiterrematchfindallstripr}   r5   _fieldsra   groupszipfloatupdater>   r   
ValueError)ri   lines	colheadermulticolheaders	line_iter
header_maplnmraw_headerskheadersattrsrw   patmissingvdatar>   rec	remainings                       r   parsez,ProcessedPassTimings._process.<locals>.parse   s`     '')E&I!))D9OUI $',#&#J   HH_b1"$**-CR"HK>IJz!'')4JGJ 2;+---E+ACSb\ 8%1HCLLA3e-LLA3h0fQCuQCw77C8 G%-- %E>a;&6!$GAJ% :C HHS"%=#AHHJ/H(+E8(<> $1 1=uQxcA >D >KK( (I* "+/3C I}}/  		),I 2Y> >ykJ  [ K6>s=   A
GG'GA7G9G?)G)(GG+9G%5G)ra   rh   rd   )r   r   rb   s      r   r   zProcessedPassTimings._process   s)    H	V uT^^,-w''r   N)   r   )r#   r$   r%   r&   r/   rl   rn   rq   rp   ry   r   r   rs   r   r(   r   r   r    r       sD    "$14$6  R(r   r    NamedTimingsnametimingsc                   r    e Zd ZdZd Zed        Zed        Zd Zd Z	d Z
ed        Zdd	Zd
 Zd Zd Zy)PassTimingsCollectionzA collection of pass timings.

    This class implements the ``Sequence`` protocol for accessing the
    individual timing records.
    c                      || _         g | _        y r-   )_name_records)r   r   s     r   r/   zPassTimingsCollection.__init__E  s    
r   c              #      K   t         j                  r=t               5 }d ddd       j                         }|r| j	                  ||       yyd y# 1 sw Y   4xY ww)a  Record new timings and append to this collection.

        Note: this is mainly for internal use inside the compiler pipeline.

        See also ``RecordLLVMPassTimingsLegacy``

        Parameters
        ----------
        name: str
            Name for the records.
        N)r   LLVM_PASS_TIMINGSr	   r!   _append)r   r   r   r   s       r   record_legacyz#PassTimingsCollection.record_legacyI  sV      ##,. '++-CT3'   s   A!A3A!AA!c              #      K   t         j                  r>t        |      5 }d ddd       j                         }|r| j	                  ||       yyd y# 1 sw Y   4xY ww)a  Record new timings and append to this collection.

        Note: this is mainly for internal use inside the compiler pipeline.

        See also ``RecordLLVMPassTimings``

        Parameters
        ----------
        name: str
            Name for the records.
        N)r   r   r*   r!   r   )r   r   r.   r   r   s        r   recordzPassTimingsCollection.recordb  sX      ##&r* g++-CT3'   s   A"A3A"AA"c                 N    | j                   j                  t        ||             y)zAppend timing records

        Parameters
        ----------
        name: str
            Name for the records.
        timings: ProcessedPassTimings
            the timing records.
        N)r   r}   r   )r   r   r   s      r   r   zPassTimingsCollection._append{  s     	\$89r   c                 T    | j                   rt        d | j                   D              S y)zComputes the sum of the total time across all contained timings.

        Returns
        -------
        res: float or None
            Returns the total number of seconds or None if no timings were
            recorded
        c              3   P   K   | ]  }|j                   j                            y wr-   r   rq   ).0rs     r   	<genexpr>z7PassTimingsCollection.get_total_time.<locals>.<genexpr>  s     Iaqyy//1Is   $&N)r   sumr   s    r   rq   z$PassTimingsCollection.get_total_time  s#     ==I4==IIIr   c                 4    t        | j                  d d      S )zReturns the timings in descending order of total time duration.

        Returns
        -------
        res: List[ProcessedPassTimings]
        c                 6    | j                   j                         S r-   r   rY   s    r   r[   z:PassTimingsCollection.list_longest_first.<locals>.<lambda>  s    AII$<$<$> r   T)rx   reverse)sortedr   r   s    r   list_longest_firstz(PassTimingsCollection.list_longest_first  s     dmm>"$ 	$r   c                     | j                    S )z	
        r   r   s    r   is_emptyzPassTimingsCollection.is_empty  s     ==  r   c                    | j                   ryg }|j                  } |d| j                          | j                         } |d|d       t	        | j
                        D ]m  \  }} |d| d|j                          |j                  j                         |z  dz  } |d|d	d
        ||j                  j                  |d             o dj                  |      S )a  Return a string representing the summary of the timings.

        Parameters
        ----------
        topn: int; optional, default=5.
            This limits the maximum number of items to show.
            This function will show the ``topn`` most time-consuming passes.

        Returns
        -------
        res: str

        See also ``ProcessedPassTimings.summary()``
        zNo pass timings were recordedzPrinting pass timings for zTotal time: r   z== #r{   d   z
 Percent: z.1f%   )r   r   r   )
r   r}   r   rq   	enumerater   r   r   r   r   )r   r   r   r   overall_timeir   percents           r   r   zPassTimingsCollection.summary  s     ==2CB+DJJ<89..0Ll3/01!$--0 ;1T!AaffX&'))224|CcIZ}A./199$$$q$9:	;
 99S>!r   c                      | j                   |   S )zGet the i-th timing record.

        Returns
        -------
        res: (name, timings)
            A named tuple with two fields:

            - name: str
            - timings: ProcessedPassTimings
        r   )r   r   s     r   __getitem__z!PassTimingsCollection.__getitem__  s     }}Qr   c                 ,    t        | j                        S )z#Length of this collection.
        )lenr   r   s    r   __len__zPassTimingsCollection.__len__  s     4==!!r   c                 "    | j                         S r-   )r   r   s    r   __str__zPassTimingsCollection.__str__  s    ||~r   N)r   )r#   r$   r%   r&   r/   r   r   r   r   rq   r   propertyr   r   r   r   r   r(   r   r   r   r   >  sk      0  0
:	$ ! !
"< "
r   r   )r   rO   ru   collectionsr   collections.abcr   
contextlibr   	functoolsr   
numba.corer   llvmlite.bindingbindingr   r	   r*   r5   rd   r    r   r   r(   r   r   <module>r      s~    	   " $ % %  0 0:0 0@  "*%Zo( o(d .69*=>YH Yr   