r/programming • • May 30 '17

Compiler Optimizations are Awesome

https://blog.regehr.org/archives/1515
146 Upvotes

97 comments sorted by

84

u/slavik262 May 31 '17

Do people seriously make arguments that compiler optimizations aren't useful? Have they ever looked at the assembly compilers emit without optimizations enabled? It's incredibly bad.

Also, anybody who quotes Knuth as saying,

We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil.

without the sentence that immediately follows:

Yet we should not pass up our opportunities in that critical 3%.

is either misinformed or disingenuous.

52

u/TNorthover May 31 '17

In general I agree completely, but Daniel Bernstein is working in a very particular niche: cryptography. For him two particular issues some together to make optimizing compilers The Devil.

First, inner cryptographic loops are generally hot enough that people are willing spend days and weeks making them as fast as possible. A compiler won't be able to match that.

Second, crypto is particularly vulnerable to compiler optimizations breaking naive assumptions. Compilers can give code you expect to execute in constant time a variable execution time; on average this is better (we hope), but just that variability can be exploited by attackers. Compilers can also remove checks they decide aren't valid; the original code would have been violating the language standard, but that's of scant comfort if your primary concern is security and someone manages to hijack a bank account because of it.

What cryptographers seem to want most of all is predictability. This doesn't correspond to most people, so in general I strongly agree with John. But I have some kind of sympathy for Daniel.

34

u/slavik262 May 31 '17

crypto is particularly vulnerable to compiler optimizations breaking naive assumptions.

This is true, but the correct solution is not to make those assumptions. Undefined behavior is a tricky problem (and one can easily argue that C and C++ make it trickier than it has to be), but there are good reasons it exists. Chandler Carruth has a great talk on this (UB, troubles crypto authors have with it, why it exists, and what tools are being made to mitigate it).

Compilers can give code you expect to execute in constant time a variable execution time; on average this is better (we hope), but just that variability can be exploited by attackers.

Unfortunately, there's little you can do about this, even if you're writing assembly. Modern desktop CPUs are essentially virtual machines that translate x64 on the fly into the micro-operations they use. Combine this with the effects of store buffers, cache misses, etc., and it's really difficult to get predictable timing.

12

u/loup-vaillant May 31 '17

the correct solution is not to make those assumptions.

This is blaming the victim. Undefined behaviour in C and C++ has gone utterly insane, you know. Signed integer overflow for instance: because some platforms can't handle it, the standard made it undefined for all platforms. Then compiler writers took advantage of this, effectively turning after-the-fact overflow checks into actual vulnerabilities.

C and C++ were supposed to be close to the machine. Can we really blame the programmer from reasoning like an electrical engineer, and assume that because X86 handles integer overflow just fine, the language should do so as well?

Chandler Carruth has a great talk on this

He downplays UB so much that's almost criminal. The hard fact is, UB sometimes does trigger catastrophes such as formatting all your hard drive, or the encryption of all your files. Some UB lead to vulnerabilities, arbitrary code execution, and malware mayhem. Even those who don't right now might cause similar problems later, as optimisers exploit more and more UB from the standard.

I'm not against UB, but the current C and C++ standard have gone way too far.

it's really difficult to get predictable timing.

Fortunately, we rarely need that much. In cryptography for instance, we don't need predictable, or even constant-time timings. We want those timings to be independent from secrets. And on modern processors, this just means no secret-dependent branch, and no secret-dependent indexing. On less modern processors, you also have to be wary of modular multiplication (this only affects public key crypto), and arithmetic shifts (without a barrel shifter, the timings depend on the magnitude of the shift).

And of course, compiler optimisations: if GCC suddenly detects that your constant-time string comparison function could if fact stop early, it is allowed to do so, and throw your security out the window. Fortunately, it doesn't yet do so.

3

u/mcmcc May 31 '17

Signed integer overflow for instance: because some platforms can't handle it, the standard made it undefined for all platforms.

How would you define the outcome of signed integer overflow? How would that definition make code that (inadvertently) induces signed integer overflow better?

5

u/loup-vaillant May 31 '17

How would you define the outcome of signed integer overflow?

I don't. Processors do. And they pretty much all agree on a 2's complement representation. When they overflow, they wrap around just like unsigned modular arithmetic. There are some rare exceptions, but we can safely ignore them in most contexts.

