57 research outputs found

    Contributions to worst-case execution time reduction using compilation techniques

    Get PDF
    Tese (doutorado) - Universidade Federal de Santa Catarina, Centro Tecnológico, Programa de Pós-Graduação em Engenharia de Automação e Sistemas, Florianópolis, 2017Abstract: A wide range of systems are distinct from the general purpose computingsystems due to the need of satisfying rigorous timing requirements, oftenunder the constraint of available resources, they are generally called realtimesystems. The development of a predictable system is concerned withthe challenges of building systems whose time requirements can be guaranteeda priori. Although, these challenges become even greater when usingprocessors architectural features for performance increase, as cachesand pipelines, which introduce a high degree of uncertainty, making difficultto provide any kind of guarantee. Parallel to this, there are the toolsneeded to develop and execute an application, such as languages, compilers,runtime support, communication systems and scheduling, which mayfurther make difficult the assertion of guarantees. In these systems, theresults of computations must be generated at the right time and faults oftemporal nature can result in catastrophic consequences both in the economicsense as in human lives. These systems are present in countlessapplications, such as in industrial plants, aviation, and the complexity ofthem imposes serious restrictions on the hardware that can be used. Toprovide timing guarantees, we must know the worst-case execution timefor each tasks of the system. In a general purpose architecture aimed atthe average case, the execution time of a program or task can be so greatin the worst case that invalidates the design constraints, or even be impossibleto be calculated or estimated with a reasonable effort. In thisthesis, we integrate compilation with WCET calculation. A compiler canprovide relevant data to facilitate the process of WCET estimation. Toimprove this process, we also use an architecture whose purpose is toconciliate performance with determinism. Considering compilation andWCET integration we present the following contributions: (1) a differentway to perform loop unrolling on data-dependent loops using codepredication targeting WCET reduction, because existing techniques onlyconsider loops with fixed execution counts. (2) considering static branchpredication techniques, we show that a very small gain or even none canbe obtained with new optimization techniques targeted to worst-case executiontime reduction. To achieve this objective, we compare several techniquesagainst the perfect branch predictor. (3) the difference between theWCET of a task and its actual execution time is called gain time. Wepropose a technique that finds specific points of a program (called gainpoints), where there will be an amount of statically estimated gain time inthe case that path is taken by the execution.Uma grande gama de sistemas se distinguem dos sistemas de computaçãode propósito geral pela necessidade de satisfação de requisitos detemporização rigorosos. O desenvolvimento de um sistema previsível preocupasecom os desafios de construção de sistemas cujos requisitos temporais possamser garantidos a priori. Estes desafios tornam-se ainda maiores quandose utiliza recursos arquiteturais para aumento de performance, como cachese pipelines, os quais introduzem um alto grau de incertezas, tornando difícilo provimento de qualquer tipo de garantia. Paralelamente a isto, existem asferramentas necessárias ao desenvolvimento e execução da aplicação, comolinguagens, compiladores, runtime de execução, sistemas de comunicação eescalonamento, os quais podem dificultar ainda mais a asserção de garantias.Nestes sistemas, os resultados das computações devem estar corretosnão somente do ponto de vista lógico, mas também devem ser gerados nomomento correto. As falhas de natureza temporal nestes sistemas são, emalguns casos, consideradas críticas no que diz respeito às suas consequências.Nos sistemas tempo real críticos (hard real-time) o não atendimento de umrequisito temporal pode resultar em consequências catastróficas tanto no sentidoeconômico quanto em vidas humanas. Quando os requisitos temporaisnão são críticos (soft real-time) eles apenas descrevem o comportamento desejado.O não atendimento de tais requisitos reduz a utilidade da aplicaçãomas não a elimina completamente nem resulta em consequências catastróficas.Estes sistemas estão presentes em diversas aplicações, como em plantasindustriais, aviação e eletrônica automotiva, telecomunicações e sistemasespaciais. Em várias destas aplicações, a complexidade dos sistemas de softwareimpõe sérias restrições quanto ao hardware que poderá ser utilizado.Este deverá ter capacidade suficiente para sustentar a aplicação em questão,além de poder estar submetido a restrições não funcionais do projeto, comocusto e eficiência energética.Arquiteturas modernas e de propósito geral possuem como premissabásica aquela que diz que os programas devem executar o mais rápido possívelna maioria das vezes. Este tempo médio é geralmente chamado deACET - Average-case Execution Time. Entretanto, em alguns casos, o tempode uma execução de uma aplicação poderá ser grande em relação ao caso médio,mas ainda estará amortizado entre as diversas execuções do programa.Esta priorização de caso médio impõe certas problemáticas quanto à utilizaçãodeste tipo de arquitetura em sistemas de tempo real. Tais sistemas podemexigir garantias de tempo de execução difíceis de serem obtidas ou muitasvezes inviáveis. Estas garantias exigem o conhecimento do pior tempo deexecução de um programa ou tarefa em um determinado processador, o qualgeralmente é chamado de WCET - Worst-case Execution Time. Em uma arquiteturade propósito geral que vise o caso médio, o tempo de execução nopior caso de um programa ou tarefa pode ser tão grande que inviabilize asrestrições de projeto, ou mesmo ser impossível de ser estimado.Atualmente, existem vertentes acadêmicas que sugerem a utilização deprocessadores e arquiteturas voltadas para aplicações de tempo real. Taisarquiteturas adotam características de hardware que tornam as análises referentesà obtenção de WCET mais simples e rápidas.Uma característica importante é que o desempenho em arquiteturas específicas,como as voltadas para tempo real, pode estar intimamente relacionadoao compilador e as técnicas de compilação empregadas, como exploraçãoestática de paralelismo. Dada a possibilidade de ser obter o WCET deprogramas para uma arquitetura específica, pode-se utilizar estas informaçõesno processo de otimização incremental dos mesmos. Estas otimizações visama redução do WCET, visto que abordagens tradicionais de transformação decódigo feitas por compilador podem até mesmo aumentar o WCET de umprograma.ObjetivosO objetivo deste trabalho é contribuir com aspectos relacionados à compilaçãopara sistemas de tempo real, cujo objetivo primário seja a reduçãode WCET ou melhoria de aspectos relacionados à escalonabilidade. A tesea ser demonstrada é que o íntimo acoplamento de um compilador com umanalisador WCET pode beneficiar tanto a análise quanto a síntese de um programaexecutável ou sistema completo para uma arquitetura determinista. Autilização de uma arquitetura determinista representa uma característica importantedeste trabalho, bem como o desenvolvimento do respectivo analisadorWCET.Dentre os elementos relacionados ao compilador essenciais para a reduçãodo WCET, pode-se citar: Mecanismos para o cálculo de WCET de programas em processo decompilação. Isto implica acoplamento do compilador com o analisadordesenvolvido. Identificação de potenciais pontos a serem beneficiados por otimizações.Este processo envolve interpretação dos resultados do analisador. Descarte de alterações de códigos que aumentem o WCET. Novamente,decisões deverão ser tomadas com base em análises sucessivas.Além dos elementos relacionados, podemos destacar a eficiência doprocesso. O uso de uma arquitetura projetada para aplicações em tempo realpermite o uso de um analisador muito mais rápido e preciso, que visa trazereficiência ao processo. Embora a arquitetura se baseie em um ISA comercial,não existe compilador livre disponível para esta, então, a implementação deum gerador de código inteiramente funcional fez-se necessária como requisitopara realização do trabalho de tese.Entre os elementos considerados como foco desta tese, têm-se: Técnicas de loop unrolling: Laços são frequentemente bons candidatosalvopara otimizações de compilação para extrair o desempenho emprocessadores modernos. Algumas técnicas foram propostas na literaturapara alcançar a redução do WCET usando o loop unrolling, comoem (ZHAO et al., 2006) e (LOKUCIEJEWSKI; MARWEDEL, 2010).Nestes trabalhos, apenas os laços com contagens de execução fixas sãoconsiderados. Previsão estática de desvios: Previsores de desvio são utilizados paraaumentar o desempenho de programas em arquiteturas modernas. Previsoresestáticos podem depender do compilador para definir o comportamentode cada desvio condicional. Esse comportamento é entãoadotado pelo processador para toda a execução do programa. O uso daprevisão estática de desvio como mecanismo para redução do tempo deexecução de pior caso é uma alternativa conhecida e foi primeiramenteproposta por (BODIN; PUAUT, 2005) e (BURGUIERE et al., 2005). Identificação de tempo ganho em programas: Tempo ganho (ou gaintime) (AUDSLEY et al., 1994) (AVILA et al., 2003) (HU et al., 2002)(HU et al., 2003) é a diferença entre o WCET de uma tarefa e o tempode execução real. Uma abordagem comum é identificar o gain timeem tempo de execução comparando o tempo de execução real (medido)com o WCET calculado estaticamente. A identificação do tempo deganho precoce é útil para aumentar a utilização do sistema em tempo deexecução e para economizar energia do sistema, por exemplo.Alcançar a redução do pior tempo de computação em tarefas que compõemum sistema de tempo real é importante pois permite que recursos computacionaisnão sejam desperdiçados, impactando diretamente no custo. Outraimportância para tal redução é a aceitação de tarefas do tipo soft real-time,pois quanto menor o WCET das tarefas do tipo hard, mais tempo de processadorpode ser alocado para este tipo de tarefa.ContribuiçõesAs contribuições desta tese para o estado da arte são:1. A proposição de uma maneira diferente de executar o loop unrollingsobre laços cujas execuções são dependentes de dados usando a predicaçãode código visando redução de WCET, porque as técnicas existentesconsideram apenas laços com contagens de execução fixas. A técnicaproposta também foi combinada com abordagens de loop unrollingexistentes. Os resultados mostraram que esta combinação pode produziragressivas reduções de WCET quando comparadas com o códigooriginal.2. Em relação às técnicas de predição estática de desvios, são mostradosque somente ganhos pequenos ou mesmo nenhum ganho pode ser obtidocom novas técnicas de otimização direcionadas para a redução do tempode execução do pior caso. Para alcançar esse objetivo, foram comparadasvárias técnicas contra o previsor de desvio perfeito. Este previsorpermite estimar a redução máxima de WCET que pode ser obtida comabordagens estáticas. Além da técnica clássica da literatura, foi incluídana comparação uma nova técnica centrada em WCET que atua comouma abordagem de força bruta para aproximar os resultados do preditorperfeito. A comparação também inclui técnicas de compilação nãodiretamente orientadas para redução de WCET. Como resultado, sãomostradas que as técnicas consideradas nesta tese estão próximas do resultadoótimo obtido pelo previsor perfeito. Também é mostrado quea técnica proposta produz resultados ligeiramente melhores do que asdemais técnicas. Como contribuição secundária, é mostrado que as técnicasinconscientes de WCET também podem ser usadas em ambientesem tempo real porque apresentam bons resultados e baixa complexidade.As técnicas de previsão foram avaliadas usando um conjunto deexemplos dos benchmarks para WCET de Mälardalen.3. Um problema do WCET é que ele é relativo a um único caminho de execução,especificamente o caminho de execução do pior caso (WCEP).Quando uma aplicação em tempo real executa sobre um caminho diferentedo WCEP, seu tempo de execução será provavelmente menor doque o WCET. A diferença entre o WCET de uma tarefa e seu tempo deexecução real é chamado de tempo ganho. Neste trabalho, é propostauma técnica que encontra pontos específicos de um programa (chamadospontos de ganho), onde haverá uma quantidade de tempo ganhoestimado estaticamente no caso de esse caminho ser tomado pela execução.Como estudo de caso, é apresentado o tempo ganho obtido pelaaplicação estratégia proposta a um benchmark da série de benchmarkspara WCET de Mälardalen. Para o benchmark selecionado, foram identificadosvários pontos de ganho e alguns deles com uma quantidadesignificativa de tempo ganho detectado estaticamente.ConclusãoSistemas de tempo real estão presentes em diversos segmentos da indústria,desde sistemas aviônicos a eletrônica automotiva, passando por sistemasindustriais. No passado, tais sistemas eram bastante simples, considerandoa demanda por recursos computacionais e interdependência entretarefas. Porém hoje o cenário é outro: têm-se aplicações com altíssimo nívelde complexidade, por vezes geradas sem intervenção humana a partir de modelosformais. Cada tarefa componente destas aplicações possui seu próprioprazo e por vezes depende de resultados provenientes de outras tarefas (possivelmenteatravés de uma rede), levando a necessidade de estimativa tambémde prazos fim-a-fim.Levantado o cenário anterior, percebe-se que processadores simples,como microcontroladores, não são capazes de atender aplicações de temporeal como atendiam no passado. Neste caso, torna-se necessária a utilizaçãode processadores com maior capacidade computacional, com mecanismos deaumento desempenho, como pipelines, caches e execução especulativa. Oproblema com estes mecanismos é a dificuldade de cálculo do pior caso notempo de computação, devido a fatores como anomalias temporais. Entretanto,algumas vertentes da literatura sugerem o uso de arquiteturas voltadaspara tempo-real, ou seja, deterministas.Neste trabalho, foi objetivada a geração e otimização de código parauma arquitetura determinista mas com mecanismos de aumento de performance.O objetivo primário foi a redução de WCET de programas, bemcomo o levantamento de alguns parâmetros úteis no projeto de um sistemade tempo real. A redução de WCET importante para não sobre-dimensionarsistemas, não desperdiçando assim, recursos computacionais. A utilizaçãode uma arquitetura determinista aliada a redução de WCET induz a sistemasbem dimensionados em termos de recursos.Usando técnicas como loop unrolling usando predicação de código eprevisão estática de desvios, foi possível reduzir o pior caso no tempo decomputação de tarefas. A caracterização de tempo ganho, do ponto de vistapuramente estático, também pôde ser alcançada neste trabalho

    Survey on Combinatorial Register Allocation and Instruction Scheduling

    Full text link
    Register allocation (mapping variables to processor registers or memory) and instruction scheduling (reordering instructions to increase instruction-level parallelism) are essential tasks for generating efficient assembly code in a compiler. In the last three decades, combinatorial optimization has emerged as an alternative to traditional, heuristic algorithms for these two tasks. Combinatorial optimization approaches can deliver optimal solutions according to a model, can precisely capture trade-offs between conflicting decisions, and are more flexible at the expense of increased compilation time. This paper provides an exhaustive literature review and a classification of combinatorial optimization approaches to register allocation and instruction scheduling, with a focus on the techniques that are most applied in this context: integer programming, constraint programming, partitioned Boolean quadratic programming, and enumeration. Researchers in compilers and combinatorial optimization can benefit from identifying developments, trends, and challenges in the area; compiler practitioners may discern opportunities and grasp the potential benefit of applying combinatorial optimization

    Using SMT Solving for the Lookup of Infeasible Paths in Binary Programs

    Get PDF
    International audienceWorst-Case Execution Time (WCET) is a key component to check temporal constraints of realtime systems. WCET by static analysis provides a safe upper bound. While hardware modelling is now efficient, loss of precision stems mainly in the inclusion of infeasible execution paths in the WCET calculation. This paper proposes a new method to detect such paths based on static analysis of machine code and the feasibility test of conditions using Satisfiability Modulo Theory (SMT) solvers. The experimentation shows promising results although the expected precision was slightly lowered due to clamping operations needed to cope with complexity explosion. An important point is that the implementation has been performed in the OTAWA framework and is independent of any instruction set thanks to its semantic instructions

    Using SMT Solving for the Lookup of Infeasible Paths in Binary Programs

    Get PDF
    Worst-Case Execution Time (WCET) is a key component to check temporal constraints of realtime systems. WCET by static analysis provides a safe upper bound. While hardware modelling is now efficient, loss of precision stems mainly in the inclusion of infeasible execution paths in the WCET calculation. This paper proposes a new method to detect such paths based on static analysis of machine code and the feasibility test of conditions using Satisfiability Modulo Theory (SMT) solvers. The experimentation shows promising results although the expected precision was slightly lowered due to clamping operations needed to cope with complexity explosion. An important point is that the implementation has been performed in the OTAWA framework and is independent of any instruction set thanks to its semantic instructions

    PRECISE YET SCALABLE RESOURCE ANALYSIS VIA SYMBOLIC EXECUTION

    Get PDF
    Ph.DDOCTOR OF PHILOSOPH

    Reducing the WCET and analysis time of systems with simple lockable instruction caches

    Get PDF
    One of the key challenges in real-time systems is the analysis of the memory hierarchy. Many Worst-Case Execution Time (WCET) analysis methods supporting an instruction cache are based on iterative or convergence algorithms, which are rather slow. Our goal in this paper is to reduce the WCET analysis time on systems with a simple lockable instruction cache, focusing on the Lock-MS method. First, we propose an algorithm to obtain a structure-based representation of the Control Flow Graph (CFG). It organizes the whole WCET problem as nested subproblems, which takes advantage of common branch-and-bound algorithms of Integer Linear Programming (ILP) solvers. Second, we add support for multiple locking points per task, each one with specific cache contents, instead of a given locked content for the whole task execution. Locking points are set heuristically before outer loops. Such simple heuristics adds no complexity, and reduces the WCET by taking profit of the temporal reuse found in loops. Since loops can be processed as isolated regions, the optimal contents to lock into cache for each region can be obtained, and the WCET analysis time is further reduced. With these two improvements, our WCET analysis is around 10 times faster than other approaches. Also, our results show that the WCET is reduced, and the hit ratio achieved for the lockable instruction cache is similar to that of a real execution with an LRU instruction cache. Finally, we analyze the WCET sensitivity to compiler optimization, showing for each benchmark the right choices and pointing out that O0 is always the worst option

    WCET-Aware Scratchpad Memory Management for Hard Real-Time Systems

    Get PDF
    abstract: Cyber-physical systems and hard real-time systems have strict timing constraints that specify deadlines until which tasks must finish their execution. Missing a deadline can cause unexpected outcome or endanger human lives in safety-critical applications, such as automotive or aeronautical systems. It is, therefore, of utmost importance to obtain and optimize a safe upper bound of each task’s execution time or the worst-case execution time (WCET), to guarantee the absence of any missed deadline. Unfortunately, conventional microarchitectural components, such as caches and branch predictors, are only optimized for average-case performance and often make WCET analysis complicated and pessimistic. Caches especially have a large impact on the worst-case performance due to expensive off- chip memory accesses involved in cache miss handling. In this regard, software-controlled scratchpad memories (SPMs) have become a promising alternative to caches. An SPM is a raw SRAM, controlled only by executing data movement instructions explicitly at runtime, and such explicit control facilitates static analyses to obtain safe and tight upper bounds of WCETs. SPM management techniques, used in compilers targeting an SPM-based processor, determine how to use a given SPM space by deciding where to insert data movement instructions and what operations to perform at those program locations. This dissertation presents several management techniques for program code and stack data, which aim to optimize the WCETs of a given program. The proposed code management techniques include optimal allocation algorithms and a polynomial-time heuristic for allocating functions to the SPM space, with or without the use of abstraction of SPM regions, and a heuristic for splitting functions into smaller partitions. The proposed stack data management technique, on the other hand, finds an optimal set of program locations to evict and restore stack frames to avoid stack overflows, when the call stack resides in a size-limited SPM. In the evaluation, the WCETs of various benchmarks including real-world automotive applications are statically calculated for SPMs and caches in several different memory configurations.Dissertation/ThesisDoctoral Dissertation Computer Science 201

    Verbessern der Präzision des Statischen Analysators Goblint durch Loop Unrolling

    Get PDF
    Goblint is a source code analysis tool for C programs. It is based on abstract interpretation, and aims for a sound analysis. For loop representation and analysis, Goblint currently performs a simple CIL transformation to the input C code and can be refined by choosing one of two different abstract array domains. These domains are quite imprecise, as all elements of an array are represented by either one or three abstract values, depending on the domain used. In other known static analyzers, the analysis of loops is made more precise by treating the first k iterations of the loop separately from the following ones. This transformation is known as loop unrolling. In general, the larger the k, the more precise the analysis, and the longer it takes to perform. The goal of this thesis is to design and implement a limited unrolling of loops of the analyzed program, and an abstract domain for arrays that can express precise information for the values at the first k index of the array. Together, those modifications optimize the precision of the analysis results that Goblint produces at loops. The approach proposed is powerful enough to transform all types of loops supported in C programs, even complex structures like nested loops. It also handles complete initialization of arrays and updates after initialization. The overhead of the analysis for real-world programs (about 50%) after integration into Goblint is also reported

    Embedded System Design

    Get PDF
    A unique feature of this open access textbook is to provide a comprehensive introduction to the fundamental knowledge in embedded systems, with applications in cyber-physical systems and the Internet of things. It starts with an introduction to the field and a survey of specification models and languages for embedded and cyber-physical systems. It provides a brief overview of hardware devices used for such systems and presents the essentials of system software for embedded systems, including real-time operating systems. The author also discusses evaluation and validation techniques for embedded systems and provides an overview of techniques for mapping applications to execution platforms, including multi-core platforms. Embedded systems have to operate under tight constraints and, hence, the book also contains a selected set of optimization techniques, including software optimization techniques. The book closes with a brief survey on testing. This fourth edition has been updated and revised to reflect new trends and technologies, such as the importance of cyber-physical systems (CPS) and the Internet of things (IoT), the evolution of single-core processors to multi-core processors, and the increased importance of energy efficiency and thermal issues
    corecore