243 points · by obl · 4y ago · 217 comments
For example, try putting `puts("hello");` at the beginning of `add`. Now neither GCC nor Clang performs the optimization. Why? Because `puts` could theoretically modify the value behind the reference, so the value loaded is not necessarily the same as the value at the beginning of the function, which makes things more complicated, so both compilers give up.
As another example, GCC and Clang both perform the optimization within a translation unit, but if the function definition and the call are in different translation units, GCC doesn't perform the optimization even with LTO, and Clang doesn't perform it with ThinLTO (but does perform it with full LTO). Meanwhile, many projects don't compile with any form of LTO, which is a reasonable decision to improve compilation speed and predictability.
Neither compiler is smart enough to perform the optimization for virtual calls in almost any situation.
It seems odd to break with C++ semantics for small parameters only; I'd expect it to either break for all parameters or no parameters.
EDIT: looks like Carbon is not doing this optimization for small values either. Its docs on parameters say, "This binding will be implemented using a pointer, unless it is legal to copy and copying is cheaper". And the OP link says, "the compiler is allowed to convert that to a T [copy] under the as-if rule." That seems like no extra optimization is enabled other than changing the function calling convention. And the "as-if" rule would require looking at the function body to check if the value could be changed (by things like puts()). I hope my understanding is wrong because this does not make sense. The word "legal" is ambiguous, so hopefully they mean something else!
You write your code assuming such an optimisation will happen, and for some reason, the compiler decides not to apply the optimisation. Perhaps the wind was blowing in the wrong direction, or it was in a bad mood, or you forgot to specify -fvisiblitly=hidden.
The exciting part here is that it happens by default, and the compiler is required to do it. I don't have to think about it, and the ABI automatically does the thing best for performance.
It's nothing really out of the ordinary ... also that particular optimization is meager in practice (on the order of 1%?). I know everything improvement adds up, but the author talks about it as if it was a game changer. I like the enthusiasm, though :D.
Given the major selling point of C/C++ is performance, that's not an insignificant amount.
Honestly the only thing that really stood out as nice is the default pass by word-sized value, in the context of templates - it’s a thing that is achievable in C++, but requires a bunch of obnoxious additional templates that aren’t even part of the standard library so everyone ends up reimplementing the same cruft. Happily I believe there’s a proposal to add this exact functionality.
I also loathe their desire to listen to the BNF maximalists insistence on not having any “ambiguity” from <>s. I’m sorry it’s clearly parseable, and <>s are the standard token for decades. Switching to []s doesn’t make it less conceptually ambiguous, if anything it makes it more ambiguous to a human reader. The only people who don’t want <>s are PLT academics obsessed with forcing their dragon book idea of what a grammar should be. You can’t argue you’re doing it because the ambiguity in a grammar or lexer is bad, because then you would also drop infix operators.
Then in carbon the more reasonable adoption of pascal’s : notation for typing a variable or parameter removes the most common case of the supposedly terrible ambiguity anyway.
Odd that you put ambiguity in quotes. I guess it's not real ambiguity then.
Ivory tower academics, as you see them, actually care about stuff because it affects you. I've heard too many times the knee-jerk response of "it's just theory" as if that actually meant anything. Try implementing it yourself and you'd start to understand that little bits of crap typically don't add, they multiply (Edit: and I'm hurting from exactly this right now), so don't diss theory until you've (ironically) had some practice with it.
Because a parser is never really ambiguous is it? Nobody writes a parser that has a random decision on which rule to take.
It's also well understood that for (2) this theoretical ambiguity is not actually a real problem for humans - the things for which reading is actually important - because otherwise they would not allow infix operators, which are ambiguous according to their definition, but much like languages that they have chosen to define as ambiguous, infix is not.
In that theoretical model of grammars we define the power of different classes of parsers to go something like LL < LALR < LR < GLR. This is how the mathematical theory of grammars goes, and everything beyond LL is basically required to be based on some PDA. The ambiguities in the PDA's state transitions are what "prove" a grammar to be ambiguous. Further LL parsers are considered the least powerful, and incapable of parsing the majority of grammars, especially those that belong to "real" languages.
The problem is that this model of grammars is arbitrarily restricted, and many (I would guess most real world) parsers for "real" languages are not any of these classes, which is certainly odd given the completeness indicated by theory. That's because this restricted definition of what a parser is says that most real world programming languages require an LALR parser, and in reality the big ones likely need LR or GLR.
In the real world, what is used could probably be classed as LL(infinity), which is impossible according to the theoretical parser classes in use. The reason that we use these impossible LL(infinity) parsers, is because they are human writable, and human understandable, and also vastly faster than the state machines LALR parsers (think bison and yacc IIRC), even more so for LR, and slower again for GLR (even if you can get away with a tomita parser, if you could find a generator for one). Additionally all the non LL parsers can only be reasonably implemented via state machine, and beyond trivial examples, a human is not going to be able to write the state transition tables, let alone modify it in future.
That means using a tool to generate the parser for you, and this really is the heart of the theoretical definition being used, to be a "real" parser, you need to be able to make a tool that will read a BNF grammar, and have it produce a program that will be able to take some text, and then, accumulating no state beyond a stack and its current state, produce an AST.
I have never been shown any justification for why this makes a grammar more understandable, it is simply stated as fact that being easier for a machine to parse means being easier for a human. The contra to that is that most people seem find infix much easier to understand than the non ambiguous pre- and post-fix notations. You could argue that's familiarity, but I would say "so what?" that people can find the "ambiguous" grammar easier to understand than the non ambiguous one indicates that the claim of "easier for machine == easier for people" to not stand up.
Anyway that giant wall of text is my position, and that is why I don't accept "<> for generics is ambiguous" as the sole justification for a change from the root language this is meant to be a replacement for. If they were creating their own language then sure, they could go ham and make the least ambiguous language that they liked (but lisp I think has technically already done that), but that is not what Carbon is doing.
Finally (and so the Great Wall of text continues) on your "ivory tower academic" accusation, I disagree. Academic CS is hugely valuable, and having been in CS academia for many years I feel I am allowed to express my disagreement with some of it.
If credential waving is needed, for academics: my masters is in programming language theory, and I was the TA for among other things my university's courses on programming language theory, parsing, etc. In industry I've worked on clang for many years, and for parsing specifically I wrote the javascript parser in javascriptcore.
I understand parsing, and I understand the PLT subfield of CS.
My frustration with academic PLT is more that by confining the definitions of what is a valid grammar, or what is a real parser, we don't see any real research into into those aspects of PLT and in my experience it seems like an area where we just treat the dragon book as being the definition of everything that matters. Then we turn around say anything that doesn't fit neatly in that definition must be bad, and can be ignored.
Not if it's in a different compilation unit, it doesn't. Or if it's just not inlining the function for some reason, then it probably also doesn't. Which is why Carbon's restriction here is so useful and practical.
void f(int i) { &i; /* disallowed */ }
I think that's a trivial case and is hopefully obviously easy to detect, and I know we're considering relevance to escaping which this doesn't do, but it seems that taking the address is explicitly disallowed regardless of use. Anyway given the many references to references, lets do void g(int &i) { &i; /* disallowed once more */ }
To me this seems no harder to detect, but this does seem like a case where banning taking the address /could/ impact things. But I can't see what the win is.I'm assuming its a different TU or something else that prevents inter procedural optimization. Could you give some examples where this allows performance wins?
I don't get that: can you express in C++ a code that "take the address of a parameter via any mechanism other than explicitly taking the address"?
int main(void) {
int x = 0;
int arr[1];
int *p = arr + 1;
*p = 42;
return x;
}
On a lot of systems (e.g., https://godbolt.org/z/jYqM8TT3Y), it just so happens that `x` is right above `arr` on the stack, so that code will return 42. But that code is absolutely UB.The more general name for this concept is "pointer provenance". Basically, you can't pull pointer values out of thin air; you have to derive them from operations rooted at taking the address of something within the same allocation.
This is undefined behavior. Because it is UB that compiler is allowed to assume it cannot happen. Therefore I have the address of a parameter, and can pass that to a closure or whatever, and the parameter has escaped, but the compiler doesn't know.
More importantly by definition the compiler does not need to know, because a program that does that is no longer well defined.
Even C++ struggles to be compatible with C++. I expect Carbon to have at least as hard a time with it, especially given the "bazaar" that is the C++ build and packaging ecosystem.
I also expect that Carbon will have a hard time tracking C++ as it evolves. It could freeze C++ feature development? Or it could target an old and aging C++ standard?
Point is, I'm not taking C++ compatibility as a given. It seems very hard and may require a lot of big tradeoffs.
It's a very realistic take on C++ interop, but still well beyond anything offered by other languages.
The real killer is that the lack of any interaction with C++ means that you can’t do any real incremental adoption of one of those safe languages in any big security critical projects. Saying that the solution to C++ is to just not use it ignores the reality that C++ exists, and large projects in C++ exist. It doesn’t matter if you don’t like C++.
The final problem with the safe languages - with the exception of swift - is that they are all hell bent on not providing even just basic ABI stability. It doesn’t matter how “safe” your language is if the first thing you have to do is make a pure C (even losing potential for automatic lifetime management the C++ would allow) interface.
So I can have two libraries both written in rust, and the entire safety of it is contingent on each library talking to the other through a C API.
I think it's more that interop with C++ is hard and ultimately a lot less valuable than interop with C, which is what the vast majority of languages use for FFI.
> It doesn’t matter how “safe” your language is if the first thing you have to do is make a pure C (even losing potential for automatic lifetime management the C++ would allow) interface.
I don't see how that leads to "it doesn't matter"
It's not that it's inherently bad, it's just insanely difficult to do and, probably, isn't worth the pain. Carbon's approach to solving this problem includes embedding a custom C++ compiler as part of its toolchain, and at this point it's just the idea, who knows if they will be able to actually do it.
> they are all hell bent on not providing even just basic ABI stability
Right, the famous stable C++ ABI
Carbon isn’t looking to do this either. The “solution” they’ve come up with is that you just recompile everything and get things on the same ABI, which is not surprising considering how Google operates internally.
Likewise JNI has always had support for COM like models, and the C API is written in such way that the struct layouts can be used as C++ classes instead, with implicit this on method calls.
You mean where Google has majority control over what does and does not go into the repo?
The reverse is true. Anything passed by value can be treated as const reference by the compiler if the compiler knows enough about access and lifetime. The compiler must be able to determine that the parameter is neither deallocated nor modified while the function is using it. Rust compilers should be able to do that.
ftp://ftp.linux-mips.org//pub/linux/mips/doc/NUBI/MD00438-2C-NUBIDESC-SPC-00.20.pdf
Section 3.4, page 21:"Arguments: [...]
Derived types (structures etc) and non-standard scalar types are passed in a register if and only if their memory- stored image is register-size aligned and fits into a register. [...]
All other arguments are passed by reference. The callee must copy the argument if it writes it or takes its address."
There is of course no 'registry of allowed names that have aged-out' but there are probably other creative names one could come up with.
As an example, look at this issue from the mold linker: https://github.com/rui314/mold/issues/584
They are looking at creating an embeddable custom dynamic linker in order to greatly reduce loading times, by fixing locations as the file gets loaded in.
The equivalent in Carbon would (for example) be to create a new type of exception handling that changes how we think about exceptions, performance and their cost. Perhaps something like the static exceptions that Herb Sutter has been working on. Instead, they are not adding exceptions at all.
You will have to excuse my disappointment.
That is all.
If you've got a 1.6 billion empty tuples in variable A, 1.4 billion in variable B and 1.8 billion in variable C, C++ can't see a way to do that on a 32-bit operating system. It needs to give each empty tuple an address, so it must think of 4.8 billion integers between 0 and 2^32 and it can't do that, so your program won't work.
Carbon is still far from finished, but if objects needn't have addresses it can do the same as Rust here, and cheerfully handle A, B and C as merely counters, counting 1.6 billion, 1.4 billion and 1.8 billion respectively is fine. Empty tuples are indistinguishable, so I needn't worry about giving you back the "wrong" empty tuple when you remove one, I can just give you a fresh one each time and decrement the counter.
There is a lot of 32 bit microcontrollers, most notable stm32
Admittedly, those probably aren't running on 32-bit systems, nowadays ...
But you are going to need some minimal buy-in from Microsoft first, if not Sony and Nintendo too.
The great thing about carbon is that you can incrementally shift a codebase over from c++, and there are no problems interacting with existing c++ APIs, so the required amount of buy-in is pretty much just "yes, you can use a 3rd party compiler" and maybe some improvements to the debugger.
Triangle meshes can be stored quite efficiently and a lot of the modern geometry is tessellated, procedural or replicated.
There are far better optimizations for gamedev like using SOA instead of AOS.
If you have those, I don’t see any way to discriminate between them. If so, why would you ever want to have more than one of a given type? Is there some template code that might accidentally try to create them?
struct Marker {};
struct Foo {
Marker marker;
int64_t number;
};
If you write the equivalent in C with GCC extensions, or Rust, sizeof(Foo) would be 8, the same as sizeof(int64_t); `marker` doesn't take up any extra space. In C++, however, sizeof(Foo) is 16, because `marker` must take up at least 1 byte to have a unique address, which gets expanded to 8 bytes due to alignment.Now, as of C++20, you can reduce sizeof(Foo) to 8 by tagging `marker` as [[no_unique_address]]. However, this has drawbacks. First of all, it's easy to get situations like this in highly generic code, so it's hard to predict where [[no_unique_address]] needs to be applied (and applying it everywhere would be verbose).
Second of all, [[no_unique_address]] is dangerous, because it doesn't just allow empty fields to be omitted, it also allows nonempty fields to have trailing padding bytes reused for other fields. Normally that's okay, but if you have any code that performs memcpy or memset or similar based on the size of a type, such as:
struct Foo {
Foo(const Foo &other) {
memcpy(this, &other, sizeof(Foo));
}
// …some fields here…
};
…then if that code writes to a [[no_unique_address]] field, it can overwrite adjacent fields, since sizeof(Foo) includes any trailing padding bytes!With only three exceptions I can't think of a case where by default one would not want that. In the case you describe you would want all those objects to have unique addresses. If you wanted to have them overlap you should go to the effort to happen the way you want it to -- how could the compiler guess on its own?
The exceptions BTW are union elements, the first class/struct element, and base object addresses (in `class foo : bar ...` the when you make a foo, the address of its bar is the same as the address of the foo itself).
I certainly don't, if you want unique addresses for indistiguishable objects I guess C++ is the perfect language for you but, what are you expecting to do with these addresses?
https://en.cppreference.com/w/cpp/language/attributes/no_uni...
I think this boils down to: Carbon defaults to passing parameters that fit in a single register by value, and all others by const reference. This affects a few things you might take for granted in C++, like whether you can take a reference to a parameter.
The opening example is showing two samples of Carbon and the equivalent C++ code, noting that the "undecorated" parameter `p : Point` is equivalent to `const Point& p` (pass by const reference to a struct) and `x : i32` is equivalent to `std::int32_t x` (pass by value).
I give it a -1 on innovation, it's so obviously stuck in a cul-de-sac in the design space that I see no hope for it. "We'll get around to memory safety eventually". Riiight.
That said, I'm glad they at least made the leap to, "Hey, we could actually use something other than C++?"
The goal of Carbon is explicitly _not_ to be a new general purpose programming language. In the docs, the authors even advise people to use Rust instead for greenfield projects. The goal of Carbon is to support migrating existing C++ codebases to some new safer language.
There already were several options instead of using C++, but some minds are wired in that way after many years of training.
And I standby my original assessment that the design is very obviously lacking in long-term experience in another language.
It usually boils down to someone assuming that a particular collection or algorithm won't be on the critical path, and using a lazy O(N^2) solution. Then the codebase grows, use cases shift, someone puts another O(N^2) algorithm around an existing O(N^2) and the whole thing explodes.
Adding proper caching and switching to N*log(N) algorithms usually brings a DRAMATIC improvement (like 100x faster), while trying to squeeze out every unnecessary copy will only squeeze out about 10% of complexity.
Unclear from the repo who is sponsoring it.
- don’t listen to me, it’s Google.
I hope this doesn't take off, with my sincere apologies to the ones who have been working hard on this. The last thing the C/C++ ecosystem needs is becoming de facto owned by a private company.
Then C and C++ are defacto controlled by private companies: Google+Apple do pretty much all the clang development, MS does MSVC - if they choose not to implement a feature that’s approved, or implement one that isn’t, that is the de facto standard.
You can argue it would require all three to agree on something, but that’s still essentially making WG21 somewhat irrelevant.
Why not? Just curious.
""We are planning to create an open source foundation and transfer all Carbon-related rights to it; our goal is for the foundation setup to be similar to other open source projects, such as LLVM or Kubernetes.""
Are they trolling Go here?
I find the tone strange. I understand that the author doesn't believe the statement. But I've never met anyone for whom performance matters and believes this. So, who's the audience here?
A C++ replacement that is just as difficult to bind/link/work with in other languages as C++ itself just seems like a missed mark, despite the fact I know this is not on their priority list at all.
I hope my read of this is wrong, and it will be easy to bind and link to from other languages after all.
Carbon might be shy about its footprint.
GC and ARC are for people that need shared ownership, which is pretty much always a bad idea.
type Point is record
x, y, z : Interfaces.Integer_64;
end record;
procedure Print(p : Point);
Is `p` passed by reference or value? The compiler chooses what it thinks is best--all parameters are considered `const` unless they're `out` parameters. There's some rules for classes (tagged types), uncopyable (limited) objects, and `aliased` parameters which are always passed by reference.I can't get a pointer type (access) out of the parameter to the function, since the accessibility rules prevent it:
-- "constant" since we don't know if it is writable
type Point_Access is access constant Point;
Last_Printed : Point_Access := null;
procedure Print(P : Point) is
begin
-- P'Access is sort of like C++ std::addressof(P) to get a "pointer"
-- There's also P'Address to get the actual address, but then requires conversion to a pointer-like "access" type to be used.
--
-- Compiler Error: "non-local pointer cannot point to local object" since Point_Access type is declared at a higher level
Last_Printed := P'Access;
-- If we really, really, want to do it, "I'm smarter than the compiler", you can force it...
-- Think of "Unrestricted" and "Unchecked" as grep-able warnings signs of "this is potentially very dangerous"
Last_Access := P'Unrestricted_Access;
-- ...
end Last_Printed;
What about making and then trying to use a local pointer-like type? This doesn't work because you can only create pointer-like accesses to types which have been marked as `aliased`, since you don't know if there's a location you can point to which has the value. procedure Print (P : Point) is
type Local_Access is access constant Point;
-- Compiler Error: prefix of "Access" attribute must be aliased
Ptr_Like : Local_Access := P'Access;
-- Similar, "I am smarter than compiler" trick works here too...
Ptr_Like : Local_Access := P'Unrestricted_Access;
You can allow passing any arbitrary pointer into a function by providing `access`, but you're not allowed to store it, since you don't know which flavor of the pointer type it could be, e.g. if it points to something on the stack, or on the heap: type Point_Access is access constant Point;
Last_Printed : Point_Access := null;
-- Allow printing any pointer-like (access) to a point.
procedure Print (P : access constant Point) is
begin
-- Compile Error: implicit conversion of anonymous access parameter not allowed
Last_Printed := P;
-- If we really, really want to do this, we can force it with a cast...
Last_Printed := Point_Access (P);
-- ...
end Print;I'd only worry about compiling it yourself if you intend to participate in Carbon's development in the near future.
The standard explicitly states that a parameter taken by value and initialized from an prvalue of the same type may elide the move constructor (which all implementations do).
No thanks google. I've been saying that for years now. You jumped the shark
This was not an overview of the language, so this comment seems a little uncharitable to the author.
I don't care if this sounds uncharitable, I see the pitfalls and I seen so many people get sucked in to prior pitfalls
It is interesting to contemplate the most-ambiguous and least-comprehensible/googleable name one might be able to give to a piece of software. "the"? "Biden"? "Russia"? "water"? "air"? "dog"? "person"? "!"? "?"? " "?
Google managers: "Whatever floats your boat. How about Go, Dart and Carbon?"
Lua and PHP have nice searchability. At least, it's fairly easy to weed out results on the Portuguese moon and the Philippine peso.
I also had to write some Go, that was actually pretty bad in terms of searchability.
https://www.irishrail.ie/en-ie/about-us/iarnrod-eireann-serv...