An example where standardising that behaviour would help is delayed carry propagation in big numbers arithmetic, where the limbs may be negative. Last time I checked, the SUPERCOP benchmarks for curve25519, as well as tweetNaCl, had some signed integer left shift arithmetic, where those integers are sometimes negative. This left shift is undefined whenever the integer is negative. To fix this, I convert the numbers to unsigned (this assumes a 2's complement representation). Not fully portable, but it doesn't matter in practice. I'm more annoyed by the slight verbosity induced by the explicit conversion.

Another example is overflow checks in general. It is easier to check for overflow after the fact than ensure the overflow won't happen at all beforehand. Since signed overflow is undefined, the compiler is allowed to assume it does not exist, and treat the check as always false, effectively deleting it. And it does. Yeah, yeah, shame on the bad programmer from relying on undefined behaviour. Still, it is a bit surprising that C of all languages doesn't match the behaviour of the platform.

Now if you insist on code that inadvertently overflows, well, that's a logic error to begin with. But that's besides the point anyway.

4

u/mcmcc May 31 '17

But that's besides the point anyway.

It is? What is the point then?

Are you're suggesting code is intending for signed overflow to occur? I submit 99.9999% of all integer arithmetic code out there was not designed with signed overflow in mind -- therefore, how overflow is defined (or not) is irrelevant to that code. It is a condition that was never designed for either way. For the tiny percentage of code out that is designed to overflow, they could just as easily explicitly manage the overflow logic by hand and not depend on the compiler to infer their needs (which may very well not agree with what the hardware does anyway).

So either you give the compiler writers freedom to optimize the code as they see fit or you pander to the 0.00001% of code that is deeply concerned about this condition in the first place. Choose your poison.

That said, it would be nice if the compiler were able to offer better warnings when suspicious code is encountered but that's a whole field of study onto itself.

3

u/loup-vaillant May 31 '17

Are you're suggesting code is intending for signed overflow to occur?

Yes. That's why they check for the overflow after the fact. Code that inadvertently overflows don't make that check, and instead produces wrong results whenever that happens.

For the tiny percentage of code out that is designed to overflow, they could just as easily explicitly manage the overflow logic by hand

Possible, but not obvious. You can convert the numbers to unsigned, then perform the operation, then convert back. It's cumbersome. You could perform a clever test before the operation is even performed, but that's not always easy.

Also, those checks are often security checks, that when not performed could lead to buffer overflows and arbitrary code execution.

So either you give the compiler writers freedom to optimize the code as they see fit or you pander to the 0.00001% of code that is deeply concerned about this condition in the first place. Choose your poison.

Compiler writers clearly have: they will exploit every bit of undefined behaviour out there, no matter unintuitive, no matter the original reason for it. (Signed integer overflow is the canonical example: unlike strict aliasing, it was undefined for portability reasons, not for performance reasons.)

And if someone in the standard committee wants to define a previously undefined behaviour, the compiler writers will moan about their lost optimization opportunity, especially if they were exploiting it.

That said, it would be nice if the compiler were able to offer better warnings when suspicious code is encountered

They can't, optimization happens too late in the compilation process. Most compilers start with a very dumb front end, that generates horrible intermediate code. The optimiser then munges the hell out of that intermediate code to get something lean and/or fast. Warning the user about fishy dead code (because of a UB assumption) is very difficult at this stage, because it cannot reliably tie the source code to any particular piece of heavily optimised intermediate code. Moreover, that dead code may have come from the dumb front end, not from the source code.

2

u/mcmcc May 31 '17

Possible, but not obvious.

And your proposal only makes it slightly more obvious. It doesn't actually fix any problems, in a general sense.

it was undefined for portability reasons, not for performance reasons.

These are effectively one and the same -- in order to conform to such a standard (i.e. to make it portable), some compilers would have to emit non-optimal code (making it a competitive advantage for the platforms where the natural output is conforming).

So it begs the question: What is the point of all of this when the proposed defined behavior is arithmetically meaningless and inhibits generally meaningful optimizations?

2

u/loup-vaillant May 31 '17

I don't recall ever talking about arithmetically meaningless behaviour. Wrapping around signed integers is plain old modular arithmetic.

→ More replies (0)

2

u/evaned May 31 '17

I would say there's a big difference between code made incorrect because it wraps around (because the language defines it that way) and code made incorrect because the compiler decided there was UB and it can go and optimize away some other piece of unrelated code.

Both are bad, but the latter seems far worse.

1

u/industry7 May 31 '17

How would you define the outcome of signed integer overflow? How would that definition make code that (inadvertently) induces signed integer overflow better?

Make it signal. That makes code better b/c you can now handle the error case consistently across platforms.

Alternatively, a sufficiently advanced type system could enforce compile time restraints in such a way that unmitigated potential overflows won't compile.

There's a lot of different ways that a language could handle this situation.

2

u/mcmcc May 31 '17

Make it signal.

Hardware vendors' collective heads would explode.

a sufficiently advanced type system

... would be unwieldy. Languages have tried this and you find yourself working around the type system. Sometimes (often) numbers are just numbers.

1

u/industry7 Jun 01 '17

... would be unwieldy. Languages have tried this and you find yourself working around the type system.

Maybe you find yourself working around advanced type systems, but I generally find the more advanced the type system the more my productivity is enhanced.

Sometimes (often) numbers are just numbers.

Until they under/over-flow and/or the compiler decides to optimize away important part of your program, and then it's a huge problem in addition to being "just numbers".

0

u/mcmcc Jun 01 '17

I'll ask again, what general problem does defined signed overflow actually solve?

Read the other branches in this thread for context.

1

u/industry7 Jun 01 '17

How would that definition make code that (inadvertently) induces signed integer overflow better?

I'll ask again, what general problem does defined signed overflow actually solve?

The general problem is undefined behavior... Defining the behavior fixes the problem... by defining the behavior.

What's your question again?

→ More replies (0)

1

u/Zarutian Jun 01 '17

Hardware vendors' collective heads would explode.

Really? Have you looked at the Carry bit in the status registers of most CPUs?

12

u/sigma914 May 31 '17 edited May 31 '17

This suggests C is the wrong tool for writing cryptographic code. Perhaps we should be using a language specially designed for crypto that generates asm that can be treated as a black box by whatever compiler links it in.

2

u/__Cyber_Dildonics__ May 31 '17

That is actually a very good point. Does that mean specific classes in C++ that do everything right, or something else all together?

3

u/loup-vaillant May 31 '17

DJB did exactly that. That said, I'm not aware of any remotely mainstream language that has all the requirements.

8

u/Dragdu May 31 '17

Can we really blame the programmer from reasoning like an electrical engineer, and assume that because X86 handles integer overflow just fine, the language should do so as well?

That depends, are we okay with then porting his "perfectly valid" code to different platform, and having it die horribly there?

What if it is crypto?

Ironically, this is the reason why the often advocated "just make X implementation defined, instead of undefined" wouldn't work for signed overflow, it would just hide the problem when running on an x86.

3

u/mcguire May 31 '17

"All the world is a VAX."

1

u/industry7 May 31 '17

Ironically, this is the reason why the often advocated "just make X implementation defined, instead of undefined" wouldn't work for signed overflow, it would just hide the problem when running on an x86.

Do you mean, "Let's just make signed overflow defined for the x86 platform", or do you mean "Let's just make signed overflow defined in the language"? Or something else?

To me, the second one is the correct answer for any security related software (like crypto).

7

u/loup-vaillant May 31 '17

That's the problem with the damn standard, there is hardly such a thing as "undefined on some platforms, implementation defined on others". It's either:

  • Portable: same behaviour on all platforms

  • Implementation defined: behaviour might differ between platforms, but it always works)

  • Undefined: it is allowed to blow up in your face on any platform.

