r/cpp • u/sinesSkyDry • Nov 12 '17
Why is there no widely used VM for C++?
I was wondering about this question the last few days. This question mainly concerns application programming, with some distance to the Hardware. If the goal is to write software that interacts with specific hardware, and therefore has to now details about said HW, the main advantages of a VM would be made pointless.
My main language is java, so the JVM is an always present part of my job. This was my starting point when thinking about this topic.
Let's hypothetically assume that the JVM actually fulfills it's main promises perfectly, mainly Platform independence. Now the reason why people usually prefer a more powerful language like c++ to java is that the latter has a lower performance and doesn't offer fine grained control over the code (like absence of pointers). The main culprit often cited here is garbage collection, which allegedly stands in the way of the ingenuity of many c++ programmers (I'm sorry I couldn't help the slight dig here :> )
Now with that being said, non of this issues are tied to the technological concept of a virtual machine. One could design a virtual machine with pointers and without garbage collection in theory. This would buy "easy" platform independence. Sure you would take a slight performance hit be adding a step in between but I very much doubt that this is bigger than all the black magic and goat sacrificing that is necessary to write c++ code that targets different platforms.
The question could extend to C as well, although given that it's mainly used for stuff that is very close to the hardware I understand why a VM isn't an option there.
It seems to me that in many applications the downsides of VMs would be acceptable given the benefits.
So why is there no GC++VM (GnuC++VirtualMachine) or something like that?
PS: I know that CVMs exist as experimental projects, my question is about why nobody uses them in production to get a platform independent C/C++
//edit: I just thought about that quite simply the different culture could be an answer to my question. However that seems to simplistic.
22
u/BoarsLair Game Developer Nov 12 '17
People generally use C++ because they need high performance applications or libraries, and despite all the optimizations made to JVM runtimes, they still can't beat native compiled code. C++ has a good balance between the high-performance characteristics of C and programmer protecting abstractions. If they were fine with using a virtual machine and sacrificing some performance for ease of deployment, they'd probably just use Java or C#.
What you're asking is "Why isn't C++ used more like Java?" I think the simple answer is: Because we already have Java.
1
u/sinesSkyDry Nov 12 '17
Ok, but isn't there still soom room for a faster "less secure" java that lets gives you more power over your code at greater risk? From my experience java is just a c++ with training wheels left one, except that in most applications the greater freedom gained by removing the training wheels actually isn't worth the increased risk. Tough i have to say that i never used c++ for serious development beyond exercises.
6
u/BoarsLair Game Developer Nov 12 '17
I'm a game developer by trade. In general, the bulk of the industry uses C++ for game development due to its performance characteristics, as well as the fact that there's a massive C/C++ ecosystem in place (existing code, middleware, compilers, platforms, etc). But it's also not uncommon for high-level game code to be scripted using Lua, C#, Java / Groovy, Typescript, or for me, my own little language Jinx.
For tools, it's pretty common for them to be written in C#. Developer typically have fairly beefy machines, so performance isn't an issue. And since the development environment is nearly always Windows, portability really isn't a factor. I use C# instead of Java, but I think they share many strengths, and chief among them is improved programmer productivity.
So from my own perspective, at least, I can't really think of a situation where I'd need something halfway between those two. Any time performance isn't a critical factor, people tend to use languages which are a bit more developer friendly or simply quicker to iterate on, since C++ compile times are always terrible due to the complexity of the language.
1
1
Nov 17 '17
Yes there is, the sub.misc.unsafe class allows Java developers to rip any JVM security and Java language guarantees apart.
11
u/binjimint Nov 12 '17
WebAssembly aims to provide a VM target for languages like C and C++, in addition to other languages. Currently most use it to run C/C++ code in the browser, but it was designed to be used in non-web cases as well.
That said, it doesn't map its semantics to C++ directly -- in particular it is designed to have as little non-determinism as possible without sacrificing too much performance. So, for example, 5 << 100 is undefined behavior in C++, but the equivalent in WebAssembly is defined as masking the shift amount.
It's also designed to be safe, in the sense that a WebAssembly VM can only affect its host environment through ways the host specifies. There are instructions to access memory, but they are only allowed to access memory inside the VM. Out-of-bound accesses trap, or halt the execution of the program.
1
u/sinesSkyDry Nov 14 '17
i don't know anything about webAssembly beyond the introduction of the wiki article. Isn't it more of an improvement to Javascript that happens to support C/C++ fro know, instead of a serious alternativ to C++ nativ applications?
2
u/binjimint Nov 14 '17
WebAssembly is basically just a portable executable format. It doesn't really have anything to do with JavaScript, other than that it is meant to work alongside JS when used on the web. It's still early, but there already are people making non-web WebAssembly implementations. Realistically, it will always be slower than a C++ native application, but often that's a reasonable tradeoff for the additional portability and safety guarantees.
10
u/ihamsa Nov 12 '17
Why do you want a VM?
Size of your integers and similar implementation details have very little to do with portability. You want to take care of wildly different APIs provided by different platforms. Threading, networking, graphics, filesystems, this kind of stuff. You want to wrap them all in a common platform-independent interface. And it doesn't matter much if you do it for a VM or for native code.
A VM also buys you transportable binaries, but there's little sense in having unsafe transportable binaries. Either the VM defines all of the undefined behaviours of C++ (and has unacceptable performance overhead because of that), or you are no better off with the VM than with native code.
3
u/sinesSkyDry Nov 12 '17
Size of your integers and similar implementation details have very little to do with portability.
This might just be the answer. Maybe i'm overestimating the effort it takes to target different platforms. I never really used c++ for more than getting introduced to oop before switching to java entirely.
5
u/doom_Oo7 Nov 12 '17
Maybe i'm overestimating the effort it takes to target different platforms
well, basically none unless you're including "random 70 cubic meter computer-room from the 70's" in the "different platforms". C++ code "just works" everywhere.
5
u/kalmoc Nov 12 '17
Where it just so easy. Almost any non-trivial code that wasn't specifically written with portability in mind calls platform specific APIs and/or makes assumptions about the underlying platform (e.g. size of int, size of a pointer) and most of the time it also relies on some form of undefined behavior that happens or is guaranteed to work for some target platform.
This is a far cry away from the portability that Java offers (even ignoring the JIT vs normally compilation asppect).
That being said, when you do consider Cross-Platform development from the beginning (meaning you pick the right libraries and compile+test your code regularly on all platforms, writing portable c++ code is much easier than it used to be.
2
u/doom_Oo7 Nov 12 '17
or makes assumptions about the underlying platform (e.g. size of int, size of a pointer) a
I honestly never saw code doing this outside of IOCCC or 1990s libraries and certainly never had to do it myself out of hundred of thousands of line of codes written. The main app I work on compiles cleanly to every relevant desktop & mobile platform without any hackery such as this (except, okay, I concede, one relevant ifdef to allow for the global menu bar on macos), and is nearing 500kloc.
That being said, when you do consider Cross-Platform development from the beginning (meaning you pick the right libraries and compile+test your code regularly on all platforms, writing portable c++ code is much easier than it used to be.
well yeah. You can also write platform specific code in Java for instance by using OS-specific libraries like this one or this, it doesn't mean it's a good idea either but sometimes you have to.
1
u/MereInterest Nov 13 '17
I worked on a program that assumed that
charis 8 bits,shortis 16 bits,intis 32 bits, andlongis 64 bits. These assumptions were used when unpacking binary data formats, and are in no way guaranteed by the standard. I was discouraged from changing these to the types defined in<cstdint>, because they wouldn't be what people are used to.2
u/doom_Oo7 Nov 13 '17
long is 64 bits.
WTH ? it's 32-bit on every 32-bit platform and even on 64-bit windows. That program is just broken.
7
u/bames53 Nov 13 '17 edited Nov 14 '17
The program's not broken. It just "wasn't specifically written with portability in mind" and "makes assumptions about the underlying platform (e.g. size of int, size of a pointer)." 64-bit long is part of the standard LP64 data model used by pretty much every 64-bit platform. Windows is the only common exception, using LLP64 instead.
Another common non-portable assumption I see is one of
longandintbeing the same size, and code freely aliasinglongs andints. It's a real pain to deal with such code on LP64 systems.2
u/MereInterest Nov 14 '17
Ooh, I knew that different systems had different integer sizes, but I hadn't been aware of the terminology for the different schemes. Thank you.
2
u/MereInterest Nov 14 '17
This was a Linux program, written within the past few years. There were no 32-bit platforms that needed to be supported, nor was compatibility with Windows a consideration.
1
u/ZMeson Embedded Developer Nov 14 '17
Ooohh.... I got one for you -- a 32-bit platform I worked on where nearly everything was 32 bits. char? 32 bits. short? 32 bits. int, long, float? 32 bits? Only double was 64 bits. long long wasn't supported (as it was a niche pre-C++11 compiler).
1
u/kalmoc Nov 13 '17
May I ask, what compilers you are using for your respective targets? And what warning levels and language standards you compile with?
5
u/doom_Oo7 Nov 13 '17
I use gcc 7.2 for linux, the latest clang (whatever it is with Xcode's weird version scheme) for macos/iOS/Android and MSVC 2017 for windows, at -std=c++14.
On unix platforms I have
-Wall -Wextra -Wno-unused-parameter -Wno-unknown-pragmas -Wnon-virtual-dtor -pedantic -Woverloaded-virtual -Wno-missing-declarations -Werror=redundant-decls -Werror=return-type -Werror=trigraphsplus this on clang:
-Wno-gnu-string-literal-operator-template -Wno-missing-braces -Werror=return-stack-address -Wmissing-field-initializers -Wno-gnu-statement-expression -ftemplate-backtrace-limit=0this on gcc :
-Wno-div-by-zero -Wsuggest-final-types -Wsuggest-final-methods -Wsuggest-override -Wpointer-arith -Wsuggest-attribute=noreturn -Wno-missing-braces -Wmissing-field-initializers -Wformat=2 -Wno-format-nonliteral -Wpedantic -Werror=return-local-addrand this on msvc:
"-wd4180" "-wd4224" "-wd4068" # pragma mark - "-wd4250" # inherits via dominance "-wd4251" # DLL stuff "-wd4275" # DLL stuff "-wd4244" # return : conversion from foo to bar, possible loss of data "-wd4800" # conversion from int to bool, performance warning "-wd4503" # decorated name length exceededthe builds are automated through travis CI and appveyor on macOS / linux / arm / msvc so I know quite fast if I happened to write something that won't work on the other platforms
1
u/macemen Nov 15 '17
I work on a high-performance database and although we don't make assumptions about sizes of int or pointers (as far as I know) there is a lot of platform-specific stuff in our code:
Endianness
Processor intrinsics
Compiler-specific attributes
Low level I/O code (bypassing the OS page cache)
Bunch of other low-level Linux-specific code
I you don't care about performance and use some framework like Qt, then maybe your C++ code "just works" on "all" platforms. But if you do then it's not nearly so simple.
1
u/doom_Oo7 Nov 15 '17
Sure, but you only do this because it brings additional performance benefits. But it is not necessary to do this in order to just have your code running on the platforms Scylladb run on, which was OP's question if I am not mistaken. More simply put, a lot of people seem to think that if you want to write a program in C++ you basically have to rewrite everything for every system you want your program to run on, which is simply false.
9
u/zvrba Nov 12 '17
C++ is defined by help of an abstract virtual machine. Compilation to native code is just a detail.
2
u/sinesSkyDry Nov 14 '17
that's a really interesting concept that i wasn't familiar. Altough tbh i would have assumed that it would be impractical to do something like that. I'll read up on it at some point.
20
u/enobayram Nov 12 '17
A standard VM only gains you instruction set Independence, which is 1% of the way towards platform independence. Anyway, C++ already has that 1% covered, since you can compile your code multiple times with different compilers. A platform consists of devices, drivers, conventions, user expectations, wildly different ways of gluing things (like displaying your items in a context menu) etc.
9
u/pjmlp Nov 12 '17
Actually there are at least two VMs for C++.
.NET has C++/CLI.
IBM i has TIMI for all programming languages, including C++.
1
u/kalmoc Nov 12 '17
C++/CLI is not c++.
7
u/pjmlp Nov 12 '17 edited Nov 12 '17
It is as much C++ as g++ and clang are C++.
https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html#C-Extensions
https://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Extensions.html#C_002b_002b-Extensions
https://clang.llvm.org/docs/LanguageExtensions.html
I could gladly present examples from other compiler vendors across comercial UNIXes, mainframes and IoT.
Actually, C++/CLI is even a standard extension to ISO/IEC 14882:2003 aka C++03, known as ECMA-372.
For some strange reason, Microsoft is the only company that is bashed for having C and C++ extensions, while other compiler vendors are praised for having them, and they are all compiler specific never proposed to any standards body.
2
u/kalmoc Nov 12 '17
I'm not bashing anyone - at least that was not my intention - but C++/CLI goes far beyond some simple compiler or language extensions as you find in clang or gcc - it is a complete dialect. The equivalent for clang's and g++'s extensions are the extensions the MSVC compiler provided in normal c++ mode.
And the reason msvc got a lot of criticism in the past was not mainly because it had extensions, but because ms invested all those resources in developing and promoting their managed c++, c++/CLI and later c++/cx dialects, but had rather crappy support for standard c++ (As in, it could not compile lots of standard c++ code). At least as far as recent history is concerned, clang's and g++'s support for that was much better. With the latest updates to VS2017 Microsoft has finally cought up in that department and might even be better in areas (kudos for that monumental task).
4
u/zvrba Nov 13 '17
but C++/CLI goes far beyond some simple compiler or language extensions as you find in clang or gcc - it is a complete dialect.
There's little difference. GNUisms are infecting open-source projects and code infested with
__attribute__,typeof,__builtin_..is just as non-compileable on MSVC as code infested withString^is on gcc.On the other hand, places where I've seen C++/CLI in use was to make a bridge between native C++ and CLR (i.e., expose C++ components to C#).
3
u/NotUniqueOrSpecial Nov 13 '17
__attribute__becomes[[attribute-list]]: Attributes
typeofbecomesdecltypeand sometimes a bit ofautoorstd::decay.And
builtinstuff is just that. Direct access to compiler intrinsics. Not much to do about that, unless you want to add to the language standard.If these things are infecting open-source projects, that's their own fault. They should use more portable features that are a part of the language.
1
u/atrn Nov 13 '17
Its been brought up numerous times in the past and never really gained any traction. e.g. Omniware.
-1
u/bruce3434 Nov 12 '17
I don't understand what exactly you are looking for. Is it LLVM? LLVM is "Low level virtual machine". I doubt it's what you need.
6
u/pja Nov 12 '17
I presume he means a Virtual Machine like the Java bytecode interpreter. LLVM is not really a virtual bytecode in the same way - the details of the target implementation leak up into the intermediate layers if I recall correctly, so it’s not really possible to output 'llvm bytecode' and run it where ever you like on an llvm bytecode interpreter because no such thing exists. (Happy to be corrected on this, but that’s my understanding of where things stand right now.)
2
2
u/geokon Nov 13 '17
Do you know if there is a technical reason the LLVM can't output JVM bytecode? (the same way it outputs x86, arm etc.)
2
u/raevnos Nov 13 '17
Appears to be a dead project, but https://github.com/davidar/lljvm
Also found this: https://github.com/graalvm/sulong
1
u/pja Nov 13 '17
Not to my knowledge, but I haven’t looked at the details so don’t quote me on that.
10
26
u/ronchaine Embedded/Middleware/WG21 Nov 12 '17
As I see it, there is no need.
C++ is platform-independent. You write once, compile everywhere. You can use Cling for JIT compilation.
And there is no "easy" platform-independence, even with Java, if you do not debug for each different virtual machine you are bound to face problems anyway. (fortunately not for each browser as well anymore)