Add opt-in option to turn on ThinLTO caching

Allow developers to enable ThinLTO caching on their local build by
setting USE_THINLTO_CACHE environment variable.

This significantly speeds up incremental ThinLTO builds by caching
intermediate results. An incremental ART build (by `touch
compiler/compiler.cc`) reduced from 01:32 to 00:45.

We put the cache under out/soong/thinlto-cache as the cache can be
valid across different targets, and allows us to set a global cache
pruning policy.

The current cache policy is sufficient for current list of
ThinLTO-enabled projects, we can tune it up/down in the future.

Test: USE_THINLTO_CACHE=true m
Bug: 62839002
Change-Id: I4838fe833a1d8fbc73d743da6d19e3698dc89600
diff --git a/cc/lto.go b/cc/lto.go
index 2ced124..d7526e2 100644
--- a/cc/lto.go
+++ b/cc/lto.go
@@ -74,12 +74,27 @@
 		var ltoFlag string
 		if Bool(lto.Properties.Lto.Thin) {
 			ltoFlag = "-flto=thin"
+
 		} else {
 			ltoFlag = "-flto"
 		}
 
 		flags.CFlags = append(flags.CFlags, ltoFlag)
 		flags.LdFlags = append(flags.LdFlags, ltoFlag)
+
+		if ctx.Config().IsEnvTrue("USE_THINLTO_CACHE") && Bool(lto.Properties.Lto.Thin) {
+			// Set appropriate ThinLTO cache policy
+			cacheDirFormat := "-Wl,-plugin-opt,cache-dir="
+			cacheDir := android.PathForOutput(ctx, "thinlto-cache").String()
+			flags.LdFlags = append(flags.LdFlags, cacheDirFormat+cacheDir)
+
+			// Limit the size of the ThinLTO cache to the lesser of 10% of available
+			// disk space and 10GB.
+			cachePolicyFormat := "-Wl,-plugin-opt,cache-policy="
+			policy := "cache_size=10%:cache_size_bytes=10g"
+			flags.LdFlags = append(flags.LdFlags, cachePolicyFormat+policy)
+		}
+
 		if ctx.Device() {
 			// Work around bug in Clang that doesn't pass correct emulated
 			// TLS option to target. See b/72706604 or