The reasonable thing to do would be to define signed overflow on platforms that behave consistently, and keep it undefined on others. But then Chandler Carruth would barge in and cry about his lost opportunities for optimizations.

5

u/Dragdu May 31 '17

Implementation defined means that each implementation (where implementation is a bit nebulous, but basically think of it as combination of specific compiler with specific platform (which itself is OS + actual arch)), defines what happens and has to respect it, but no commonalities are actually required.

It would mean that say GCC on x86 Linux could define signed int overflow as actually overflowing, but Clang on x86 Linux could define signed int overflow as launching nuclear missiles and both would be correct according to standard.

2

u/industry7 Jun 01 '17

where implementation is a bit nebulous, but basically think of it as combination of specific compiler with specific platform (which itself is OS + actual arch)

Thanks, this is the part where the standard seemed a little vague to me. So like I wasn't sure if GCC on x86 Linux counts as the same or separate implementation as GCC on x86 Windows. If GCC says they support both platforms, does that mean you can expect consistency between both platforms? What about from version to version? Is each version of an implementation considered by the standard to be an entirely separate implementation, and therefore "implementation defined" behaviors can vary wildly from version to version?

So I guess the answer is, vendors can do pretty much whatever they want.

3

u/loup-vaillant Jun 01 '17

"implementation defined" behaviors can vary wildly from version to version?

Yes, but consistently so: each platform is required to precisely define the behaviour. While launching the nukes is strictly speaking permitted by the standard, that behaviour must be documented. It won't even launch the nukes by surprise.

This is quite different from undefined, which can trigger anything, without having to document it (the proverbial nasal demons).

3

u/millenix May 31 '17

It's possible to specify in C and C++ exactly the non-optimization necessary to make strncmp, memcmp, etc behave correctly: https://stackoverflow.com/questions/25373767/optimization-stable-constant-time-array-comparisons/25374036#25374036

2

u/loup-vaillant May 31 '17

Thanks, I'm going to use it right away.

3

u/mcguire May 31 '17

C isn't especially close to the machine, not any more.

C++, however, is not close to the machine, in any way, shape, or form. Think of templates without massive optimization. Anyone remember the 90s? (BRB, I have to go make a hello world comparison.)

The bottom line is that we have 3 issues:

  1. Generate fast code.

  2. Be portable.

  3. Generate cryptologically consistent code.

Pick any two.

C choose the first two, because it was defined by compiler vendors who were competing I code speed for their individual platforms. It would be reasonable to pick others, but C isn't it.

