PerformanceTips.rst 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. =====================================
  2. Performance Tips for Frontend Authors
  3. =====================================
  4. .. contents::
  5. :local:
  6. :depth: 2
  7. Abstract
  8. ========
  9. The intended audience of this document is developers of language frontends
  10. targeting LLVM IR. This document is home to a collection of tips on how to
  11. generate IR that optimizes well. As with any optimizer, LLVM has its strengths
  12. and weaknesses. In some cases, surprisingly small changes in the source IR
  13. can have a large effect on the generated code.
  14. Avoid loads and stores of large aggregate type
  15. ================================================
  16. LLVM currently does not optimize well loads and stores of large :ref:`aggregate
  17. types <t_aggregate>` (i.e. structs and arrays). As an alternative, consider
  18. loading individual fields from memory.
  19. Aggregates that are smaller than the largest (performant) load or store
  20. instruction supported by the targeted hardware are well supported. These can
  21. be an effective way to represent collections of small packed fields.
  22. Prefer zext over sext when legal
  23. ==================================
  24. On some architectures (X86_64 is one), sign extension can involve an extra
  25. instruction whereas zero extension can be folded into a load. LLVM will try to
  26. replace a sext with a zext when it can be proven safe, but if you have
  27. information in your source language about the range of a integer value, it can
  28. be profitable to use a zext rather than a sext.
  29. Alternatively, you can :ref:`specify the range of the value using metadata
  30. <range-metadata>` and LLVM can do the sext to zext conversion for you.
  31. Zext GEP indices to machine register width
  32. ============================================
  33. Internally, LLVM often promotes the width of GEP indices to machine register
  34. width. When it does so, it will default to using sign extension (sext)
  35. operations for safety. If your source language provides information about
  36. the range of the index, you may wish to manually extend indices to machine
  37. register width using a zext instruction.
  38. Other things to consider
  39. =========================
  40. #. Make sure that a DataLayout is provided (this will likely become required in
  41. the near future, but is certainly important for optimization).
  42. #. Add nsw/nuw flags as appropriate. Reasoning about overflow is
  43. generally hard for an optimizer so providing these facts from the frontend
  44. can be very impactful.
  45. #. Use fast-math flags on floating point operations if legal. If you don't
  46. need strict IEEE floating point semantics, there are a number of additional
  47. optimizations that can be performed. This can be highly impactful for
  48. floating point intensive computations.
  49. #. Use inbounds on geps. This can help to disambiguate some aliasing queries.
  50. #. Add noalias/align/dereferenceable/nonnull to function arguments and return
  51. values as appropriate
  52. #. Mark functions as readnone/readonly or noreturn/nounwind when known. The
  53. optimizer will try to infer these flags, but may not always be able to.
  54. Manual annotations are particularly important for external functions that
  55. the optimizer can not analyze.
  56. #. Use ptrtoint/inttoptr sparingly (they interfere with pointer aliasing
  57. analysis), prefer GEPs
  58. #. Use the lifetime.start/lifetime.end and invariant.start/invariant.end
  59. intrinsics where possible. Common profitable uses are for stack like data
  60. structures (thus allowing dead store elimination) and for describing
  61. life times of allocas (thus allowing smaller stack sizes).
  62. #. Use pointer aliasing metadata, especially tbaa metadata, to communicate
  63. otherwise-non-deducible pointer aliasing facts
  64. #. Use the "most-private" possible linkage types for the functions being defined
  65. (private, internal or linkonce_odr preferably)
  66. #. Mark invariant locations using !invariant.load and TBAA's constant flags
  67. #. Prefer globals over inttoptr of a constant address - this gives you
  68. dereferencability information. In MCJIT, use getSymbolAddress to provide
  69. actual address.
  70. #. Be wary of ordered and atomic memory operations. They are hard to optimize
  71. and may not be well optimized by the current optimizer. Depending on your
  72. source language, you may consider using fences instead.
  73. #. If calling a function which is known to throw an exception (unwind), use
  74. an invoke with a normal destination which contains an unreachable
  75. instruction. This form conveys to the optimizer that the call returns
  76. abnormally. For an invoke which neither returns normally or requires unwind
  77. code in the current function, you can use a noreturn call instruction if
  78. desired. This is generally not required because the optimizer will convert
  79. an invoke with an unreachable unwind destination to a call instruction.
  80. #. If you language uses range checks, consider using the IRCE pass. It is not
  81. currently part of the standard pass order.
  82. #. For languages with numerous rarely executed guard conditions (e.g. null
  83. checks, type checks, range checks) consider adding an extra execution or
  84. two of LoopUnswith and LICM to your pass order. The standard pass order,
  85. which is tuned for C and C++ applications, may not be sufficient to remove
  86. all dischargeable checks from loops.
  87. #. Use profile metadata to indicate statically known cold paths, even if
  88. dynamic profiling information is not available. This can make a large
  89. difference in code placement and thus the performance of tight loops.
  90. #. When generating code for loops, try to avoid terminating the header block of
  91. the loop earlier than necessary. If the terminator of the loop header
  92. block is a loop exiting conditional branch, the effectiveness of LICM will
  93. be limited for loads not in the header. (This is due to the fact that LLVM
  94. may not know such a load is safe to speculatively execute and thus can't
  95. lift an otherwise loop invariant load unless it can prove the exiting
  96. condition is not taken.) It can be profitable, in some cases, to emit such
  97. instructions into the header even if they are not used along a rarely
  98. executed path that exits the loop. This guidance specifically does not
  99. apply if the condition which terminates the loop header is itself invariant,
  100. or can be easily discharged by inspecting the loop index variables.
  101. #. In hot loops, consider duplicating instructions from small basic blocks
  102. which end in highly predictable terminators into their successor blocks.
  103. If a hot successor block contains instructions which can be vectorized
  104. with the duplicated ones, this can provide a noticeable throughput
  105. improvement. Note that this is not always profitable and does involve a
  106. potentially large increase in code size.
  107. #. Avoid high in-degree basic blocks (e.g. basic blocks with dozens or hundreds
  108. of predecessors). Among other issues, the register allocator is known to
  109. perform badly with confronted with such structures. The only exception to
  110. this guidance is that a unified return block with high in-degree is fine.
  111. #. When checking a value against a constant, emit the check using a consistent
  112. comparison type. The GVN pass *will* optimize redundant equalities even if
  113. the type of comparison is inverted, but GVN only runs late in the pipeline.
  114. As a result, you may miss the opportunity to run other important
  115. optimizations. Improvements to EarlyCSE to remove this issue are tracked in
  116. Bug 23333.
  117. #. Avoid using arithmetic intrinsics unless you are *required* by your source
  118. language specification to emit a particular code sequence. The optimizer
  119. is quite good at reasoning about general control flow and arithmetic, it is
  120. not anywhere near as strong at reasoning about the various intrinsics. If
  121. profitable for code generation purposes, the optimizer will likely form the
  122. intrinsics itself late in the optimization pipeline. It is *very* rarely
  123. profitable to emit these directly in the language frontend. This item
  124. explicitly includes the use of the :ref:`overflow intrinsics <int_overflow>`.
  125. #. Avoid using the :ref:`assume intrinsic <int_assume>` until you've
  126. established that a) there's no other way to express the given fact and b)
  127. that fact is critical for optimization purposes. Assumes are a great
  128. prototyping mechanism, but they can have negative effects on both compile
  129. time and optimization effectiveness. The former is fixable with enough
  130. effort, but the later is fairly fundamental to their designed purpose.
  131. p.s. If you want to help improve this document, patches expanding any of the
  132. above items into standalone sections of their own with a more complete
  133. discussion would be very welcome.