We propose the first polynomial-time code selection algorithm for minimising the worst-case execution time of a nonnested loop executed on a fully pipelined processor that uses scratchpad memory to replace the instruction cache. The time complexity of our algorithm is O(m(ne + n2 log n)), where n and e are the number of basic blocks and the number of edges in the control flow graph of the loop, and m is the size of the scratchpad memory. Furthermore, we propose the first dynamic code selection heuristic for minimising the worst-case execution time of a task by using our algorithm for a non-nested loop. Our simulation results show that our heuristic significantly outperforms a previously known heuristic. Categories and Subject Descriptors D.3.4 [Processors]: [Compilers, Memory Management, Optimisation]; D4.7 [Organisation and Design]: Real-time systems and embedded systems General Terms Algorithms, Design, Performance Keywords Scratchpad Management, Worst-case Execution Time, Minimum N...