But since C appears to be the only language choice, it has to be cryptographers' responsibility to make sure stuff ain't broke because they are outnumbered by the rest of us getting the benefits of C's choices.

2

u/loup-vaillant May 31 '17

[cryptographers] are outnumbered by the rest of us getting the benefits of C's choices.

There's just one tiny little problem: cryptographers are more important than much larger groups of programmers. Their vote should have more weight.

More than anything, crypto code tend to be written once and used everywhere. And we don't want it to break because compilers suddenly start to optimize differently.

At some point's it's compiler dev's responsibility to make sure the new version of their compiler doesn't break crypto code. (And if it ever does, I bet my hat insults will fly.)

2

u/jms_nh May 31 '17

not just cryptographers, also embedded control systems designers

1

u/mcguire May 31 '17

More important? Maybe. You could certainly make that argument. The more academic parts of the standards community would certainly like it.

In fact, at this point the situation is better than it ever had been; nothing but x86 and ARM really matters, and you just have two projects to convince: gcc and clang.

But I do have to complain about your use of 'break'. 'Breaking' crypto might involve adding a feature that improves everyone else's life 100×.

2

u/loup-vaillant May 31 '17

Since crypto code tend to be fully compliant, the only thing that can really break are timings. That means optimizations that significantly alters the originals algorithms so they use secret dependent indexing or secret dependent branches even though the original algorithm didn't require them.

C and C++ (yes, even C++17 with all the new bells and whistles) are low level languages. They're no longer as close to the metal as they once were, but they still require the programmer to manage memory —even the layout of data. They're not supposed to find clever tricks like Haskell to run faster. And if they do, they're likely to make things much worse in some cases.

I doubt this could make everyone's life 100 times better. If you want to write high level code, just use a high level language.


More important? Maybe.

Just ponder the consequences for a second: killing strong crypto would basically kill the internet —or at least your ability to order anything online. No one will ever allow that to happen, the money is too big.

2

u/jms_nh May 31 '17

There are an awwwwful lot of embedded processors out there which aren't x86 or ARM. (billions of Microchip PICs and TI DSPs/MSP430s just to name two companies)

1

u/Zarutian Jun 01 '17

Pick any two.

Pick any one, you mean?

2

u/mcguire Jun 01 '17

In many cases, it's 'pick none '.

1

u/jms_nh May 31 '17

^^

I'm too cheap to give reddit gold but I would if I could. :-)

15

u/hegbork May 31 '17

The biggest optimization problem with crypto isn't UB. That's pretty trivial to avoid and a very minor problem at most for a long time. The biggest problem with crypto is dead store optimizations, vectorization and various heuristics that convert constant time operations into non-constant time.

Let's take dead store optimizations. A clever compiler knows that in memset(x, 0, sizeof(*x)); free(x); the memset is useless. From the point of view of the standard the contents of x can never be observed so there is no reason to set them to 0. The problem is that an attacker isn't obliged to follow the standard so you want to wipe your secrets from memory as soon as possible unless you want to repeat heartbleed.

