Skip to main content
AI
  • Get started with AI

    • Red Hat AI

      Accelerate the development and deployment of enterprise AI solutions.

    • AI learning hub

      Explore learning materials and tools, organized by task.

    • AI interactive demos

      Click through scenarios with Red Hat AI, including training LLMs and more.

    • AI/ML learning paths

      Expand your Red Hat OpenShift AI knowledge using these learning resources.

    • AI quickstarts

      Focused AI use cases designed for fast deployment on Red Hat AI platforms.

    • No-cost AI training

      Foundational Red Hat AI training.

  • Featured resources

    • Red Hat OpenShift AI
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

Red Hat AI Factory with NVIDIA

Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.

Learn
  • Self-guided

    • Documentation

      Find answers, get step-by-step guidance, and learn how to use Red Hat products.

    • Learning paths

      Explore curated walkthroughs for common development tasks.

    • Guided learning

      Receive custom learning paths powered by our AI assistant.

    • See all learning
  • Hands-on

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

    • Interactive labs

      Learn by doing in these hands-on, browser-based experiences.

    • Interactive demos

      Click through product features in these guided tours.

  • Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics
  • Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
Build
  • Get started

    • Red Hat build of Podman Desktop

      A downloadable, local development hub to experiment with our products and builds.

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

  • Download products

    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products
  • Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset
  • References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
Community
  • Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions
  • Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github
  • Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

Join the Red Hat Developer program

Download Red Hat products and project builds, access support documentation, learning content, and more.

ConsoleDocsSupport Search
New For you

Recommended

We'll recommend resources you may like as you browse. Try these suggestions for now.

  • Product downloads
  • Cheat sheets
  • Red Hat Developer learning portal
  • Developer blog
  • E-books
  • Developer Sandbox
Log in

Get more with a Red Hat Developer account

  • Product downloads
  • Console access
  • Event registration
  • Training & trials
Explore more account benefitsLog in or register

A subscription may be required for some services.

Contact us

A beginner's attempt at optimizing GCC

