1 //===- Args.cpp -----------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lld/Common/Args.h"
10 #include "lld/Common/ErrorHandler.h"
11 #include "llvm/ADT/SmallVector.h"
12 #include "llvm/ADT/StringExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/Path.h"
16 
17 using namespace llvm;
18 using namespace lld;
19 
20 // TODO(sbc): Remove this once CGOptLevel can be set completely based on bitcode
21 // function metadata.
22 CodeGenOpt::Level lld::args::getCGOptLevel(int optLevelLTO) {
23   if (optLevelLTO == 3)
24     return CodeGenOpt::Aggressive;
25   assert(optLevelLTO < 3);
26   return CodeGenOpt::Default;
27 }
28 
29 int64_t lld::args::getInteger(opt::InputArgList &args, unsigned key,
30                               int64_t Default) {
31   auto *a = args.getLastArg(key);
32   if (!a)
33     return Default;
34 
35   int64_t v;
36   if (to_integer(a->getValue(), v, 10))
37     return v;
38 
39   StringRef spelling = args.getArgString(a->getIndex());
40   error(spelling + ": number expected, but got '" + a->getValue() + "'");
41   return 0;
42 }
43 
44 std::vector<StringRef> lld::args::getStrings(opt::InputArgList &args, int id) {
45   std::vector<StringRef> v;
46   for (auto *arg : args.filtered(id))
47     v.push_back(arg->getValue());
48   return v;
49 }
50 
51 uint64_t lld::args::getZOptionValue(opt::InputArgList &args, int id,
52                                     StringRef key, uint64_t Default) {
53   for (auto *arg : args.filtered_reverse(id)) {
54     std::pair<StringRef, StringRef> kv = StringRef(arg->getValue()).split('=');
55     if (kv.first == key) {
56       uint64_t result = Default;
57       if (!to_integer(kv.second, result))
58         error("invalid " + key + ": " + kv.second);
59       return result;
60     }
61   }
62   return Default;
63 }
64 
65 std::vector<StringRef> lld::args::getLines(MemoryBufferRef mb) {
66   SmallVector<StringRef, 0> arr;
67   mb.getBuffer().split(arr, '\n');
68 
69   std::vector<StringRef> ret;
70   for (StringRef s : arr) {
71     s = s.trim();
72     if (!s.empty() && s[0] != '#')
73       ret.push_back(s);
74   }
75   return ret;
76 }
77 
78 StringRef lld::args::getFilenameWithoutExe(StringRef path) {
79   if (path.endswith_lower(".exe"))
80     return sys::path::stem(path);
81   return sys::path::filename(path);
82 }
83