Look in LibreSSL how many hoops and iterations explicit_bzero had (it's not obvious from the repository because the function has moved around, but poke around in OpenBSD libc where it came from) before it was found to actually not be optimized out by some compiler in some situation (by testing all combinations they could think of and checking the results by hand which is no proof at all). The function is completely filthy right now and there is still nothing that prevents it from being broken by the next minor version of any compiler. The last bug was when some linker figured out the dead stores during link time optimization when the code it was dealing with wasn't even C anymore (LTO might have eaten the function even if it was hand-written in assembler, probably not today, but it's not impossible in the future).

Amusingly enough, memset_s from C11 appendix K is supposed to do the same thing as explicit_bzero, except that no one has ever implemented it correctly because it is pretty much impossible to implement it correctly without serious help from the compiler and compiler people don't give a fuck about some controversial functions from an appendix.

DJB has a point. As usual he's throwing the baby out with the bath water, but he does have a point. I don't think we can live without compiler optimizations, but there need to exist reliable methods to tell compilers, linkers, virtual machines, etc. to stop being clever with a piece of code.

For your second point. As far as I know there has never been an attack that targeted uops for timing information, so we're still fine there.

5

u/zvrba May 31 '17 edited May 31 '17

DJB has a point. As usual he's throwing the baby out with the bath water, but he does have a point. I don't think we can live without compiler optimizations, but there need to exist reliable methods to tell compilers, linkers, virtual machines, etc. to stop being clever with a piece of code.

Regehr had an article about "friendly C", and a follow-up article about having lost faith in it ever going to happen due to $reasons: https://blog.regehr.org/archives/1287

I guess the only way forward here is another systems language that willingly gives strong guarantees about the generated code at the cost of performance. Even this is far less trivial than it appears, for example, when should the compiler be allowed to coalesce four 8-bit writes to adjacent locations into a single write? Should all memory writes be treated as "volatile" (in the C meaning of the word) accesses?

Would Rust fit the bill?

5

u/mcguire May 31 '17

Would Rust fit the bill?

Nope. Not as it stands, anyway.

Rust is built on the current top of the line optimization framework, llvm. It's also designed to provide C++ level abstractions.

7

u/steveklabnik1 May 31 '17

Today's Rust in general would not, absolutely.

However, making Rust good for crypto is something we'd like in the future; we may or may not be able to help here. But that's far-future work.

Right now it's "write the stuff you need to be exact in asm and link it in."

0

u/sstewartgallus May 31 '17

memset_s is a garbage idea. Processors and compilers provide absolutely no guarantees about not caching the data. If you want the data not to be cached somewhere then separate it out into a separate process or even a separate processor.

4

u/mr_birkenblatt May 31 '17

it's not necessarily undefined behavior. for example, in crypto you don't want information lingering around so you zero out buffers after use. a compiler can detect that you're not reading the buffer after writing the zeros so it might decide that writing the zeros are not necessary (because you're not supposed to be able to tell the difference)

2

u/TNorthover May 31 '17

I absolutely agree. One of the advantages of C and C++ is that you know exactly what you're signing up to when you start writing. It may not be what you prefer, but compared to many other languages what you get really is defined.

Combine this with the effects of store buffers, cache misses, etc., and it's really difficult to get predictable timing.

It's difficult, but I understand people have managed to produce useful hardenings w.r.t. CPU executions. Mostly I think it comes down to load-> predictable arithmetic -> store.

3

u/Sean1708 May 31 '17

compared to many other languages what you get really is defined.

Could you give an example? C has far more undefined behaviour than any language I know of.

1

u/TNorthover May 31 '17

I mainly meant that I prefer languages with specifications over ones with a reference implementation. I wasn't very clear though.

In principle everyone can agree on whether a C++ program is valid, and how it should behave if so. It's trickier to pin down whether some Python behaviour is because that's how CPython does it now, or because it's really intended to be like that forever.

Not that I think Python's bad. I just happened to see an example there recently over the behaviour of __del__ (in the talk about removing the GIL).

1

u/Sean1708 May 31 '17

Ah yeah, that's fair enough.

-3

u/sstewartgallus May 31 '17

Chandler Carruth's talk on this is garbage.

My reasons for why undefined behaviour is mostly a garbage idea:

  • Undefined behaviour based optimizations cause millions of dollars worth of security vulnerabilities

  • Most people write code in shit like Java anyway. Undefined behaviour based optimizations aren't required for the vast majority of people.

Chandler Carruth's reasons for why undefined behaviour is good:

  • It's a contract between users of the language and compiler writers and the users simply aren't following it.

Guess what. The vast majority of programmers are as to proper software development as the human brain is to a cancerous mass of worms and maggots. Nobody follows the contract because most programmers are shit.

9

u/Works_of_memercy May 31 '17

In general I agree completely, but Daniel Bernstein is working in a very particular niche: cryptography. For him two particular issues some together to make optimizing compilers The Devil.

But that's the problem, isn't it? He has a very specific idea of how a "typical program" looks like, informed by his experience, and apparently it looks like 10%/90% of the code taking 90%/10% of the run time respectively, so he wants to be able to hand-optimize that 10% of the code and doesn't care about that 10% of the time at all.

Well, good for him, but there are also cases where 90% of the consist of boring business logic and also takes 90% of the time, so we actually want the compiler to optimize it passably. And everything in between.

I mean, I agree with the thesis that it would be very nice to have a programming language that allows you to smoothly get down to lower level primitives in your hot loops. I've been wishing for exactly that myself, when working with a couple long-running SQL statements for data migration/transformation that I'd really prefer to express using the same concepts explain plan used directly, instead of massaging SQL and adding hints and whatnot until what I see there looks acceptable. That's just a backward waste of time.

But on the other hand I really enjoy leaving it to the RDBMS for the rest 98% of the SQL statements I write, that take more than the other half of time to execute. Because I don't have the time to hand-optimize them all, and I definitely don't have the time to make several hand-optimized versions and switch between them based on collected statistics.

12

u/zvrba May 31 '17

Compilers can also remove checks they decide aren't valid; the original code would have been violating the language standard,

So... using the wrong tool (language) for the job? EDIT: if you must write code that violates the standard in order to get the job done, then you're using the wrong tool. Don't blame the compiler for doing what users want it to do (i.e., producing the fastest code possible).

2

u/evaned May 31 '17

if you must write code that violates the standard in order to get the job done, then you're using the wrong tool

People don't generally write that code on purpose, you know.

5

u/Chii May 31 '17

what the original comment meant is that you ought to be using a provable language to write code that needs to be provable.

0

u/[deleted] May 31 '17

[deleted]

1

u/[deleted] May 31 '17

Just bloody write the right tool then.

0

u/[deleted] May 31 '17

[deleted]

3

u/[deleted] May 31 '17

Ok, say I do that, how do I get people to use it?

What people? You and your team have to use it. To write your crypto code. Nothing else.

C or C++ is about all that's left.

Not any more. There are lower level yet portable options available now.

1

u/zvrba Jun 01 '17 edited Jun 01 '17

Few people who write things in C do it because they love the shit out of C.

Then they're living in a state of cognitive dissonance. They love C, complain about compilers' "deficiencies" and UB etc, but refuse to see that they're actually complaining about C itself because that's what the compiler implements. EDIT: I misread your sentence. I parsed the subject as (Few people who write things in C) instead of (Few people)

They do it because they want their project to actually be used.

You don't need to write something in C in order to provide C linkage. Microsoft has solved this problem with COM decades ago. COM allows you to call binary-only components from whichever language you want, as long as you implement a tiny glue layer (basically a vtable mechanism; struct with function pointers).

10

u/Gotebe May 31 '17

What if I rephrase the second point to "if I make wrong: assumptions, optimizer might break my code"?

Say, using memset to wipe out memory after use. Well, just don't, use the dedicated function, which the crypto library offers.

Also, I dislike the point that the optimizer changes the speed - yes, but so does the CPU itself, as well as the rest of the system.

tl;dr: better deal with the complex world than take questionable shortcuts.

2

u/laccro May 31 '17

Very informative. Thanks!

1

u/BonzaiThePenguin May 31 '17

Compilers can give code you expect to execute in constant time a variable execution time; on average this is better (we hope), but just that variability can be exploited by attackers.

How so? I thought it was the constant-time execution that could be exploited by attackers, as the length of execution leaks information about the amount of work that the algorithm performed before failing out.

7

u/YourGamerMom May 31 '17

You're correct in a way, but switched up constant and variable time. If the function always evaluates in the same time (constant) then info about how much work was performed doesn't leak.

1

u/BonzaiThePenguin May 31 '17

Oh I thought we were talking about constant time per instruction rather than the entire algorithm.

2

u/ThisIs_MyName May 31 '17

Variable instruction timing is silly, it only adds a few bits of security. The attacker can just average them out.

0

u/[deleted] May 31 '17

It is exceptionally idiotic to write any crypto code in any "general purpose" language, to start with.

0

u/[deleted] May 31 '17

[deleted]

6

u/TNorthover May 31 '17

It's mostly there to optimize for debugging.

Even the most trivial cleanups can discard local variables at inopportune moments. People are thinking about modes which actually do some optimization without compromizing debugging now, but it's early stages.

9

u/Boojum May 31 '17

GCC offers -Og for this now.

3

u/ismtrn May 31 '17

My limited experience with writing a compiler is that in many cases it is a lot easier to spit out really silly assembler code and then do simple optimization on it. For example you always assume that a value is not were it is supposed to be and move it there first, which ends up with a lot of moving a value around so it ends up were it started. In this way when you generate code there are less special cases. Then afterwards it is fairly simple to run through the assembly code and remove redundant move instructions.

9

u/t0rakka May 31 '17

The value of optimizing compiler is that you can write reasonable code and not by default expect it to result in completely garbage machine code. There is a symbiosis between experienced programmer and a compiler; the programmer will know how specific idioms will behave when translated into machine code. This is however on-going process because what you "know" has to be updated periodically. This causes "code rot" which means old code begins to stink - it is written with specific idioms and patterns that obfuscate the intent the programmer had in mind when he crafted the code in the first place.

The code that survives the test of time best is simplest possible code to solve a specific problem.

Meanwhile in the real world computers have finite performance and code has to be fast enough to get the job done. Number of CPU cores has been stuck to ~4 cores on mainstream desktop for a long while now. There is a change coming in the near future to this which means more multi-threading which means more complicated code. Clarity of expressing our intent will be more important than ever. I welcome the awesome compiler optimizations. :)