October 29, 2021
Arjun Shankar
Related topics:
C, C#, C++LinuxOpen source
Related products:
Red Hat Enterprise Linux

    Anyone who engages in C/C++ development on a modern GNU/Linux system typically ends up using the GCC or LLVM compiler, to which Red Hat actively contributes. As a member of the toolchain engineering team, I mostly work on runtime libraries (glibc), but being acquainted with the internals of the compiler that builds Red Hat Enterprise Linux (RHEL) is useful.

    With this goal in mind, and with a bit of advice from experienced engineers on the team, I decided to dip my toes into GCC internals by attempting to implement a small optimization. I was pointed to a list of open "tree optimization" bugs marked as easyhack. These are beginner-friendly optimizations identified by the community.

    Finding a suitable GCC bug

    I went through a number of reports in the bug tracker. Some were already fixed by a recent commit and just needed closing, and others weren't nearly as simple as I'd like for my first attempt. Eventually, I found what seemed like an easy bug to work on, in the form of bug 96703, reported by Gabriel Ravier. The gist of the bug is that the following expression:

    (x > y) && (y == 0)

    can be simplified to:

    (x > 0) && (y == 0)

    The optimization works because you're not interested in the result of x > y unless y is zero.

    In his initial comment Gabriel mentioned that, although this optimization doesn't appear to make the code run any faster, it can potentially run faster on pipelined CPUs and make further optimizations easier. This is an optimization because it removes an "input dependence" between the two comparisons, and makes the first comparison depend only on one variable instead of two.

    Clang/LLVM already implements this optimization, an advantage that happens to be a common thread in many of the bugs reported by Gabriel. It's nice to observe the healthy competition between the two compiler communities that leads to great compilers for everyone.

    Using GCC's Match and Simplify DSL

    So how would one go about implementing this optimization in GCC, as well? Thankfully, GCC comes with a purpose-built, domain-specific language (DSL) for writing expression simplifications like this one. It's described in the Match and Simplify chapter of the GCC Internals manual.

    The language is declarative. A new expression simplification only needs to be declared in gcc/match.pd. The equivalent optimizer code is generated at GCC build time. A simplification takes the form of:

    (simplify <expression> <simplified_expression>)

    An example from the GCC Internals manual is:

    (simplify
      (bit_and @0 integer_all_onesp)
      @0)

    Items in this language are combined through Polish or prefix notation (along with a parenthesis-delimited syntax suspiciously reminiscent of Lisp). The bit_and prefix represents the && that appears between expressions in C, but here bit_and appears before the two expressions instead of between them.

    This domain-specific code declares a simplification where the bitwise AND of any operand (captured as @0) and "all ones" (i.e., 0xFFFFFFFF) is equivalent to the operand @0 itself. integer_all_onesp is a predicate that returns true for any operand that has all of its bits turned ON.

    After looking around in match.pd for inspiration, I could easily see that operations can be nested inside other operations, and that GCC will gladly accept, match, and simplify them. For the optimization I wanted to implement, the initial expression would be something like:

    (bit_and (gt @0 @1) (eq @1 integer_zerop@2))

    integer_zerop is another predicate, matching integers with the value 0. The @2 captures the operand so that it can be reused during the simplification if needed.

    The optimized expression should look a bit like:

    (bit_and (gt @0 ZERO) (eq @1 @2))

    At this point, I didn't know how to emit 0 in the resulting expression. But once again, reading match.pd gives the idea that build_zero_cst (some_type) probably translates to a 0 value of the given type. Also, TREE_TYPE (@0) returns the type of operand @0. Combining these constructs leads to a simplified expression that GCC is likely to grok:

    (bit_and
      (gt @0 { build_zero_cst (TREE_TYPE (@0)); })   (eq @1 @2); }))

    Putting all of this together, the final declaration of the simplification is:

    /*  (x > y) && (y == 0)  ->  (x > 0) && (y == 0)  */
    (simplify
      (bit_and (gt @0 @1) (eq @1 integer_zerop@2))
      (bit_and (gt @0 { build_zero_cst (TREE_TYPE (@0)); })
               (eq @1 @2)))

    Adding this declaration to match.pd and compiling it was all I needed to do to insert the necessary change into generated code. Now, let's see whether the change was truly an optimization.

    Did it work?

    Before I added the declaration, the following C code:

    bool
    f(int x, int y)
    {
      return x > y && y == 0;
    }

    translated (on x86-64) to:

    f:
      cmpl    %esi, %edi # compare X and Y
      setg    %al        # set AL if X gt Y
      testl   %esi, %esi # test Y
      sete    %dl        # set DL if Y eq 0
      andl    %edx, %eax # AL and DL
      ret

    After adding the declaration, GCC produces:

    f:
      testl   %esi, %esi # test Y
      sete    %al        # set AL if Y equals 0
      testl   %edi, %edi # test X
      setg    %dl        # set DL if X gt 0
      andl    %edx, %eax # AL and DL
      ret

    The change breaks the input dependency, as I hoped, and brings the code in line with what Clang/LLVM generates.

    Conclusion

    Although my learning curve—from never having looked at match.pd or tree optimizations to having hacked together my first optimization—was a bit steep, I found it was relatively easy for a beginner to implement a minor tree optimization using GCC's "Match and Simplify" infrastructure.

    I have yet to properly test this new pattern, and there's possibly a fatal flaw in my approach. Also, there are several open questions, such as whether there is a more general pattern that optimizes for constants other than 0 and comparisons other than "greater than." I hope to answer these questions before I try submitting my very first patch. In the meantime, I'm happy to report that beginners can indeed quickly work toward their first contribution to GCC.

    Happy hacking!

    Last updated: September 27, 2024

    Related Posts

    • Open Source Contributor Experience

    • Red Hat Enterprise Linux 8.3 supports faster service and workload delivery

    Recent Posts

    • A day in the life of an NVIDIA H100 on Red Hat OpenShift 5

    • Migrate BuildConfigs to builds for Red Hat OpenShift with one plug-in install

    • Run Red Hat Enterprise Linux CoreOS on NVIDIA BlueField DPUs

    • Agent harness engineering: Separating model capabilities from enforcement

    • What's new for developers in Red Hat Enterprise Linux 10.3 and 9.9

    Red Hat Developers logo

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    Red Hat Developer

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility
    Ask AI