Newer
Older
dub_jkp / source / dub / compilers / ldc.d
  1. /**
  2. LDC compiler support.
  3.  
  4. Copyright: © 2013-2013 rejectedsoftware e.K.
  5. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
  6. Authors: Sönke Ludwig
  7. */
  8. module dub.compilers.ldc;
  9.  
  10. import dub.compilers.compiler;
  11. import dub.compilers.utils;
  12. import dub.internal.utils;
  13. import dub.internal.vibecompat.core.file;
  14. import dub.internal.vibecompat.inet.path;
  15. import dub.internal.logging;
  16.  
  17. import std.algorithm;
  18. import std.array;
  19. import std.exception;
  20. import std.typecons;
  21.  
  22.  
  23. class LDCCompiler : Compiler {
  24. private static immutable s_options = [
  25. tuple(BuildOption.debugMode, ["-d-debug"]),
  26. tuple(BuildOption.releaseMode, ["-release"]),
  27. tuple(BuildOption.coverage, ["-cov"]),
  28. tuple(BuildOption.coverageCTFE, ["-cov=ctfe"]),
  29. tuple(BuildOption.debugInfo, ["-g"]),
  30. tuple(BuildOption.debugInfoC, ["-gc"]),
  31. tuple(BuildOption.alwaysStackFrame, ["-disable-fp-elim"]),
  32. //tuple(BuildOption.stackStomping, ["-?"]),
  33. tuple(BuildOption.inline, ["-enable-inlining", "-Hkeep-all-bodies"]),
  34. tuple(BuildOption.noBoundsCheck, ["-boundscheck=off"]),
  35. tuple(BuildOption.optimize, ["-O3"]),
  36. tuple(BuildOption.profile, ["-fdmd-trace-functions"]),
  37. tuple(BuildOption.unittests, ["-unittest"]),
  38. tuple(BuildOption.verbose, ["-v"]),
  39. tuple(BuildOption.ignoreUnknownPragmas, ["-ignore"]),
  40. tuple(BuildOption.syntaxOnly, ["-o-"]),
  41. tuple(BuildOption.warnings, ["-wi"]),
  42. tuple(BuildOption.warningsAsErrors, ["-w"]),
  43. tuple(BuildOption.ignoreDeprecations, ["-d"]),
  44. tuple(BuildOption.deprecationWarnings, ["-dw"]),
  45. tuple(BuildOption.deprecationErrors, ["-de"]),
  46. tuple(BuildOption.property, ["-property"]),
  47. //tuple(BuildOption.profileGC, ["-?"]),
  48. tuple(BuildOption.betterC, ["-betterC"]),
  49. tuple(BuildOption.lowmem, ["-lowmem"]),
  50. tuple(BuildOption.color, ["-enable-color"]),
  51.  
  52. tuple(BuildOption._docs, ["-Dd=docs"]),
  53. tuple(BuildOption._ddox, ["-Xf=docs.json", "-Dd=__dummy_docs"]),
  54. ];
  55.  
  56. @property string name() const { return "ldc"; }
  57.  
  58. enum ldcVersionRe = `^version\s+v?(\d+\.\d+\.\d+[A-Za-z0-9.+-]*)`;
  59.  
  60. unittest {
  61. import std.regex : matchFirst, regex;
  62. auto probe = `
  63. binary /usr/bin/ldc2
  64. version 1.11.0 (DMD v2.081.2, LLVM 6.0.1)
  65. config /etc/ldc2.conf (x86_64-pc-linux-gnu)
  66. `;
  67. auto re = regex(ldcVersionRe, "m");
  68. auto c = matchFirst(probe, re);
  69. assert(c && c.length > 1 && c[1] == "1.11.0");
  70. }
  71.  
  72. string determineVersion(string compiler_binary, string verboseOutput)
  73. {
  74. import std.regex : matchFirst, regex;
  75. auto ver = matchFirst(verboseOutput, regex(ldcVersionRe, "m"));
  76. return ver && ver.length > 1 ? ver[1] : null;
  77. }
  78.  
  79. BuildPlatform determinePlatform(ref BuildSettings settings, string compiler_binary, string arch_override)
  80. {
  81. string[] arch_flags;
  82. switch (arch_override) {
  83. case "": break;
  84. case "x86": arch_flags = ["-march=x86"]; break;
  85. case "x86_mscoff": arch_flags = ["-march=x86"]; break;
  86. case "x86_64": arch_flags = ["-march=x86-64"]; break;
  87. case "aarch64": arch_flags = ["-march=aarch64"]; break;
  88. case "powerpc64": arch_flags = ["-march=powerpc64"]; break;
  89. default:
  90. if (arch_override.canFind('-'))
  91. arch_flags = ["-mtriple="~arch_override];
  92. else
  93. throw new UnsupportedArchitectureException(arch_override);
  94. break;
  95. }
  96. settings.addDFlags(arch_flags);
  97.  
  98. return probePlatform(
  99. compiler_binary,
  100. arch_flags ~ ["-c", "-o-", "-v"],
  101. arch_override
  102. );
  103. }
  104.  
  105. void prepareBuildSettings(ref BuildSettings settings, const scope ref BuildPlatform platform, BuildSetting fields = BuildSetting.all) const
  106. {
  107. import std.format : format;
  108. enforceBuildRequirements(settings);
  109.  
  110. // Keep the current dflags at the end of the array so that they will overwrite other flags.
  111. // This allows user $DFLAGS to modify flags added by us.
  112. const dflagsTail = settings.dflags;
  113. settings.dflags = [];
  114.  
  115. if (!(fields & BuildSetting.options)) {
  116. foreach (t; s_options)
  117. if (settings.options & t[0])
  118. settings.addDFlags(t[1]);
  119. }
  120.  
  121. // since LDC always outputs multiple object files, avoid conflicts by default
  122. settings.addDFlags("--oq", format("-od=%s/obj", settings.targetPath));
  123.  
  124. if (!(fields & BuildSetting.versions)) {
  125. settings.addDFlags(settings.versions.map!(s => "-d-version="~s)().array());
  126. settings.versions = null;
  127. }
  128.  
  129. if (!(fields & BuildSetting.debugVersions)) {
  130. settings.addDFlags(settings.debugVersions.map!(s => "-d-debug="~s)().array());
  131. settings.debugVersions = null;
  132. }
  133.  
  134. if (!(fields & BuildSetting.importPaths)) {
  135. settings.addDFlags(settings.importPaths.map!(s => "-I"~s)().array());
  136. settings.importPaths = null;
  137. }
  138.  
  139. if (!(fields & BuildSetting.cImportPaths)) {
  140. settings.addDFlags(settings.cImportPaths.map!(s => "-I"~s)().array());
  141. settings.cImportPaths = null;
  142. }
  143.  
  144. if (!(fields & BuildSetting.stringImportPaths)) {
  145. settings.addDFlags(settings.stringImportPaths.map!(s => "-J"~s)().array());
  146. settings.stringImportPaths = null;
  147. }
  148.  
  149. if (!(fields & BuildSetting.sourceFiles)) {
  150. settings.addDFlags(settings.sourceFiles);
  151. settings.sourceFiles = null;
  152. }
  153.  
  154. if (!(fields & BuildSetting.libs)) {
  155. resolveLibs(settings, platform);
  156. settings.addLFlags(settings.libs.map!(l => "-l"~l)().array());
  157. }
  158.  
  159. if (!(fields & BuildSetting.lflags)) {
  160. settings.addDFlags(lflagsToDFlags(settings.lflags));
  161. settings.lflags = null;
  162. }
  163.  
  164. if (settings.options & BuildOption.pic) {
  165. if (platform.isWindows()) {
  166. /* This has nothing to do with PIC, but as the PIC option is exclusively
  167. * set internally for code that ends up in a dynamic library, explicitly
  168. * specify what `-shared` defaults to (`-shared` can't be used when
  169. * compiling only, without linking).
  170. * *Pre*pending the flags enables the user to override them.
  171. */
  172. settings.prependDFlags("-fvisibility=public", "-dllimport=all");
  173. } else {
  174. settings.addDFlags("-relocation-model=pic");
  175. }
  176. }
  177.  
  178. settings.addDFlags(dflagsTail);
  179.  
  180. assert(fields & BuildSetting.dflags);
  181. assert(fields & BuildSetting.copyFiles);
  182. }
  183.  
  184. void extractBuildOptions(ref BuildSettings settings) const
  185. {
  186. Appender!(string[]) newflags;
  187. next_flag: foreach (f; settings.dflags) {
  188. foreach (t; s_options)
  189. if (t[1].canFind(f)) {
  190. settings.options |= t[0];
  191. continue next_flag;
  192. }
  193. if (f.startsWith("-d-version=")) settings.addVersions(f[11 .. $]);
  194. else if (f.startsWith("-d-debug=")) settings.addDebugVersions(f[9 .. $]);
  195. else newflags ~= f;
  196. }
  197. settings.dflags = newflags.data;
  198. }
  199.  
  200. string getTargetFileName(in BuildSettings settings, in BuildPlatform platform)
  201. const {
  202. assert(settings.targetName.length > 0, "No target name set.");
  203.  
  204. const p = platform.platform;
  205. final switch (settings.targetType) {
  206. case TargetType.autodetect: assert(false, "Configurations must have a concrete target type.");
  207. case TargetType.none: return null;
  208. case TargetType.sourceLibrary: return null;
  209. case TargetType.executable:
  210. if (p.canFind("windows"))
  211. return settings.targetName ~ ".exe";
  212. else if (p.canFind("wasm"))
  213. return settings.targetName ~ ".wasm";
  214. else return settings.targetName.idup;
  215. case TargetType.library:
  216. case TargetType.staticLibrary:
  217. if (p.canFind("windows") && !p.canFind("mingw"))
  218. return settings.targetName ~ ".lib";
  219. else return "lib" ~ settings.targetName ~ ".a";
  220. case TargetType.dynamicLibrary:
  221. if (p.canFind("windows"))
  222. return settings.targetName ~ ".dll";
  223. else if (p.canFind("darwin"))
  224. return "lib" ~ settings.targetName ~ ".dylib";
  225. else return "lib" ~ settings.targetName ~ ".so";
  226. case TargetType.object:
  227. if (p.canFind("windows"))
  228. return settings.targetName ~ ".obj";
  229. else return settings.targetName ~ ".o";
  230. }
  231. }
  232.  
  233. void setTarget(ref BuildSettings settings, in BuildPlatform platform, string tpath = null) const
  234. {
  235. const targetFileName = getTargetFileName(settings, platform);
  236.  
  237. final switch (settings.targetType) {
  238. case TargetType.autodetect: assert(false, "Invalid target type: autodetect");
  239. case TargetType.none: assert(false, "Invalid target type: none");
  240. case TargetType.sourceLibrary: assert(false, "Invalid target type: sourceLibrary");
  241. case TargetType.executable: break;
  242. case TargetType.library:
  243. case TargetType.staticLibrary:
  244. settings.addDFlags("-lib");
  245. break;
  246. case TargetType.dynamicLibrary:
  247. settings.addDFlags("-shared");
  248. addDynamicLibName(settings, platform, targetFileName);
  249. break;
  250. case TargetType.object:
  251. settings.addDFlags("-c");
  252. break;
  253. }
  254.  
  255. if (tpath is null)
  256. tpath = (NativePath(settings.targetPath) ~ targetFileName).toNativeString();
  257. settings.addDFlags("-of"~tpath);
  258. }
  259.  
  260. void invoke(in BuildSettings settings, in BuildPlatform platform, void delegate(int, string) output_callback, NativePath cwd)
  261. {
  262. auto res_file = getTempFile("dub-build", ".rsp");
  263. const(string)[] args = settings.dflags;
  264. if (platform.frontendVersion >= 2066) args ~= "-vcolumns";
  265. writeFile(res_file, escapeArgs(args).join("\n"));
  266.  
  267. logDiagnostic("%s %s", platform.compilerBinary, escapeArgs(args).join(" "));
  268. string[string] env;
  269. foreach (aa; [settings.environments, settings.buildEnvironments])
  270. foreach (k, v; aa)
  271. env[k] = v;
  272. invokeTool([platform.compilerBinary, "@"~res_file.toNativeString()], output_callback, cwd, env);
  273. }
  274.  
  275. void invokeLinker(in BuildSettings settings, in BuildPlatform platform, string[] objects, void delegate(int, string) output_callback, NativePath cwd)
  276. {
  277. import std.string;
  278. auto tpath = NativePath(settings.targetPath) ~ getTargetFileName(settings, platform);
  279. auto args = ["-of"~tpath.toNativeString()];
  280. args ~= objects;
  281. args ~= settings.sourceFiles;
  282. if (platform.platform.canFind("linux"))
  283. args ~= "-L--no-as-needed"; // avoids linker errors due to libraries being specified in the wrong order
  284. args ~= lflagsToDFlags(settings.lflags);
  285. args ~= settings.dflags.filter!(f => isLinkerDFlag(f)).array;
  286.  
  287. auto res_file = getTempFile("dub-build", ".lnk");
  288. writeFile(res_file, escapeArgs(args).join("\n"));
  289.  
  290. logDiagnostic("%s %s", platform.compilerBinary, escapeArgs(args).join(" "));
  291. string[string] env;
  292. foreach (aa; [settings.environments, settings.buildEnvironments])
  293. foreach (k, v; aa)
  294. env[k] = v;
  295. invokeTool([platform.compilerBinary, "@"~res_file.toNativeString()], output_callback, cwd, env);
  296. }
  297.  
  298. string[] lflagsToDFlags(const string[] lflags) const
  299. {
  300. return map!(f => "-L"~f)(lflags.filter!(f => f != "")()).array();
  301. }
  302.  
  303. private auto escapeArgs(in string[] args)
  304. {
  305. return args.map!(s => s.canFind(' ') ? "\""~s~"\"" : s);
  306. }
  307.  
  308. static bool isLinkerDFlag(string arg)
  309. {
  310. if (arg.length > 2 && arg.startsWith("--"))
  311. arg = arg[1 .. $]; // normalize to 1 leading hyphen
  312.  
  313. switch (arg) {
  314. case "-g", "-gc", "-m32", "-m64", "-shared", "-lib",
  315. "-betterC", "-disable-linker-strip-dead", "-static":
  316. return true;
  317. default:
  318. return arg.startsWith("-L")
  319. || arg.startsWith("-Xcc=")
  320. || arg.startsWith("-defaultlib=")
  321. || arg.startsWith("-platformlib=")
  322. || arg.startsWith("-flto")
  323. || arg.startsWith("-fsanitize=")
  324. || arg.startsWith("-gcc=")
  325. || arg.startsWith("-link-")
  326. || arg.startsWith("-linker=")
  327. || arg.startsWith("-march=")
  328. || arg.startsWith("-mscrtlib=")
  329. || arg.startsWith("-mtriple=");
  330. }
  331. }
  332. }