6

u/[deleted] May 31 '17

Second, size matters. Most of the computers in the world are embedded and many of these are storage-constrained. Compiler optimization reduces code size and this phenomenon is completely independent of the hot/cold issue.

I wonder if he has numbers to back this up, that optimizations reduce code size compare to naive compiling. If we compile

int factorial(int x) {
    return x > 1 ? x * factorial(x-1) : 1;
}

With no optimizations (on my particular version of GCC, which is 7.0 from git not that long ago) we get

_Z9factoriali:
.LFB0:
    .cfi_startproc
    push	rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    mov	rbp, rsp
    .cfi_def_cfa_register 6
    sub	rsp, 16
    mov	DWORD PTR [rbp-4], edi
    cmp	DWORD PTR [rbp-4], 1
    jle	.L2
    mov	eax, DWORD PTR [rbp-4]
    sub	eax, 1
    mov	edi, eax
    call	_Z9factoriali
    imul	eax, DWORD PTR [rbp-4]
    jmp	.L4
.L2:
    mov	eax, 1
.L4:
    leave
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc

If I compile with -O3 I get

_Z9factoriali:
.LFB0:
    .cfi_startproc
    cmp	edi, 1
    jle	.L7
    lea	eax, [rdi-2]
    lea	ecx, [rdi-1]
    cmp	eax, 7
    jbe	.L8
    mov	DWORD PTR [rsp-12], edi
    mov	edx, ecx
    xor	eax, eax
    movd	xmm5, DWORD PTR [rsp-12]
    shr	edx, 2
    movdqa	xmm0, XMMWORD PTR .LC0[rip]
    pshufd	xmm2, xmm5, 0
    movdqa	xmm4, XMMWORD PTR .LC2[rip]
    paddd	xmm2, XMMWORD PTR .LC1[rip]
    .p2align 4,,10
    .p2align 3
