Only use -flto when supported

This adds a dynamic check to see if -flto is supported by the compiler.

Co-Authored-By: JianBo He <heeejianbo@gmail.com>
diff --git a/rebar.config b/rebar.config
index 396631e..b951b5e 100644
--- a/rebar.config
+++ b/rebar.config
@@ -7,13 +7,15 @@
 ]}.
 
 {port_env, [
-    {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin|gnu)",
-        "CFLAGS", "$CFLAGS -Ic_src/ -g -Wall -flto -Werror -O3"},
-    {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin|gnu)",
-        "CXXFLAGS", "$CXXFLAGS -Ic_src/ -g -Wall -flto -Werror -O3"},
+    {".*", "FLTO_FLAG", ""},
 
     {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin|gnu)",
-        "LDFLAGS", "$LDFLAGS -flto -lstdc++"},
+        "CFLAGS", "$CFLAGS -Ic_src/ -g -Wall $FLTO_FLAG -Werror -O3"},
+    {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin|gnu)",
+        "CXXFLAGS", "$CXXFLAGS -Ic_src/ -g -Wall $FLTO_FLAG -Werror -O3"},
+
+    {"(linux|solaris|freebsd|netbsd|openbsd|dragonfly|darwin|gnu)",
+        "LDFLAGS", "$LDFLAGS $FLTO_FLAG -lstdc++"},
 
     %% OS X Leopard flags for 64-bit
     {"darwin9.*-64$", "CXXFLAGS", "-m64"},
diff --git a/rebar.config.script b/rebar.config.script
index 42bc6ef..a5da769 100644
--- a/rebar.config.script
+++ b/rebar.config.script
@@ -9,10 +9,31 @@
     [{d, 'HAVE_EQC'}]
 end,
 
-case lists:keyfind(erl_opts, 1, CONFIG) of
+Config1 = case lists:keyfind(erl_opts, 1, CONFIG) of
     {erl_opts, Opts} ->
         NewOpts = {erl_opts, Opts ++ ErlOpts},
         lists:keyreplace(erl_opts, 1, CONFIG, NewOpts);
     false ->
         CONFIG ++ [{erl_opts, ErlOpts}]
+end,
+
+case os:type() of
+    {unix, _} ->
+        CC = case os:getenv("CC") of
+            false -> "cc";
+            Else -> Else
+        end,
+        FLTO_CHECK = "echo 'int main(int argc, char *argv[]) {return 0;}' | "
+                ++ CC ++ " -c -x c -o /dev/null -flto -",
+        case os:cmd(FLTO_CHECK) of
+            [] ->
+                {port_env, PortEnv} = lists:keyfind(port_env, 1, Config1),
+                NewFlag = {".*", "FLTO_FLAG", "-flto"},
+                NewPortEnv = lists:keyreplace("FLTO_FLAG", 2, PortEnv, NewFlag),
+                lists:keyreplace(port_env, 1, Config1, {port_env, NewPortEnv});
+            _ ->
+                Config1
+        end;
+    _ ->
+        Config1
 end.