.L4:
    movdqa	xmm3, xmm2
    add	eax, 1
    movdqa	xmm1, xmm2
    cmp	eax, edx
    paddd	xmm2, xmm4
    pmuludq	xmm3, xmm0
    psrlq	xmm0, 32
    psrlq	xmm1, 32
    pmuludq	xmm1, xmm0
    pshufd	xmm0, xmm3, 8
    pshufd	xmm1, xmm1, 8
    punpckldq	xmm0, xmm1
    jb	.L4
    movdqa	xmm2, xmm0
    mov	edx, ecx
    movdqa	xmm1, xmm0
    psrlq	xmm0, 32
    and	edx, -4
    psrldq	xmm2, 8
    sub	edi, edx
    cmp	ecx, edx
    pmuludq	xmm1, xmm2
    psrlq	xmm2, 32
    pshufd	xmm1, xmm1, 8
    pmuludq	xmm0, xmm2
    pshufd	xmm0, xmm0, 8
    punpckldq	xmm1, xmm0
    movdqa	xmm0, xmm1
    psrldq	xmm1, 4
    pmuludq	xmm0, xmm1
    movd	eax, xmm0
    je	.L1
    lea	ecx, [rdi-1]
.L3:
    imul	eax, edi
    cmp	ecx, 1
    je	.L1
    lea	edx, [rdi-2]
    imul	eax, ecx
    cmp	edx, 1
    je	.L1
    lea	ecx, [rdi-3]
    imul	eax, edx
    cmp	ecx, 1
    je	.L1
    lea	edx, [rdi-4]
    imul	eax, ecx
    cmp	edx, 1
    je	.L1
    lea	ecx, [rdi-5]
    imul	eax, edx
    cmp	ecx, 1
    je	.L1
    lea	edx, [rdi-6]
    imul	eax, ecx
    cmp	edx, 1
    je	.L1
    imul	eax, edx
    sub	edi, 7
    imul	eax, edi
    ret

Sorry for the wall of text.

23

u/TNorthover May 31 '17 edited May 31 '17

It depends what you tell the compiler. Especially, "-O3" tells the compiler to aim for performance no matter what the size penalty is. It may or may not succeed, but a line-by-line dump doesn't argue either way.

Both GCC and Clang produce more compact code with "-Os" (optimize for size, though they both interpret that differently too).

2

u/[deleted] May 31 '17

To be clear I'm not saying optimizations can't create more compact code, that's obviously false (and while I've never measured I am reasonably confident -Os does a reasonable good job at it). I just wonder whether or not the normal optimizations gcc/clang run actually end up creating more compact code or not.

8

u/TNorthover May 31 '17

That's definitely worth worrying about. I can't speak for GCC, but Clang interprets -Os as "go fast but don't unnecessarily bloat code". Generally it ought to be a decent balance, but that definition is so hand-wavy as to be meaningless.

If you use -O2 or -O3, clang will assume you don't care about code size.

In either case it's not possible to work out what actually results in smaller code in general. For example you can come up with small functions that may or may not be worth inlining. Just tiny changes in the rest of the program can make a function better standalone or better inlined (or better inlined sometimes).

7

u/masklinn May 31 '17

If you use -O2 or -O3, clang will assume you don't care about code size.

That's true for O3, but not for O2. O2 is "try to strike a good balance", Os is based on O2 but may disable some optimisations which "typically increase code sizes" and enable some optimisations specifically designed to reduce code size.

In Clang, Os is identical to O2, and has been for years (since at least 3.2).

5

u/[deleted] May 31 '17

You seem like the sort of person who might be able to answer this.

I only have a surface knowledge of optimization, but something that is repeatedly a lot these days is that making data small/fit in cache is pretty much the most important thing you can do. Why doesn't increasing code size go against that?

14

u/evaned May 31 '17

something that is repeatedly a lot these days is that making data small/fit in cache is pretty much the most important thing you can do. Why doesn't increasing code size go against that?

Not the person you're replying to, but... it does. Just one of many things that the compiler has to weigh, and why optimization is haaard.

But everything is a tradeoff, right? For example, maybe the compiler enlarges a performance-critical section of code that's executed repeatedly, but even the enlarged version still fits into the cache (so there's no hit while it's running) and whatever optimizations made it larger helped more during its processing than the extra cache pressure cost.

There are also optimizations that will often help but sometimes hurt, but the compiler can't tell when each will happen; but because they help more than they hurt, it applies them.

Finally, I don't have concrete data to back this up, but I suspect that data cache locality matters more than instruction cache locality, in the sense that it's much easier to blow your data cache than instruction cache. This guess is based on the fact that most (longer-lived) programs have much more data than code. Even extremely large programs have "only" a couple hundred MB of code,1 but will often operate on GBs of data. I also suspect it's much more common for a relatively tight loop to walk over a huge amount of data than it is for a small amount of data to be accessed by an enormous amount of code in sequence.

1 For example, Chrome running on my system seems to have around 250 MB of executable memory (I got that via cat /proc/2230/maps | grep r-x | cut -d" " -f1 | sed 's/^\([0-9a-f]*\)-\([0-9a-f]*\)$/0x\2-0x\1/' | tr '\n' '+' and evaluating that expression), but apparently something like 6 GB (!) of virtual address space used, 933 MB of which is resident.

5

u/AlotOfReading May 31 '17

Like everything else in optimization, it depends heavily on the particulars. Some optimizations like loop unrolling force you to make a choice between smaller and faster, although the degree of both depends on the code preceding the immediate assembly, as well as where the code is in memory and the system state.

5

u/ThisIs_MyName May 31 '17 edited May 31 '17

Why doesn't increasing code size go against that?

Sometimes -Os results in faster code than -O2 for exactly this reason. Compiler flags like "funroll-loops" are also a meme for this reason.

Another issue is that optimizations that increase code size do very well on naive benchmarks because most benchmark executables are small enough to always fit in the cache. Real binaries don't.

In most cases however, -O2 is faster.

1

u/doom_Oo7 May 31 '17

Sometimes -Os results in faster code than -O2 for exactly this reason.

in any remotely recent benchmark it's not the case

4

u/[deleted] May 31 '17

The most code fattening optimisations are inlining and loop unrolling. While they are obviously damaging cache locality, they are enabling potentially many other optimisations and therefore worth trying. If your cost model is reasonable, you can balance code size vs. the effects of a better vectorisation, specialisation, constant propagation, etc.

17

u/zoells May 31 '17

What about with -Os?

5

u/holgerschurig May 31 '17 edited May 31 '17

Much, much smaller, albeit compiled with a much older gcc:

$ gcc-4.9 -Os -c -o fact.o fact.c
$ objdump -d fact.o 

fact.o:     file format elf32-i386


Disassembly of section .text:

00000000 <factorial>:
   0:	55                   	push   %ebp
   1:	b8 01 00 00 00       	mov    $0x1,%eax
   6:	89 e5                	mov    %esp,%ebp
   8:	8b 55 08             	mov    0x8(%ebp),%edx
   b:	83 fa 01             	cmp    $0x1,%edx
   e:	7e 06                	jle    16 <factorial+0x16>
  10:	0f af c2             	imul   %edx,%eax
  13:	4a                   	dec    %edx
  14:	eb f5                	jmp    b <factorial+0xb>
  16:	5d                   	pop    %ebp
  17:	c3                   	ret 

(I like the objdump output for this purpose better, because you can immediately see the byte count on the left column).

BTW, clang-3.8 for this simple procedure only emits 0x15 (21) bytes of instructions with -Os. And 0x14c (332) bytes with -O3.

8

u/jpakkane May 31 '17

For -O2 (according to Compiler Explorer, GCC 7):

factorial(int):
        cmp     edi, 1
        mov     eax, 1
        jle     .L4
.L3:
        imul    eax, edi
        sub     edi, 1
        cmp     edi, 1
        jne     .L3
        rep ret
.L4:
        rep ret

Which is noticeably smaller than without optimizations.

2

u/[deleted] May 31 '17

-Os

2

u/maxhaton May 31 '17

That's not a good example. This is best demonstrated by how good compilers are at eliminated unused variables and common subexpessions(Both done easily with SSA IRs). This is a very cheap optimisation and can eliminate entire basic blocks of code that would otherwise do nothing. Your factorial example is only a good example for showing off the auto-vectorisation and loop unrolling of one's compiler.

You are also optimising for speed (-O3) not size.

2

u/industry7 May 31 '17

Many compilers allow you to choose between optimizing run time speed vs optimizing executable size vs optimizing run time power usage, etc.

1

u/ellen_magic May 31 '17

Bernstein's talk is filled with detail and examples. John Regehr's dismissal is just a few paragraphs of personal claims.

2

u/[deleted] May 31 '17

Full of irrelevant details and unimportant examples.