File: | tools/lld/lib/Driver/DarwinLdDriver.cpp |
Warning: | line 534, column 24 The result of the left shift is undefined due to shifting by '64', which is greater or equal to the width of type 'int' |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- lib/Driver/DarwinLdDriver.cpp --------------------------------------===// | |||
2 | // | |||
3 | // The LLVM Linker | |||
4 | // | |||
5 | // This file is distributed under the University of Illinois Open Source | |||
6 | // License. See LICENSE.TXT for details. | |||
7 | // | |||
8 | //===----------------------------------------------------------------------===// | |||
9 | /// | |||
10 | /// \file | |||
11 | /// | |||
12 | /// Concrete instance of the Driver for darwin's ld. | |||
13 | /// | |||
14 | //===----------------------------------------------------------------------===// | |||
15 | ||||
16 | #include "lld/Common/Args.h" | |||
17 | #include "lld/Common/ErrorHandler.h" | |||
18 | #include "lld/Common/LLVM.h" | |||
19 | #include "lld/Core/ArchiveLibraryFile.h" | |||
20 | #include "lld/Core/Error.h" | |||
21 | #include "lld/Core/File.h" | |||
22 | #include "lld/Core/Instrumentation.h" | |||
23 | #include "lld/Core/LinkingContext.h" | |||
24 | #include "lld/Core/Node.h" | |||
25 | #include "lld/Core/PassManager.h" | |||
26 | #include "lld/Core/Resolver.h" | |||
27 | #include "lld/Core/SharedLibraryFile.h" | |||
28 | #include "lld/Core/Simple.h" | |||
29 | #include "lld/ReaderWriter/MachOLinkingContext.h" | |||
30 | #include "llvm/ADT/ArrayRef.h" | |||
31 | #include "llvm/ADT/Optional.h" | |||
32 | #include "llvm/ADT/STLExtras.h" | |||
33 | #include "llvm/ADT/SmallString.h" | |||
34 | #include "llvm/ADT/StringExtras.h" | |||
35 | #include "llvm/ADT/StringRef.h" | |||
36 | #include "llvm/ADT/Twine.h" | |||
37 | #include "llvm/BinaryFormat/MachO.h" | |||
38 | #include "llvm/Option/Arg.h" | |||
39 | #include "llvm/Option/ArgList.h" | |||
40 | #include "llvm/Option/OptTable.h" | |||
41 | #include "llvm/Option/Option.h" | |||
42 | #include "llvm/Support/Casting.h" | |||
43 | #include "llvm/Support/CommandLine.h" | |||
44 | #include "llvm/Support/Error.h" | |||
45 | #include "llvm/Support/ErrorOr.h" | |||
46 | #include "llvm/Support/Format.h" | |||
47 | #include "llvm/Support/MathExtras.h" | |||
48 | #include "llvm/Support/MemoryBuffer.h" | |||
49 | #include "llvm/Support/Path.h" | |||
50 | #include "llvm/Support/raw_ostream.h" | |||
51 | #include <algorithm> | |||
52 | #include <cstdint> | |||
53 | #include <memory> | |||
54 | #include <string> | |||
55 | #include <system_error> | |||
56 | #include <utility> | |||
57 | #include <vector> | |||
58 | ||||
59 | using namespace lld; | |||
60 | ||||
61 | namespace { | |||
62 | ||||
63 | // Create enum with OPT_xxx values for each option in DarwinLdOptions.td | |||
64 | enum { | |||
65 | OPT_INVALID = 0, | |||
66 | #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ | |||
67 | HELP, META, VALUES) \ | |||
68 | OPT_##ID, | |||
69 | #include "DarwinLdOptions.inc" | |||
70 | #undef OPTION | |||
71 | }; | |||
72 | ||||
73 | // Create prefix string literals used in DarwinLdOptions.td | |||
74 | #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; | |||
75 | #include "DarwinLdOptions.inc" | |||
76 | #undef PREFIX | |||
77 | ||||
78 | // Create table mapping all options defined in DarwinLdOptions.td | |||
79 | static const llvm::opt::OptTable::Info InfoTable[] = { | |||
80 | #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ | |||
81 | HELPTEXT, METAVAR, VALUES) \ | |||
82 | {PREFIX, NAME, HELPTEXT, \ | |||
83 | METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \ | |||
84 | PARAM, FLAGS, OPT_##GROUP, \ | |||
85 | OPT_##ALIAS, ALIASARGS, VALUES}, | |||
86 | #include "DarwinLdOptions.inc" | |||
87 | #undef OPTION | |||
88 | }; | |||
89 | ||||
90 | // Create OptTable class for parsing actual command line arguments | |||
91 | class DarwinLdOptTable : public llvm::opt::OptTable { | |||
92 | public: | |||
93 | DarwinLdOptTable() : OptTable(InfoTable) {} | |||
94 | }; | |||
95 | ||||
96 | static std::vector<std::unique_ptr<File>> | |||
97 | makeErrorFile(StringRef path, std::error_code ec) { | |||
98 | std::vector<std::unique_ptr<File>> result; | |||
99 | result.push_back(llvm::make_unique<ErrorFile>(path, ec)); | |||
100 | return result; | |||
101 | } | |||
102 | ||||
103 | static std::vector<std::unique_ptr<File>> | |||
104 | parseMemberFiles(std::unique_ptr<File> file) { | |||
105 | std::vector<std::unique_ptr<File>> members; | |||
106 | if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) { | |||
107 | if (std::error_code ec = archive->parseAllMembers(members)) | |||
108 | return makeErrorFile(file->path(), ec); | |||
109 | } else { | |||
110 | members.push_back(std::move(file)); | |||
111 | } | |||
112 | return members; | |||
113 | } | |||
114 | ||||
115 | std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx, | |||
116 | StringRef path, bool wholeArchive, | |||
117 | bool upwardDylib) { | |||
118 | if (ctx.logInputFiles()) | |||
119 | message(path); | |||
120 | ||||
121 | ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path); | |||
122 | if (std::error_code ec = mbOrErr.getError()) | |||
123 | return makeErrorFile(path, ec); | |||
124 | ErrorOr<std::unique_ptr<File>> fileOrErr = | |||
125 | ctx.registry().loadFile(std::move(mbOrErr.get())); | |||
126 | if (std::error_code ec = fileOrErr.getError()) | |||
127 | return makeErrorFile(path, ec); | |||
128 | std::unique_ptr<File> &file = fileOrErr.get(); | |||
129 | ||||
130 | // If file is a dylib, inform LinkingContext about it. | |||
131 | if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) { | |||
132 | if (std::error_code ec = shl->parse()) | |||
133 | return makeErrorFile(path, ec); | |||
134 | ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl), | |||
135 | upwardDylib); | |||
136 | } | |||
137 | if (wholeArchive) | |||
138 | return parseMemberFiles(std::move(file)); | |||
139 | std::vector<std::unique_ptr<File>> files; | |||
140 | files.push_back(std::move(file)); | |||
141 | return files; | |||
142 | } | |||
143 | ||||
144 | } // end anonymous namespace | |||
145 | ||||
146 | // Test may be running on Windows. Canonicalize the path | |||
147 | // separator to '/' to get consistent outputs for tests. | |||
148 | static std::string canonicalizePath(StringRef path) { | |||
149 | char sep = llvm::sys::path::get_separator().front(); | |||
150 | if (sep != '/') { | |||
151 | std::string fixedPath = path; | |||
152 | std::replace(fixedPath.begin(), fixedPath.end(), sep, '/'); | |||
153 | return fixedPath; | |||
154 | } else { | |||
155 | return path; | |||
156 | } | |||
157 | } | |||
158 | ||||
159 | static void addFile(StringRef path, MachOLinkingContext &ctx, | |||
160 | bool loadWholeArchive, bool upwardDylib) { | |||
161 | std::vector<std::unique_ptr<File>> files = | |||
162 | loadFile(ctx, path, loadWholeArchive, upwardDylib); | |||
163 | for (std::unique_ptr<File> &file : files) | |||
164 | ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file))); | |||
165 | } | |||
166 | ||||
167 | // Export lists are one symbol per line. Blank lines are ignored. | |||
168 | // Trailing comments start with #. | |||
169 | static std::error_code parseExportsList(StringRef exportFilePath, | |||
170 | MachOLinkingContext &ctx) { | |||
171 | // Map in export list file. | |||
172 | ErrorOr<std::unique_ptr<MemoryBuffer>> mb = | |||
173 | MemoryBuffer::getFileOrSTDIN(exportFilePath); | |||
174 | if (std::error_code ec = mb.getError()) | |||
175 | return ec; | |||
176 | ctx.addInputFileDependency(exportFilePath); | |||
177 | StringRef buffer = mb->get()->getBuffer(); | |||
178 | while (!buffer.empty()) { | |||
179 | // Split off each line in the file. | |||
180 | std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n'); | |||
181 | StringRef line = lineAndRest.first; | |||
182 | // Ignore trailing # comments. | |||
183 | std::pair<StringRef, StringRef> symAndComment = line.split('#'); | |||
184 | StringRef sym = symAndComment.first.trim(); | |||
185 | if (!sym.empty()) | |||
186 | ctx.addExportSymbol(sym); | |||
187 | buffer = lineAndRest.second; | |||
188 | } | |||
189 | return std::error_code(); | |||
190 | } | |||
191 | ||||
192 | /// Order files are one symbol per line. Blank lines are ignored. | |||
193 | /// Trailing comments start with #. Symbol names can be prefixed with an | |||
194 | /// architecture name and/or .o leaf name. Examples: | |||
195 | /// _foo | |||
196 | /// bar.o:_bar | |||
197 | /// libfrob.a(bar.o):_bar | |||
198 | /// x86_64:_foo64 | |||
199 | static std::error_code parseOrderFile(StringRef orderFilePath, | |||
200 | MachOLinkingContext &ctx) { | |||
201 | // Map in order file. | |||
202 | ErrorOr<std::unique_ptr<MemoryBuffer>> mb = | |||
203 | MemoryBuffer::getFileOrSTDIN(orderFilePath); | |||
204 | if (std::error_code ec = mb.getError()) | |||
205 | return ec; | |||
206 | ctx.addInputFileDependency(orderFilePath); | |||
207 | StringRef buffer = mb->get()->getBuffer(); | |||
208 | while (!buffer.empty()) { | |||
209 | // Split off each line in the file. | |||
210 | std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n'); | |||
211 | StringRef line = lineAndRest.first; | |||
212 | buffer = lineAndRest.second; | |||
213 | // Ignore trailing # comments. | |||
214 | std::pair<StringRef, StringRef> symAndComment = line.split('#'); | |||
215 | if (symAndComment.first.empty()) | |||
216 | continue; | |||
217 | StringRef sym = symAndComment.first.trim(); | |||
218 | if (sym.empty()) | |||
219 | continue; | |||
220 | // Check for prefix. | |||
221 | StringRef prefix; | |||
222 | std::pair<StringRef, StringRef> prefixAndSym = sym.split(':'); | |||
223 | if (!prefixAndSym.second.empty()) { | |||
224 | sym = prefixAndSym.second; | |||
225 | prefix = prefixAndSym.first; | |||
226 | if (!prefix.endswith(".o") && !prefix.endswith(".o)")) { | |||
227 | // If arch name prefix does not match arch being linked, ignore symbol. | |||
228 | if (!ctx.archName().equals(prefix)) | |||
229 | continue; | |||
230 | prefix = ""; | |||
231 | } | |||
232 | } else | |||
233 | sym = prefixAndSym.first; | |||
234 | if (!sym.empty()) { | |||
235 | ctx.appendOrderedSymbol(sym, prefix); | |||
236 | //llvm::errs() << sym << ", prefix=" << prefix << "\n"; | |||
237 | } | |||
238 | } | |||
239 | return std::error_code(); | |||
240 | } | |||
241 | ||||
242 | // | |||
243 | // There are two variants of the -filelist option: | |||
244 | // | |||
245 | // -filelist <path> | |||
246 | // In this variant, the path is to a text file which contains one file path | |||
247 | // per line. There are no comments or trimming of whitespace. | |||
248 | // | |||
249 | // -fileList <path>,<dir> | |||
250 | // In this variant, the path is to a text file which contains a partial path | |||
251 | // per line. The <dir> prefix is prepended to each partial path. | |||
252 | // | |||
253 | static llvm::Error loadFileList(StringRef fileListPath, | |||
254 | MachOLinkingContext &ctx, bool forceLoad) { | |||
255 | // If there is a comma, split off <dir>. | |||
256 | std::pair<StringRef, StringRef> opt = fileListPath.split(','); | |||
257 | StringRef filePath = opt.first; | |||
258 | StringRef dirName = opt.second; | |||
259 | ctx.addInputFileDependency(filePath); | |||
260 | // Map in file list file. | |||
261 | ErrorOr<std::unique_ptr<MemoryBuffer>> mb = | |||
262 | MemoryBuffer::getFileOrSTDIN(filePath); | |||
263 | if (std::error_code ec = mb.getError()) | |||
264 | return llvm::errorCodeToError(ec); | |||
265 | StringRef buffer = mb->get()->getBuffer(); | |||
266 | while (!buffer.empty()) { | |||
267 | // Split off each line in the file. | |||
268 | std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n'); | |||
269 | StringRef line = lineAndRest.first; | |||
270 | StringRef path; | |||
271 | if (!dirName.empty()) { | |||
272 | // If there is a <dir> then prepend dir to each line. | |||
273 | SmallString<256> fullPath; | |||
274 | fullPath.assign(dirName); | |||
275 | llvm::sys::path::append(fullPath, Twine(line)); | |||
276 | path = ctx.copy(fullPath.str()); | |||
277 | } else { | |||
278 | // No <dir> use whole line as input file path. | |||
279 | path = ctx.copy(line); | |||
280 | } | |||
281 | if (!ctx.pathExists(path)) { | |||
282 | return llvm::make_error<GenericError>(Twine("File not found '") | |||
283 | + path | |||
284 | + "'"); | |||
285 | } | |||
286 | if (ctx.testingFileUsage()) { | |||
287 | message("Found filelist entry " + canonicalizePath(path)); | |||
288 | } | |||
289 | addFile(path, ctx, forceLoad, false); | |||
290 | buffer = lineAndRest.second; | |||
291 | } | |||
292 | return llvm::Error::success(); | |||
293 | } | |||
294 | ||||
295 | /// Parse number assuming it is base 16, but allow 0x prefix. | |||
296 | static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) { | |||
297 | if (numStr.startswith_lower("0x")) | |||
298 | numStr = numStr.drop_front(2); | |||
299 | return numStr.getAsInteger(16, baseAddress); | |||
300 | } | |||
301 | ||||
302 | static void parseLLVMOptions(const LinkingContext &ctx) { | |||
303 | // Honor -mllvm | |||
304 | if (!ctx.llvmOptions().empty()) { | |||
305 | unsigned numArgs = ctx.llvmOptions().size(); | |||
306 | auto **args = new const char *[numArgs + 2]; | |||
307 | args[0] = "lld (LLVM option parsing)"; | |||
308 | for (unsigned i = 0; i != numArgs; ++i) | |||
309 | args[i + 1] = ctx.llvmOptions()[i]; | |||
310 | args[numArgs + 1] = nullptr; | |||
311 | llvm::cl::ParseCommandLineOptions(numArgs + 1, args); | |||
312 | } | |||
313 | } | |||
314 | ||||
315 | namespace lld { | |||
316 | namespace mach_o { | |||
317 | ||||
318 | bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) { | |||
319 | // Parse command line options using DarwinLdOptions.td | |||
320 | DarwinLdOptTable table; | |||
321 | unsigned missingIndex; | |||
322 | unsigned missingCount; | |||
323 | llvm::opt::InputArgList parsedArgs = | |||
324 | table.ParseArgs(args.slice(1), missingIndex, missingCount); | |||
325 | if (missingCount) { | |||
| ||||
326 | error("missing arg value for '" + | |||
327 | Twine(parsedArgs.getArgString(missingIndex)) + "' expected " + | |||
328 | Twine(missingCount) + " argument(s)."); | |||
329 | return false; | |||
330 | } | |||
331 | ||||
332 | for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) { | |||
333 | warn("ignoring unknown argument: " + | |||
334 | Twine(unknownArg->getAsString(parsedArgs))); | |||
335 | } | |||
336 | ||||
337 | errorHandler().Verbose = parsedArgs.hasArg(OPT_v); | |||
338 | errorHandler().ErrorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20); | |||
339 | ||||
340 | // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static ) | |||
341 | llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE; | |||
342 | bool isStaticExecutable = false; | |||
343 | if (llvm::opt::Arg *kind = parsedArgs.getLastArg( | |||
344 | OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) { | |||
345 | switch (kind->getOption().getID()) { | |||
346 | case OPT_dylib: | |||
347 | fileType = llvm::MachO::MH_DYLIB; | |||
348 | break; | |||
349 | case OPT_relocatable: | |||
350 | fileType = llvm::MachO::MH_OBJECT; | |||
351 | break; | |||
352 | case OPT_bundle: | |||
353 | fileType = llvm::MachO::MH_BUNDLE; | |||
354 | break; | |||
355 | case OPT_static: | |||
356 | fileType = llvm::MachO::MH_EXECUTE; | |||
357 | isStaticExecutable = true; | |||
358 | break; | |||
359 | case OPT_preload: | |||
360 | fileType = llvm::MachO::MH_PRELOAD; | |||
361 | break; | |||
362 | } | |||
363 | } | |||
364 | ||||
365 | // Handle -arch xxx | |||
366 | MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown; | |||
367 | if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) { | |||
368 | arch = MachOLinkingContext::archFromName(archStr->getValue()); | |||
369 | if (arch == MachOLinkingContext::arch_unknown) { | |||
370 | error("unknown arch named '" + Twine(archStr->getValue()) + "'"); | |||
371 | return false; | |||
372 | } | |||
373 | } | |||
374 | // If no -arch specified, scan input files to find first non-fat .o file. | |||
375 | if (arch == MachOLinkingContext::arch_unknown) { | |||
376 | for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) { | |||
377 | // This is expensive because it opens and maps the file. But that is | |||
378 | // ok because no -arch is rare. | |||
379 | if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch)) | |||
380 | break; | |||
381 | } | |||
382 | if (arch == MachOLinkingContext::arch_unknown && | |||
383 | !parsedArgs.getLastArg(OPT_test_file_usage)) { | |||
384 | // If no -arch and no options at all, print usage message. | |||
385 | if (parsedArgs.size() == 0) { | |||
386 | table.PrintHelp(llvm::outs(), | |||
387 | (std::string(args[0]) + " [options] file...").c_str(), | |||
388 | "LLVM Linker", false); | |||
389 | } else { | |||
390 | error("-arch not specified and could not be inferred"); | |||
391 | } | |||
392 | return false; | |||
393 | } | |||
394 | } | |||
395 | ||||
396 | // Handle -macosx_version_min or -ios_version_min | |||
397 | MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown; | |||
398 | uint32_t minOSVersion = 0; | |||
399 | if (llvm::opt::Arg *minOS = | |||
400 | parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min, | |||
401 | OPT_ios_simulator_version_min)) { | |||
402 | switch (minOS->getOption().getID()) { | |||
403 | case OPT_macosx_version_min: | |||
404 | os = MachOLinkingContext::OS::macOSX; | |||
405 | if (MachOLinkingContext::parsePackedVersion(minOS->getValue(), | |||
406 | minOSVersion)) { | |||
407 | error("malformed macosx_version_min value"); | |||
408 | return false; | |||
409 | } | |||
410 | break; | |||
411 | case OPT_ios_version_min: | |||
412 | os = MachOLinkingContext::OS::iOS; | |||
413 | if (MachOLinkingContext::parsePackedVersion(minOS->getValue(), | |||
414 | minOSVersion)) { | |||
415 | error("malformed ios_version_min value"); | |||
416 | return false; | |||
417 | } | |||
418 | break; | |||
419 | case OPT_ios_simulator_version_min: | |||
420 | os = MachOLinkingContext::OS::iOS_simulator; | |||
421 | if (MachOLinkingContext::parsePackedVersion(minOS->getValue(), | |||
422 | minOSVersion)) { | |||
423 | error("malformed ios_simulator_version_min value"); | |||
424 | return false; | |||
425 | } | |||
426 | break; | |||
427 | } | |||
428 | } else { | |||
429 | // No min-os version on command line, check environment variables | |||
430 | } | |||
431 | ||||
432 | // Handle export_dynamic | |||
433 | // FIXME: Should we warn when this applies to something other than a static | |||
434 | // executable or dylib? Those are the only cases where this has an effect. | |||
435 | // Note, this has to come before ctx.configure() so that we get the correct | |||
436 | // value for _globalsAreDeadStripRoots. | |||
437 | bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic); | |||
438 | ||||
439 | // Now that there's enough information parsed in, let the linking context | |||
440 | // set up default values. | |||
441 | ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols); | |||
442 | ||||
443 | // Handle -e xxx | |||
444 | if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry)) | |||
445 | ctx.setEntrySymbolName(entry->getValue()); | |||
446 | ||||
447 | // Handle -o xxx | |||
448 | if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output)) | |||
449 | ctx.setOutputPath(outpath->getValue()); | |||
450 | else | |||
451 | ctx.setOutputPath("a.out"); | |||
452 | ||||
453 | // Handle -image_base XXX and -seg1addr XXXX | |||
454 | if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) { | |||
455 | uint64_t baseAddress; | |||
456 | if (parseNumberBase16(imageBase->getValue(), baseAddress)) { | |||
457 | error("image_base expects a hex number"); | |||
458 | return false; | |||
459 | } else if (baseAddress < ctx.pageZeroSize()) { | |||
460 | error("image_base overlaps with __PAGEZERO"); | |||
461 | return false; | |||
462 | } else if (baseAddress % ctx.pageSize()) { | |||
463 | error("image_base must be a multiple of page size (0x" + | |||
464 | llvm::utohexstr(ctx.pageSize()) + ")"); | |||
465 | return false; | |||
466 | } | |||
467 | ||||
468 | ctx.setBaseAddress(baseAddress); | |||
469 | } | |||
470 | ||||
471 | // Handle -dead_strip | |||
472 | if (parsedArgs.getLastArg(OPT_dead_strip)) | |||
473 | ctx.setDeadStripping(true); | |||
474 | ||||
475 | bool globalWholeArchive = false; | |||
476 | // Handle -all_load | |||
477 | if (parsedArgs.getLastArg(OPT_all_load)) | |||
478 | globalWholeArchive = true; | |||
479 | ||||
480 | // Handle -install_name | |||
481 | if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name)) | |||
482 | ctx.setInstallName(installName->getValue()); | |||
483 | else | |||
484 | ctx.setInstallName(ctx.outputPath()); | |||
485 | ||||
486 | // Handle -mark_dead_strippable_dylib | |||
487 | if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib)) | |||
488 | ctx.setDeadStrippableDylib(true); | |||
489 | ||||
490 | // Handle -compatibility_version and -current_version | |||
491 | if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) { | |||
492 | if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) { | |||
493 | error("-compatibility_version can only be used with -dylib"); | |||
494 | return false; | |||
495 | } | |||
496 | uint32_t parsedVers; | |||
497 | if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) { | |||
498 | error("-compatibility_version value is malformed"); | |||
499 | return false; | |||
500 | } | |||
501 | ctx.setCompatibilityVersion(parsedVers); | |||
502 | } | |||
503 | ||||
504 | if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) { | |||
505 | if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) { | |||
506 | error("-current_version can only be used with -dylib"); | |||
507 | return false; | |||
508 | } | |||
509 | uint32_t parsedVers; | |||
510 | if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) { | |||
511 | error("-current_version value is malformed"); | |||
512 | return false; | |||
513 | } | |||
514 | ctx.setCurrentVersion(parsedVers); | |||
515 | } | |||
516 | ||||
517 | // Handle -bundle_loader | |||
518 | if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader)) | |||
519 | ctx.setBundleLoader(loader->getValue()); | |||
520 | ||||
521 | // Handle -sectalign segname sectname align | |||
522 | for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) { | |||
523 | const char* segName = alignArg->getValue(0); | |||
524 | const char* sectName = alignArg->getValue(1); | |||
525 | const char* alignStr = alignArg->getValue(2); | |||
526 | if ((alignStr[0] == '0') && (alignStr[1] == 'x')) | |||
527 | alignStr += 2; | |||
528 | unsigned long long alignValue; | |||
529 | if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) { | |||
530 | error("-sectalign alignment value '" + Twine(alignStr) + | |||
531 | "' not a valid number"); | |||
532 | return false; | |||
533 | } | |||
534 | uint16_t align = 1 << llvm::countTrailingZeros(alignValue); | |||
| ||||
535 | if (!llvm::isPowerOf2_64(alignValue)) { | |||
536 | std::string Msg; | |||
537 | llvm::raw_string_ostream OS(Msg); | |||
538 | OS << "alignment for '-sectalign " << segName << " " << sectName | |||
539 | << llvm::format(" 0x%llX", alignValue) | |||
540 | << "' is not a power of two, using " << llvm::format("0x%08X", align); | |||
541 | OS.flush(); | |||
542 | warn(Msg); | |||
543 | } | |||
544 | ctx.addSectionAlignment(segName, sectName, align); | |||
545 | } | |||
546 | ||||
547 | // Handle -mllvm | |||
548 | for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) { | |||
549 | ctx.appendLLVMOption(llvmArg->getValue()); | |||
550 | } | |||
551 | ||||
552 | // Handle -print_atoms | |||
553 | if (parsedArgs.getLastArg(OPT_print_atoms)) | |||
554 | ctx.setPrintAtoms(); | |||
555 | ||||
556 | // Handle -t (trace) option. | |||
557 | if (parsedArgs.getLastArg(OPT_t)) | |||
558 | ctx.setLogInputFiles(true); | |||
559 | ||||
560 | // Handle -demangle option. | |||
561 | if (parsedArgs.getLastArg(OPT_demangle)) | |||
562 | ctx.setDemangleSymbols(true); | |||
563 | ||||
564 | // Handle -keep_private_externs | |||
565 | if (parsedArgs.getLastArg(OPT_keep_private_externs)) { | |||
566 | ctx.setKeepPrivateExterns(true); | |||
567 | if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT) | |||
568 | warn("-keep_private_externs only used in -r mode"); | |||
569 | } | |||
570 | ||||
571 | // Handle -dependency_info <path> used by Xcode. | |||
572 | if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info)) | |||
573 | if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue())) | |||
574 | warn(ec.message() + ", processing '-dependency_info " + | |||
575 | depInfo->getValue()); | |||
576 | ||||
577 | // In -test_file_usage mode, we'll be given an explicit list of paths that | |||
578 | // exist. We'll also be expected to print out information about how we located | |||
579 | // libraries and so on that the user specified, but not to actually do any | |||
580 | // linking. | |||
581 | if (parsedArgs.getLastArg(OPT_test_file_usage)) { | |||
582 | ctx.setTestingFileUsage(); | |||
583 | ||||
584 | // With paths existing by fiat, linking is not going to end well. | |||
585 | ctx.setDoNothing(true); | |||
586 | ||||
587 | // Only bother looking for an existence override if we're going to use it. | |||
588 | for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) { | |||
589 | ctx.addExistingPathForDebug(existingPath->getValue()); | |||
590 | } | |||
591 | } | |||
592 | ||||
593 | // Register possible input file parsers. | |||
594 | if (!ctx.doNothing()) { | |||
595 | ctx.registry().addSupportMachOObjects(ctx); | |||
596 | ctx.registry().addSupportArchives(ctx.logInputFiles()); | |||
597 | ctx.registry().addSupportYamlFiles(); | |||
598 | } | |||
599 | ||||
600 | // Now construct the set of library search directories, following ld64's | |||
601 | // baroque set of accumulated hacks. Mostly, the algorithm constructs | |||
602 | // { syslibroots } x { libpaths } | |||
603 | // | |||
604 | // Unfortunately, there are numerous exceptions: | |||
605 | // 1. Only absolute paths get modified by syslibroot options. | |||
606 | // 2. If there is just 1 -syslibroot, system paths not found in it are | |||
607 | // skipped. | |||
608 | // 3. If the last -syslibroot is "/", all of them are ignored entirely. | |||
609 | // 4. If { syslibroots } x path == {}, the original path is kept. | |||
610 | std::vector<StringRef> sysLibRoots; | |||
611 | for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) { | |||
612 | sysLibRoots.push_back(syslibRoot->getValue()); | |||
613 | } | |||
614 | if (!sysLibRoots.empty()) { | |||
615 | // Ignore all if last -syslibroot is "/". | |||
616 | if (sysLibRoots.back() != "/") | |||
617 | ctx.setSysLibRoots(sysLibRoots); | |||
618 | } | |||
619 | ||||
620 | // Paths specified with -L come first, and are not considered system paths for | |||
621 | // the case where there is precisely 1 -syslibroot. | |||
622 | for (auto libPath : parsedArgs.filtered(OPT_L)) { | |||
623 | ctx.addModifiedSearchDir(libPath->getValue()); | |||
624 | } | |||
625 | ||||
626 | // Process -F directories (where to look for frameworks). | |||
627 | for (auto fwPath : parsedArgs.filtered(OPT_F)) { | |||
628 | ctx.addFrameworkSearchDir(fwPath->getValue()); | |||
629 | } | |||
630 | ||||
631 | // -Z suppresses the standard search paths. | |||
632 | if (!parsedArgs.hasArg(OPT_Z)) { | |||
633 | ctx.addModifiedSearchDir("/usr/lib", true); | |||
634 | ctx.addModifiedSearchDir("/usr/local/lib", true); | |||
635 | ctx.addFrameworkSearchDir("/Library/Frameworks", true); | |||
636 | ctx.addFrameworkSearchDir("/System/Library/Frameworks", true); | |||
637 | } | |||
638 | ||||
639 | // Now that we've constructed the final set of search paths, print out those | |||
640 | // search paths in verbose mode. | |||
641 | if (errorHandler().Verbose) { | |||
642 | message("Library search paths:"); | |||
643 | for (auto path : ctx.searchDirs()) { | |||
644 | message(" " + path); | |||
645 | } | |||
646 | message("Framework search paths:"); | |||
647 | for (auto path : ctx.frameworkDirs()) { | |||
648 | message(" " + path); | |||
649 | } | |||
650 | } | |||
651 | ||||
652 | // Handle -exported_symbols_list <file> | |||
653 | for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) { | |||
654 | if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) { | |||
655 | error("-exported_symbols_list cannot be combined with " | |||
656 | "-unexported_symbol[s_list]"); | |||
657 | return false; | |||
658 | } | |||
659 | ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList); | |||
660 | if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) { | |||
661 | error(ec.message() + ", processing '-exported_symbols_list " + | |||
662 | expFile->getValue()); | |||
663 | return false; | |||
664 | } | |||
665 | } | |||
666 | ||||
667 | // Handle -exported_symbol <symbol> | |||
668 | for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) { | |||
669 | if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) { | |||
670 | error("-exported_symbol cannot be combined with " | |||
671 | "-unexported_symbol[s_list]"); | |||
672 | return false; | |||
673 | } | |||
674 | ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList); | |||
675 | ctx.addExportSymbol(symbol->getValue()); | |||
676 | } | |||
677 | ||||
678 | // Handle -unexported_symbols_list <file> | |||
679 | for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) { | |||
680 | if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) { | |||
681 | error("-unexported_symbols_list cannot be combined with " | |||
682 | "-exported_symbol[s_list]"); | |||
683 | return false; | |||
684 | } | |||
685 | ctx.setExportMode(MachOLinkingContext::ExportMode::blackList); | |||
686 | if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) { | |||
687 | error(ec.message() + ", processing '-unexported_symbols_list " + | |||
688 | expFile->getValue()); | |||
689 | return false; | |||
690 | } | |||
691 | } | |||
692 | ||||
693 | // Handle -unexported_symbol <symbol> | |||
694 | for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) { | |||
695 | if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) { | |||
696 | error("-unexported_symbol cannot be combined with " | |||
697 | "-exported_symbol[s_list]"); | |||
698 | return false; | |||
699 | } | |||
700 | ctx.setExportMode(MachOLinkingContext::ExportMode::blackList); | |||
701 | ctx.addExportSymbol(symbol->getValue()); | |||
702 | } | |||
703 | ||||
704 | // Handle obosolete -multi_module and -single_module | |||
705 | if (llvm::opt::Arg *mod = | |||
706 | parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) { | |||
707 | if (mod->getOption().getID() == OPT_multi_module) | |||
708 | warn("-multi_module is obsolete and being ignored"); | |||
709 | else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) | |||
710 | warn("-single_module being ignored. It is only for use when producing a " | |||
711 | "dylib"); | |||
712 | } | |||
713 | ||||
714 | // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only | |||
715 | if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) { | |||
716 | error("-objc_gc_compaction is not supported"); | |||
717 | return false; | |||
718 | } | |||
719 | ||||
720 | if (parsedArgs.getLastArg(OPT_objc_gc)) { | |||
721 | error("-objc_gc is not supported"); | |||
722 | return false; | |||
723 | } | |||
724 | ||||
725 | if (parsedArgs.getLastArg(OPT_objc_gc_only)) { | |||
726 | error("-objc_gc_only is not supported"); | |||
727 | return false; | |||
728 | } | |||
729 | ||||
730 | // Handle -pie or -no_pie | |||
731 | if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) { | |||
732 | switch (ctx.outputMachOType()) { | |||
733 | case llvm::MachO::MH_EXECUTE: | |||
734 | switch (ctx.os()) { | |||
735 | case MachOLinkingContext::OS::macOSX: | |||
736 | if ((minOSVersion < 0x000A0500) && | |||
737 | (pie->getOption().getID() == OPT_pie)) { | |||
738 | error("-pie can only be used when targeting Mac OS X 10.5 or later"); | |||
739 | return false; | |||
740 | } | |||
741 | break; | |||
742 | case MachOLinkingContext::OS::iOS: | |||
743 | if ((minOSVersion < 0x00040200) && | |||
744 | (pie->getOption().getID() == OPT_pie)) { | |||
745 | error("-pie can only be used when targeting iOS 4.2 or later"); | |||
746 | return false; | |||
747 | } | |||
748 | break; | |||
749 | case MachOLinkingContext::OS::iOS_simulator: | |||
750 | if (pie->getOption().getID() == OPT_no_pie) { | |||
751 | error("iOS simulator programs must be built PIE"); | |||
752 | return false; | |||
753 | } | |||
754 | break; | |||
755 | case MachOLinkingContext::OS::unknown: | |||
756 | break; | |||
757 | } | |||
758 | ctx.setPIE(pie->getOption().getID() == OPT_pie); | |||
759 | break; | |||
760 | case llvm::MachO::MH_PRELOAD: | |||
761 | break; | |||
762 | case llvm::MachO::MH_DYLIB: | |||
763 | case llvm::MachO::MH_BUNDLE: | |||
764 | warn(pie->getSpelling() + | |||
765 | " being ignored. It is only used when linking main executables"); | |||
766 | break; | |||
767 | default: | |||
768 | error(pie->getSpelling() + | |||
769 | " can only used when linking main executables"); | |||
770 | return false; | |||
771 | } | |||
772 | } | |||
773 | ||||
774 | // Handle -version_load_command or -no_version_load_command | |||
775 | { | |||
776 | bool flagOn = false; | |||
777 | bool flagOff = false; | |||
778 | if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command, | |||
779 | OPT_no_version_load_command)) { | |||
780 | flagOn = arg->getOption().getID() == OPT_version_load_command; | |||
781 | flagOff = arg->getOption().getID() == OPT_no_version_load_command; | |||
782 | } | |||
783 | ||||
784 | // default to adding version load command for dynamic code, | |||
785 | // static code must opt-in | |||
786 | switch (ctx.outputMachOType()) { | |||
787 | case llvm::MachO::MH_OBJECT: | |||
788 | ctx.setGenerateVersionLoadCommand(false); | |||
789 | break; | |||
790 | case llvm::MachO::MH_EXECUTE: | |||
791 | // dynamic executables default to generating a version load command, | |||
792 | // while static exectuables only generate it if required. | |||
793 | if (isStaticExecutable) { | |||
794 | if (flagOn) | |||
795 | ctx.setGenerateVersionLoadCommand(true); | |||
796 | } else { | |||
797 | if (!flagOff) | |||
798 | ctx.setGenerateVersionLoadCommand(true); | |||
799 | } | |||
800 | break; | |||
801 | case llvm::MachO::MH_PRELOAD: | |||
802 | case llvm::MachO::MH_KEXT_BUNDLE: | |||
803 | if (flagOn) | |||
804 | ctx.setGenerateVersionLoadCommand(true); | |||
805 | break; | |||
806 | case llvm::MachO::MH_DYLINKER: | |||
807 | case llvm::MachO::MH_DYLIB: | |||
808 | case llvm::MachO::MH_BUNDLE: | |||
809 | if (!flagOff) | |||
810 | ctx.setGenerateVersionLoadCommand(true); | |||
811 | break; | |||
812 | case llvm::MachO::MH_FVMLIB: | |||
813 | case llvm::MachO::MH_DYLDLINK: | |||
814 | case llvm::MachO::MH_DYLIB_STUB: | |||
815 | case llvm::MachO::MH_DSYM: | |||
816 | // We don't generate load commands for these file types, even if | |||
817 | // forced on. | |||
818 | break; | |||
819 | } | |||
820 | } | |||
821 | ||||
822 | // Handle -function_starts or -no_function_starts | |||
823 | { | |||
824 | bool flagOn = false; | |||
825 | bool flagOff = false; | |||
826 | if (auto *arg = parsedArgs.getLastArg(OPT_function_starts, | |||
827 | OPT_no_function_starts)) { | |||
828 | flagOn = arg->getOption().getID() == OPT_function_starts; | |||
829 | flagOff = arg->getOption().getID() == OPT_no_function_starts; | |||
830 | } | |||
831 | ||||
832 | // default to adding functions start for dynamic code, static code must | |||
833 | // opt-in | |||
834 | switch (ctx.outputMachOType()) { | |||
835 | case llvm::MachO::MH_OBJECT: | |||
836 | ctx.setGenerateFunctionStartsLoadCommand(false); | |||
837 | break; | |||
838 | case llvm::MachO::MH_EXECUTE: | |||
839 | // dynamic executables default to generating a version load command, | |||
840 | // while static exectuables only generate it if required. | |||
841 | if (isStaticExecutable) { | |||
842 | if (flagOn) | |||
843 | ctx.setGenerateFunctionStartsLoadCommand(true); | |||
844 | } else { | |||
845 | if (!flagOff) | |||
846 | ctx.setGenerateFunctionStartsLoadCommand(true); | |||
847 | } | |||
848 | break; | |||
849 | case llvm::MachO::MH_PRELOAD: | |||
850 | case llvm::MachO::MH_KEXT_BUNDLE: | |||
851 | if (flagOn) | |||
852 | ctx.setGenerateFunctionStartsLoadCommand(true); | |||
853 | break; | |||
854 | case llvm::MachO::MH_DYLINKER: | |||
855 | case llvm::MachO::MH_DYLIB: | |||
856 | case llvm::MachO::MH_BUNDLE: | |||
857 | if (!flagOff) | |||
858 | ctx.setGenerateFunctionStartsLoadCommand(true); | |||
859 | break; | |||
860 | case llvm::MachO::MH_FVMLIB: | |||
861 | case llvm::MachO::MH_DYLDLINK: | |||
862 | case llvm::MachO::MH_DYLIB_STUB: | |||
863 | case llvm::MachO::MH_DSYM: | |||
864 | // We don't generate load commands for these file types, even if | |||
865 | // forced on. | |||
866 | break; | |||
867 | } | |||
868 | } | |||
869 | ||||
870 | // Handle -data_in_code_info or -no_data_in_code_info | |||
871 | { | |||
872 | bool flagOn = false; | |||
873 | bool flagOff = false; | |||
874 | if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info, | |||
875 | OPT_no_data_in_code_info)) { | |||
876 | flagOn = arg->getOption().getID() == OPT_data_in_code_info; | |||
877 | flagOff = arg->getOption().getID() == OPT_no_data_in_code_info; | |||
878 | } | |||
879 | ||||
880 | // default to adding data in code for dynamic code, static code must | |||
881 | // opt-in | |||
882 | switch (ctx.outputMachOType()) { | |||
883 | case llvm::MachO::MH_OBJECT: | |||
884 | if (!flagOff) | |||
885 | ctx.setGenerateDataInCodeLoadCommand(true); | |||
886 | break; | |||
887 | case llvm::MachO::MH_EXECUTE: | |||
888 | // dynamic executables default to generating a version load command, | |||
889 | // while static exectuables only generate it if required. | |||
890 | if (isStaticExecutable) { | |||
891 | if (flagOn) | |||
892 | ctx.setGenerateDataInCodeLoadCommand(true); | |||
893 | } else { | |||
894 | if (!flagOff) | |||
895 | ctx.setGenerateDataInCodeLoadCommand(true); | |||
896 | } | |||
897 | break; | |||
898 | case llvm::MachO::MH_PRELOAD: | |||
899 | case llvm::MachO::MH_KEXT_BUNDLE: | |||
900 | if (flagOn) | |||
901 | ctx.setGenerateDataInCodeLoadCommand(true); | |||
902 | break; | |||
903 | case llvm::MachO::MH_DYLINKER: | |||
904 | case llvm::MachO::MH_DYLIB: | |||
905 | case llvm::MachO::MH_BUNDLE: | |||
906 | if (!flagOff) | |||
907 | ctx.setGenerateDataInCodeLoadCommand(true); | |||
908 | break; | |||
909 | case llvm::MachO::MH_FVMLIB: | |||
910 | case llvm::MachO::MH_DYLDLINK: | |||
911 | case llvm::MachO::MH_DYLIB_STUB: | |||
912 | case llvm::MachO::MH_DSYM: | |||
913 | // We don't generate load commands for these file types, even if | |||
914 | // forced on. | |||
915 | break; | |||
916 | } | |||
917 | } | |||
918 | ||||
919 | // Handle sdk_version | |||
920 | if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) { | |||
921 | uint32_t sdkVersion = 0; | |||
922 | if (MachOLinkingContext::parsePackedVersion(arg->getValue(), | |||
923 | sdkVersion)) { | |||
924 | error("malformed sdkVersion value"); | |||
925 | return false; | |||
926 | } | |||
927 | ctx.setSdkVersion(sdkVersion); | |||
928 | } else if (ctx.generateVersionLoadCommand()) { | |||
929 | // If we don't have an sdk version, but were going to emit a load command | |||
930 | // with min_version, then we need to give an warning as we have no sdk | |||
931 | // version to put in that command. | |||
932 | // FIXME: We need to decide whether to make this an error. | |||
933 | warn("-sdk_version is required when emitting min version load command. " | |||
934 | "Setting sdk version to match provided min version"); | |||
935 | ctx.setSdkVersion(ctx.osMinVersion()); | |||
936 | } | |||
937 | ||||
938 | // Handle source_version | |||
939 | if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) { | |||
940 | uint64_t version = 0; | |||
941 | if (MachOLinkingContext::parsePackedVersion(arg->getValue(), | |||
942 | version)) { | |||
943 | error("malformed source_version value"); | |||
944 | return false; | |||
945 | } | |||
946 | ctx.setSourceVersion(version); | |||
947 | } | |||
948 | ||||
949 | // Handle stack_size | |||
950 | if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) { | |||
951 | uint64_t stackSizeVal; | |||
952 | if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) { | |||
953 | error("stack_size expects a hex number"); | |||
954 | return false; | |||
955 | } | |||
956 | if ((stackSizeVal % ctx.pageSize()) != 0) { | |||
957 | error("stack_size must be a multiple of page size (0x" + | |||
958 | llvm::utohexstr(ctx.pageSize()) + ")"); | |||
959 | return false; | |||
960 | } | |||
961 | ||||
962 | ctx.setStackSize(stackSizeVal); | |||
963 | } | |||
964 | ||||
965 | // Handle debug info handling options: -S | |||
966 | if (parsedArgs.hasArg(OPT_S)) | |||
967 | ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap); | |||
968 | ||||
969 | // Handle -order_file <file> | |||
970 | for (auto orderFile : parsedArgs.filtered(OPT_order_file)) { | |||
971 | if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) { | |||
972 | error(ec.message() + ", processing '-order_file " + orderFile->getValue() | |||
973 | + "'"); | |||
974 | return false; | |||
975 | } | |||
976 | } | |||
977 | ||||
978 | // Handle -flat_namespace. | |||
979 | if (llvm::opt::Arg *ns = | |||
980 | parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) { | |||
981 | if (ns->getOption().getID() == OPT_flat_namespace) | |||
982 | ctx.setUseFlatNamespace(true); | |||
983 | } | |||
984 | ||||
985 | // Handle -undefined | |||
986 | if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) { | |||
987 | MachOLinkingContext::UndefinedMode UndefMode; | |||
988 | if (StringRef(undef->getValue()).equals("error")) | |||
989 | UndefMode = MachOLinkingContext::UndefinedMode::error; | |||
990 | else if (StringRef(undef->getValue()).equals("warning")) | |||
991 | UndefMode = MachOLinkingContext::UndefinedMode::warning; | |||
992 | else if (StringRef(undef->getValue()).equals("suppress")) | |||
993 | UndefMode = MachOLinkingContext::UndefinedMode::suppress; | |||
994 | else if (StringRef(undef->getValue()).equals("dynamic_lookup")) | |||
995 | UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup; | |||
996 | else { | |||
997 | error("invalid option to -undefined [ warning | error | suppress | " | |||
998 | "dynamic_lookup ]"); | |||
999 | return false; | |||
1000 | } | |||
1001 | ||||
1002 | if (ctx.useFlatNamespace()) { | |||
1003 | // If we're using -flat_namespace then 'warning', 'suppress' and | |||
1004 | // 'dynamic_lookup' are all equivalent, so map them to 'suppress'. | |||
1005 | if (UndefMode != MachOLinkingContext::UndefinedMode::error) | |||
1006 | UndefMode = MachOLinkingContext::UndefinedMode::suppress; | |||
1007 | } else { | |||
1008 | // If we're using -twolevel_namespace then 'warning' and 'suppress' are | |||
1009 | // illegal. Emit a diagnostic if they've been (mis)used. | |||
1010 | if (UndefMode == MachOLinkingContext::UndefinedMode::warning || | |||
1011 | UndefMode == MachOLinkingContext::UndefinedMode::suppress) { | |||
1012 | error("can't use -undefined warning or suppress with " | |||
1013 | "-twolevel_namespace"); | |||
1014 | return false; | |||
1015 | } | |||
1016 | } | |||
1017 | ||||
1018 | ctx.setUndefinedMode(UndefMode); | |||
1019 | } | |||
1020 | ||||
1021 | // Handle -no_objc_category_merging. | |||
1022 | if (parsedArgs.getLastArg(OPT_no_objc_category_merging)) | |||
1023 | ctx.setMergeObjCCategories(false); | |||
1024 | ||||
1025 | // Handle -rpath <path> | |||
1026 | if (parsedArgs.hasArg(OPT_rpath)) { | |||
1027 | switch (ctx.outputMachOType()) { | |||
1028 | case llvm::MachO::MH_EXECUTE: | |||
1029 | case llvm::MachO::MH_DYLIB: | |||
1030 | case llvm::MachO::MH_BUNDLE: | |||
1031 | if (!ctx.minOS("10.5", "2.0")) { | |||
1032 | if (ctx.os() == MachOLinkingContext::OS::macOSX) | |||
1033 | error("-rpath can only be used when targeting OS X 10.5 or later"); | |||
1034 | else | |||
1035 | error("-rpath can only be used when targeting iOS 2.0 or later"); | |||
1036 | return false; | |||
1037 | } | |||
1038 | break; | |||
1039 | default: | |||
1040 | error("-rpath can only be used when creating a dynamic final linked " | |||
1041 | "image"); | |||
1042 | return false; | |||
1043 | } | |||
1044 | ||||
1045 | for (auto rPath : parsedArgs.filtered(OPT_rpath)) { | |||
1046 | ctx.addRpath(rPath->getValue()); | |||
1047 | } | |||
1048 | } | |||
1049 | ||||
1050 | // Parse the LLVM options before we process files in case the file handling | |||
1051 | // makes use of things like LLVM_DEBUG(). | |||
1052 | parseLLVMOptions(ctx); | |||
1053 | ||||
1054 | // Handle input files and sectcreate. | |||
1055 | for (auto &arg : parsedArgs) { | |||
1056 | bool upward; | |||
1057 | llvm::Optional<StringRef> resolvedPath; | |||
1058 | switch (arg->getOption().getID()) { | |||
1059 | default: | |||
1060 | continue; | |||
1061 | case OPT_INPUT: | |||
1062 | addFile(arg->getValue(), ctx, globalWholeArchive, false); | |||
1063 | break; | |||
1064 | case OPT_upward_library: | |||
1065 | addFile(arg->getValue(), ctx, false, true); | |||
1066 | break; | |||
1067 | case OPT_force_load: | |||
1068 | addFile(arg->getValue(), ctx, true, false); | |||
1069 | break; | |||
1070 | case OPT_l: | |||
1071 | case OPT_upward_l: | |||
1072 | upward = (arg->getOption().getID() == OPT_upward_l); | |||
1073 | resolvedPath = ctx.searchLibrary(arg->getValue()); | |||
1074 | if (!resolvedPath) { | |||
1075 | error("Unable to find library for " + arg->getSpelling() + | |||
1076 | arg->getValue()); | |||
1077 | return false; | |||
1078 | } else if (ctx.testingFileUsage()) { | |||
1079 | message(Twine("Found ") + (upward ? "upward " : " ") + "library " + | |||
1080 | canonicalizePath(resolvedPath.getValue())); | |||
1081 | } | |||
1082 | addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward); | |||
1083 | break; | |||
1084 | case OPT_framework: | |||
1085 | case OPT_upward_framework: | |||
1086 | upward = (arg->getOption().getID() == OPT_upward_framework); | |||
1087 | resolvedPath = ctx.findPathForFramework(arg->getValue()); | |||
1088 | if (!resolvedPath) { | |||
1089 | error("Unable to find framework for " + arg->getSpelling() + " " + | |||
1090 | arg->getValue()); | |||
1091 | return false; | |||
1092 | } else if (ctx.testingFileUsage()) { | |||
1093 | message(Twine("Found ") + (upward ? "upward " : " ") + "framework " + | |||
1094 | canonicalizePath(resolvedPath.getValue())); | |||
1095 | } | |||
1096 | addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward); | |||
1097 | break; | |||
1098 | case OPT_filelist: | |||
1099 | if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) { | |||
1100 | handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) { | |||
1101 | error(EI.message() + ", processing '-filelist " + arg->getValue()); | |||
1102 | }); | |||
1103 | return false; | |||
1104 | } | |||
1105 | break; | |||
1106 | case OPT_sectcreate: { | |||
1107 | const char* seg = arg->getValue(0); | |||
1108 | const char* sect = arg->getValue(1); | |||
1109 | const char* fileName = arg->getValue(2); | |||
1110 | ||||
1111 | ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr = | |||
1112 | MemoryBuffer::getFile(fileName); | |||
1113 | ||||
1114 | if (!contentOrErr) { | |||
1115 | error("can't open -sectcreate file " + Twine(fileName)); | |||
1116 | return false; | |||
1117 | } | |||
1118 | ||||
1119 | ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr)); | |||
1120 | } | |||
1121 | break; | |||
1122 | } | |||
1123 | } | |||
1124 | ||||
1125 | if (ctx.getNodes().empty()) { | |||
1126 | error("No input files"); | |||
1127 | return false; | |||
1128 | } | |||
1129 | ||||
1130 | // Validate the combination of options used. | |||
1131 | return ctx.validate(); | |||
1132 | } | |||
1133 | ||||
1134 | static void createFiles(MachOLinkingContext &ctx, bool Implicit) { | |||
1135 | std::vector<std::unique_ptr<File>> Files; | |||
1136 | if (Implicit) | |||
1137 | ctx.createImplicitFiles(Files); | |||
1138 | else | |||
1139 | ctx.createInternalFiles(Files); | |||
1140 | for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) { | |||
1141 | auto &members = ctx.getNodes(); | |||
1142 | members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i))); | |||
1143 | } | |||
1144 | } | |||
1145 | ||||
1146 | /// This is where the link is actually performed. | |||
1147 | bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly, | |||
1148 | raw_ostream &Error) { | |||
1149 | errorHandler().LogName = args::getFilenameWithoutExe(args[0]); | |||
1150 | errorHandler().ErrorLimitExceededMsg = | |||
1151 | "too many errors emitted, stopping now (use " | |||
1152 | "'-error-limit 0' to see all errors)"; | |||
1153 | errorHandler().ErrorOS = &Error; | |||
1154 | errorHandler().ExitEarly = CanExitEarly; | |||
1155 | errorHandler().ColorDiagnostics = Error.has_colors(); | |||
1156 | ||||
1157 | MachOLinkingContext ctx; | |||
1158 | if (!parse(args, ctx)) | |||
1159 | return false; | |||
1160 | if (ctx.doNothing()) | |||
1161 | return true; | |||
1162 | if (ctx.getNodes().empty()) | |||
1163 | return false; | |||
1164 | ||||
1165 | for (std::unique_ptr<Node> &ie : ctx.getNodes()) | |||
1166 | if (FileNode *node = dyn_cast<FileNode>(ie.get())) | |||
1167 | node->getFile()->parse(); | |||
1168 | ||||
1169 | createFiles(ctx, false /* Implicit */); | |||
1170 | ||||
1171 | // Give target a chance to add files | |||
1172 | createFiles(ctx, true /* Implicit */); | |||
1173 | ||||
1174 | // Give target a chance to postprocess input files. | |||
1175 | // Mach-O uses this chance to move all object files before library files. | |||
1176 | ctx.finalizeInputFiles(); | |||
1177 | ||||
1178 | // Do core linking. | |||
1179 | ScopedTask resolveTask(getDefaultDomain(), "Resolve"); | |||
1180 | Resolver resolver(ctx); | |||
1181 | if (!resolver.resolve()) | |||
1182 | return false; | |||
1183 | SimpleFile *merged = nullptr; | |||
1184 | { | |||
1185 | std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile(); | |||
1186 | merged = mergedFile.get(); | |||
1187 | auto &members = ctx.getNodes(); | |||
1188 | members.insert(members.begin(), | |||
1189 | llvm::make_unique<FileNode>(std::move(mergedFile))); | |||
1190 | } | |||
1191 | resolveTask.end(); | |||
1192 | ||||
1193 | // Run passes on linked atoms. | |||
1194 | ScopedTask passTask(getDefaultDomain(), "Passes"); | |||
1195 | PassManager pm; | |||
1196 | ctx.addPasses(pm); | |||
1197 | if (auto ec = pm.runOnFile(*merged)) { | |||
1198 | // FIXME: This should be passed to logAllUnhandledErrors but it needs | |||
1199 | // to be passed a Twine instead of a string. | |||
1200 | *errorHandler().ErrorOS << "Failed to run passes on file '" | |||
1201 | << ctx.outputPath() << "': "; | |||
1202 | logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS, | |||
1203 | std::string()); | |||
1204 | return false; | |||
1205 | } | |||
1206 | ||||
1207 | passTask.end(); | |||
1208 | ||||
1209 | // Give linked atoms to Writer to generate output file. | |||
1210 | ScopedTask writeTask(getDefaultDomain(), "Write"); | |||
1211 | if (auto ec = ctx.writeFile(*merged)) { | |||
1212 | // FIXME: This should be passed to logAllUnhandledErrors but it needs | |||
1213 | // to be passed a Twine instead of a string. | |||
1214 | *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath() | |||
1215 | << "': "; | |||
1216 | logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS, | |||
1217 | std::string()); | |||
1218 | return false; | |||
1219 | } | |||
1220 | ||||
1221 | // Call exit() if we can to avoid calling destructors. | |||
1222 | if (CanExitEarly) | |||
1223 | exitLld(errorCount() ? 1 : 0); | |||
1224 | ||||
1225 | ||||
1226 | return true; | |||
1227 | } | |||
1228 | ||||
1229 | } // end namespace mach_o | |||
1230 | } // end namespace lld |
1 | //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// |
2 | // |
3 | // The LLVM Compiler Infrastructure |
4 | // |
5 | // This file is distributed under the University of Illinois Open Source |
6 | // License. See LICENSE.TXT for details. |
7 | // |
8 | //===----------------------------------------------------------------------===// |
9 | // |
10 | // This file contains some functions that are useful for math stuff. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_SUPPORT_MATHEXTRAS_H |
15 | #define LLVM_SUPPORT_MATHEXTRAS_H |
16 | |
17 | #include "llvm/Support/Compiler.h" |
18 | #include "llvm/Support/SwapByteOrder.h" |
19 | #include <algorithm> |
20 | #include <cassert> |
21 | #include <climits> |
22 | #include <cstring> |
23 | #include <limits> |
24 | #include <type_traits> |
25 | |
26 | #ifdef __ANDROID_NDK__ |
27 | #include <android/api-level.h> |
28 | #endif |
29 | |
30 | #ifdef _MSC_VER |
31 | // Declare these intrinsics manually rather including intrin.h. It's very |
32 | // expensive, and MathExtras.h is popular. |
33 | // #include <intrin.h> |
34 | extern "C" { |
35 | unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask); |
36 | unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask); |
37 | unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask); |
38 | unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask); |
39 | } |
40 | #endif |
41 | |
42 | namespace llvm { |
43 | /// The behavior an operation has on an input of 0. |
44 | enum ZeroBehavior { |
45 | /// The returned value is undefined. |
46 | ZB_Undefined, |
47 | /// The returned value is numeric_limits<T>::max() |
48 | ZB_Max, |
49 | /// The returned value is numeric_limits<T>::digits |
50 | ZB_Width |
51 | }; |
52 | |
53 | namespace detail { |
54 | template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter { |
55 | static std::size_t count(T Val, ZeroBehavior) { |
56 | if (!Val) |
57 | return std::numeric_limits<T>::digits; |
58 | if (Val & 0x1) |
59 | return 0; |
60 | |
61 | // Bisection method. |
62 | std::size_t ZeroBits = 0; |
63 | T Shift = std::numeric_limits<T>::digits >> 1; |
64 | T Mask = std::numeric_limits<T>::max() >> Shift; |
65 | while (Shift) { |
66 | if ((Val & Mask) == 0) { |
67 | Val >>= Shift; |
68 | ZeroBits |= Shift; |
69 | } |
70 | Shift >>= 1; |
71 | Mask >>= Shift; |
72 | } |
73 | return ZeroBits; |
74 | } |
75 | }; |
76 | |
77 | #if __GNUC__4 >= 4 || defined(_MSC_VER) |
78 | template <typename T> struct TrailingZerosCounter<T, 4> { |
79 | static std::size_t count(T Val, ZeroBehavior ZB) { |
80 | if (ZB != ZB_Undefined && Val == 0) |
81 | return 32; |
82 | |
83 | #if __has_builtin(__builtin_ctz)1 || LLVM_GNUC_PREREQ(4, 0, 0)((4 << 20) + (2 << 10) + 1 >= ((4) << 20 ) + ((0) << 10) + (0)) |
84 | return __builtin_ctz(Val); |
85 | #elif defined(_MSC_VER) |
86 | unsigned long Index; |
87 | _BitScanForward(&Index, Val); |
88 | return Index; |
89 | #endif |
90 | } |
91 | }; |
92 | |
93 | #if !defined(_MSC_VER) || defined(_M_X64) |
94 | template <typename T> struct TrailingZerosCounter<T, 8> { |
95 | static std::size_t count(T Val, ZeroBehavior ZB) { |
96 | if (ZB != ZB_Undefined && Val == 0) |
97 | return 64; |
98 | |
99 | #if __has_builtin(__builtin_ctzll)1 || LLVM_GNUC_PREREQ(4, 0, 0)((4 << 20) + (2 << 10) + 1 >= ((4) << 20 ) + ((0) << 10) + (0)) |
100 | return __builtin_ctzll(Val); |
101 | #elif defined(_MSC_VER) |
102 | unsigned long Index; |
103 | _BitScanForward64(&Index, Val); |
104 | return Index; |
105 | #endif |
106 | } |
107 | }; |
108 | #endif |
109 | #endif |
110 | } // namespace detail |
111 | |
112 | /// Count number of 0's from the least significant bit to the most |
113 | /// stopping at the first 1. |
114 | /// |
115 | /// Only unsigned integral types are allowed. |
116 | /// |
117 | /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are |
118 | /// valid arguments. |
119 | template <typename T> |
120 | std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) { |
121 | static_assert(std::numeric_limits<T>::is_integer && |
122 | !std::numeric_limits<T>::is_signed, |
123 | "Only unsigned integral types are allowed."); |
124 | return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB); |
125 | } |
126 | |
127 | namespace detail { |
128 | template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter { |
129 | static std::size_t count(T Val, ZeroBehavior) { |
130 | if (!Val) |
131 | return std::numeric_limits<T>::digits; |
132 | |
133 | // Bisection method. |
134 | std::size_t ZeroBits = 0; |
135 | for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) { |
136 | T Tmp = Val >> Shift; |
137 | if (Tmp) |
138 | Val = Tmp; |
139 | else |
140 | ZeroBits |= Shift; |
141 | } |
142 | return ZeroBits; |
143 | } |
144 | }; |
145 | |
146 | #if __GNUC__4 >= 4 || defined(_MSC_VER) |
147 | template <typename T> struct LeadingZerosCounter<T, 4> { |
148 | static std::size_t count(T Val, ZeroBehavior ZB) { |
149 | if (ZB != ZB_Undefined && Val == 0) |
150 | return 32; |
151 | |
152 | #if __has_builtin(__builtin_clz)1 || LLVM_GNUC_PREREQ(4, 0, 0)((4 << 20) + (2 << 10) + 1 >= ((4) << 20 ) + ((0) << 10) + (0)) |
153 | return __builtin_clz(Val); |
154 | #elif defined(_MSC_VER) |
155 | unsigned long Index; |
156 | _BitScanReverse(&Index, Val); |
157 | return Index ^ 31; |
158 | #endif |
159 | } |
160 | }; |
161 | |
162 | #if !defined(_MSC_VER) || defined(_M_X64) |
163 | template <typename T> struct LeadingZerosCounter<T, 8> { |
164 | static std::size_t count(T Val, ZeroBehavior ZB) { |
165 | if (ZB != ZB_Undefined && Val == 0) |
166 | return 64; |
167 | |
168 | #if __has_builtin(__builtin_clzll)1 || LLVM_GNUC_PREREQ(4, 0, 0)((4 << 20) + (2 << 10) + 1 >= ((4) << 20 ) + ((0) << 10) + (0)) |
169 | return __builtin_clzll(Val); |
170 | #elif defined(_MSC_VER) |
171 | unsigned long Index; |
172 | _BitScanReverse64(&Index, Val); |
173 | return Index ^ 63; |
174 | #endif |
175 | } |
176 | }; |
177 | #endif |
178 | #endif |
179 | } // namespace detail |
180 | |
181 | /// Count number of 0's from the most significant bit to the least |
182 | /// stopping at the first 1. |
183 | /// |
184 | /// Only unsigned integral types are allowed. |
185 | /// |
186 | /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are |
187 | /// valid arguments. |
188 | template <typename T> |
189 | std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) { |
190 | static_assert(std::numeric_limits<T>::is_integer && |
191 | !std::numeric_limits<T>::is_signed, |
192 | "Only unsigned integral types are allowed."); |
193 | return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB); |
194 | } |
195 | |
196 | /// Get the index of the first set bit starting from the least |
197 | /// significant bit. |
198 | /// |
199 | /// Only unsigned integral types are allowed. |
200 | /// |
201 | /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are |
202 | /// valid arguments. |
203 | template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) { |
204 | if (ZB == ZB_Max && Val == 0) |
205 | return std::numeric_limits<T>::max(); |
206 | |
207 | return countTrailingZeros(Val, ZB_Undefined); |
208 | } |
209 | |
210 | /// Create a bitmask with the N right-most bits set to 1, and all other |
211 | /// bits set to 0. Only unsigned types are allowed. |
212 | template <typename T> T maskTrailingOnes(unsigned N) { |
213 | static_assert(std::is_unsigned<T>::value, "Invalid type!"); |
214 | const unsigned Bits = CHAR_BIT8 * sizeof(T); |
215 | assert(N <= Bits && "Invalid bit index")((N <= Bits && "Invalid bit index") ? static_cast< void> (0) : __assert_fail ("N <= Bits && \"Invalid bit index\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 215, __PRETTY_FUNCTION__)); |
216 | return N == 0 ? 0 : (T(-1) >> (Bits - N)); |
217 | } |
218 | |
219 | /// Create a bitmask with the N left-most bits set to 1, and all other |
220 | /// bits set to 0. Only unsigned types are allowed. |
221 | template <typename T> T maskLeadingOnes(unsigned N) { |
222 | return ~maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N); |
223 | } |
224 | |
225 | /// Create a bitmask with the N right-most bits set to 0, and all other |
226 | /// bits set to 1. Only unsigned types are allowed. |
227 | template <typename T> T maskTrailingZeros(unsigned N) { |
228 | return maskLeadingOnes<T>(CHAR_BIT8 * sizeof(T) - N); |
229 | } |
230 | |
231 | /// Create a bitmask with the N left-most bits set to 0, and all other |
232 | /// bits set to 1. Only unsigned types are allowed. |
233 | template <typename T> T maskLeadingZeros(unsigned N) { |
234 | return maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N); |
235 | } |
236 | |
237 | /// Get the index of the last set bit starting from the least |
238 | /// significant bit. |
239 | /// |
240 | /// Only unsigned integral types are allowed. |
241 | /// |
242 | /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are |
243 | /// valid arguments. |
244 | template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) { |
245 | if (ZB == ZB_Max && Val == 0) |
246 | return std::numeric_limits<T>::max(); |
247 | |
248 | // Use ^ instead of - because both gcc and llvm can remove the associated ^ |
249 | // in the __builtin_clz intrinsic on x86. |
250 | return countLeadingZeros(Val, ZB_Undefined) ^ |
251 | (std::numeric_limits<T>::digits - 1); |
252 | } |
253 | |
254 | /// Macro compressed bit reversal table for 256 bits. |
255 | /// |
256 | /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable |
257 | static const unsigned char BitReverseTable256[256] = { |
258 | #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64 |
259 | #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16) |
260 | #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4) |
261 | R6(0), R6(2), R6(1), R6(3) |
262 | #undef R2 |
263 | #undef R4 |
264 | #undef R6 |
265 | }; |
266 | |
267 | /// Reverse the bits in \p Val. |
268 | template <typename T> |
269 | T reverseBits(T Val) { |
270 | unsigned char in[sizeof(Val)]; |
271 | unsigned char out[sizeof(Val)]; |
272 | std::memcpy(in, &Val, sizeof(Val)); |
273 | for (unsigned i = 0; i < sizeof(Val); ++i) |
274 | out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]]; |
275 | std::memcpy(&Val, out, sizeof(Val)); |
276 | return Val; |
277 | } |
278 | |
279 | // NOTE: The following support functions use the _32/_64 extensions instead of |
280 | // type overloading so that signed and unsigned integers can be used without |
281 | // ambiguity. |
282 | |
283 | /// Return the high 32 bits of a 64 bit value. |
284 | constexpr inline uint32_t Hi_32(uint64_t Value) { |
285 | return static_cast<uint32_t>(Value >> 32); |
286 | } |
287 | |
288 | /// Return the low 32 bits of a 64 bit value. |
289 | constexpr inline uint32_t Lo_32(uint64_t Value) { |
290 | return static_cast<uint32_t>(Value); |
291 | } |
292 | |
293 | /// Make a 64-bit integer from a high / low pair of 32-bit integers. |
294 | constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) { |
295 | return ((uint64_t)High << 32) | (uint64_t)Low; |
296 | } |
297 | |
298 | /// Checks if an integer fits into the given bit width. |
299 | template <unsigned N> constexpr inline bool isInt(int64_t x) { |
300 | return N >= 64 || (-(INT64_C(1)1L<<(N-1)) <= x && x < (INT64_C(1)1L<<(N-1))); |
301 | } |
302 | // Template specializations to get better code for common cases. |
303 | template <> constexpr inline bool isInt<8>(int64_t x) { |
304 | return static_cast<int8_t>(x) == x; |
305 | } |
306 | template <> constexpr inline bool isInt<16>(int64_t x) { |
307 | return static_cast<int16_t>(x) == x; |
308 | } |
309 | template <> constexpr inline bool isInt<32>(int64_t x) { |
310 | return static_cast<int32_t>(x) == x; |
311 | } |
312 | |
313 | /// Checks if a signed integer is an N bit number shifted left by S. |
314 | template <unsigned N, unsigned S> |
315 | constexpr inline bool isShiftedInt(int64_t x) { |
316 | static_assert( |
317 | N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number."); |
318 | static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide."); |
319 | return isInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0); |
320 | } |
321 | |
322 | /// Checks if an unsigned integer fits into the given bit width. |
323 | /// |
324 | /// This is written as two functions rather than as simply |
325 | /// |
326 | /// return N >= 64 || X < (UINT64_C(1) << N); |
327 | /// |
328 | /// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting |
329 | /// left too many places. |
330 | template <unsigned N> |
331 | constexpr inline typename std::enable_if<(N < 64), bool>::type |
332 | isUInt(uint64_t X) { |
333 | static_assert(N > 0, "isUInt<0> doesn't make sense"); |
334 | return X < (UINT64_C(1)1UL << (N)); |
335 | } |
336 | template <unsigned N> |
337 | constexpr inline typename std::enable_if<N >= 64, bool>::type |
338 | isUInt(uint64_t X) { |
339 | return true; |
340 | } |
341 | |
342 | // Template specializations to get better code for common cases. |
343 | template <> constexpr inline bool isUInt<8>(uint64_t x) { |
344 | return static_cast<uint8_t>(x) == x; |
345 | } |
346 | template <> constexpr inline bool isUInt<16>(uint64_t x) { |
347 | return static_cast<uint16_t>(x) == x; |
348 | } |
349 | template <> constexpr inline bool isUInt<32>(uint64_t x) { |
350 | return static_cast<uint32_t>(x) == x; |
351 | } |
352 | |
353 | /// Checks if a unsigned integer is an N bit number shifted left by S. |
354 | template <unsigned N, unsigned S> |
355 | constexpr inline bool isShiftedUInt(uint64_t x) { |
356 | static_assert( |
357 | N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)"); |
358 | static_assert(N + S <= 64, |
359 | "isShiftedUInt<N, S> with N + S > 64 is too wide."); |
360 | // Per the two static_asserts above, S must be strictly less than 64. So |
361 | // 1 << S is not undefined behavior. |
362 | return isUInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0); |
363 | } |
364 | |
365 | /// Gets the maximum value for a N-bit unsigned integer. |
366 | inline uint64_t maxUIntN(uint64_t N) { |
367 | assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range" ) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 367, __PRETTY_FUNCTION__)); |
368 | |
369 | // uint64_t(1) << 64 is undefined behavior, so we can't do |
370 | // (uint64_t(1) << N) - 1 |
371 | // without checking first that N != 64. But this works and doesn't have a |
372 | // branch. |
373 | return UINT64_MAX(18446744073709551615UL) >> (64 - N); |
374 | } |
375 | |
376 | /// Gets the minimum value for a N-bit signed integer. |
377 | inline int64_t minIntN(int64_t N) { |
378 | assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range" ) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 378, __PRETTY_FUNCTION__)); |
379 | |
380 | return -(UINT64_C(1)1UL<<(N-1)); |
381 | } |
382 | |
383 | /// Gets the maximum value for a N-bit signed integer. |
384 | inline int64_t maxIntN(int64_t N) { |
385 | assert(N > 0 && N <= 64 && "integer width out of range")((N > 0 && N <= 64 && "integer width out of range" ) ? static_cast<void> (0) : __assert_fail ("N > 0 && N <= 64 && \"integer width out of range\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 385, __PRETTY_FUNCTION__)); |
386 | |
387 | // This relies on two's complement wraparound when N == 64, so we convert to |
388 | // int64_t only at the very end to avoid UB. |
389 | return (UINT64_C(1)1UL << (N - 1)) - 1; |
390 | } |
391 | |
392 | /// Checks if an unsigned integer fits into the given (dynamic) bit width. |
393 | inline bool isUIntN(unsigned N, uint64_t x) { |
394 | return N >= 64 || x <= maxUIntN(N); |
395 | } |
396 | |
397 | /// Checks if an signed integer fits into the given (dynamic) bit width. |
398 | inline bool isIntN(unsigned N, int64_t x) { |
399 | return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N)); |
400 | } |
401 | |
402 | /// Return true if the argument is a non-empty sequence of ones starting at the |
403 | /// least significant bit with the remainder zero (32 bit version). |
404 | /// Ex. isMask_32(0x0000FFFFU) == true. |
405 | constexpr inline bool isMask_32(uint32_t Value) { |
406 | return Value && ((Value + 1) & Value) == 0; |
407 | } |
408 | |
409 | /// Return true if the argument is a non-empty sequence of ones starting at the |
410 | /// least significant bit with the remainder zero (64 bit version). |
411 | constexpr inline bool isMask_64(uint64_t Value) { |
412 | return Value && ((Value + 1) & Value) == 0; |
413 | } |
414 | |
415 | /// Return true if the argument contains a non-empty sequence of ones with the |
416 | /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true. |
417 | constexpr inline bool isShiftedMask_32(uint32_t Value) { |
418 | return Value && isMask_32((Value - 1) | Value); |
419 | } |
420 | |
421 | /// Return true if the argument contains a non-empty sequence of ones with the |
422 | /// remainder zero (64 bit version.) |
423 | constexpr inline bool isShiftedMask_64(uint64_t Value) { |
424 | return Value && isMask_64((Value - 1) | Value); |
425 | } |
426 | |
427 | /// Return true if the argument is a power of two > 0. |
428 | /// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) |
429 | constexpr inline bool isPowerOf2_32(uint32_t Value) { |
430 | return Value && !(Value & (Value - 1)); |
431 | } |
432 | |
433 | /// Return true if the argument is a power of two > 0 (64 bit edition.) |
434 | constexpr inline bool isPowerOf2_64(uint64_t Value) { |
435 | return Value && !(Value & (Value - 1)); |
436 | } |
437 | |
438 | /// Return a byte-swapped representation of the 16-bit argument. |
439 | inline uint16_t ByteSwap_16(uint16_t Value) { |
440 | return sys::SwapByteOrder_16(Value); |
441 | } |
442 | |
443 | /// Return a byte-swapped representation of the 32-bit argument. |
444 | inline uint32_t ByteSwap_32(uint32_t Value) { |
445 | return sys::SwapByteOrder_32(Value); |
446 | } |
447 | |
448 | /// Return a byte-swapped representation of the 64-bit argument. |
449 | inline uint64_t ByteSwap_64(uint64_t Value) { |
450 | return sys::SwapByteOrder_64(Value); |
451 | } |
452 | |
453 | /// Count the number of ones from the most significant bit to the first |
454 | /// zero bit. |
455 | /// |
456 | /// Ex. countLeadingOnes(0xFF0FFF00) == 8. |
457 | /// Only unsigned integral types are allowed. |
458 | /// |
459 | /// \param ZB the behavior on an input of all ones. Only ZB_Width and |
460 | /// ZB_Undefined are valid arguments. |
461 | template <typename T> |
462 | std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) { |
463 | static_assert(std::numeric_limits<T>::is_integer && |
464 | !std::numeric_limits<T>::is_signed, |
465 | "Only unsigned integral types are allowed."); |
466 | return countLeadingZeros<T>(~Value, ZB); |
467 | } |
468 | |
469 | /// Count the number of ones from the least significant bit to the first |
470 | /// zero bit. |
471 | /// |
472 | /// Ex. countTrailingOnes(0x00FF00FF) == 8. |
473 | /// Only unsigned integral types are allowed. |
474 | /// |
475 | /// \param ZB the behavior on an input of all ones. Only ZB_Width and |
476 | /// ZB_Undefined are valid arguments. |
477 | template <typename T> |
478 | std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) { |
479 | static_assert(std::numeric_limits<T>::is_integer && |
480 | !std::numeric_limits<T>::is_signed, |
481 | "Only unsigned integral types are allowed."); |
482 | return countTrailingZeros<T>(~Value, ZB); |
483 | } |
484 | |
485 | namespace detail { |
486 | template <typename T, std::size_t SizeOfT> struct PopulationCounter { |
487 | static unsigned count(T Value) { |
488 | // Generic version, forward to 32 bits. |
489 | static_assert(SizeOfT <= 4, "Not implemented!"); |
490 | #if __GNUC__4 >= 4 |
491 | return __builtin_popcount(Value); |
492 | #else |
493 | uint32_t v = Value; |
494 | v = v - ((v >> 1) & 0x55555555); |
495 | v = (v & 0x33333333) + ((v >> 2) & 0x33333333); |
496 | return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; |
497 | #endif |
498 | } |
499 | }; |
500 | |
501 | template <typename T> struct PopulationCounter<T, 8> { |
502 | static unsigned count(T Value) { |
503 | #if __GNUC__4 >= 4 |
504 | return __builtin_popcountll(Value); |
505 | #else |
506 | uint64_t v = Value; |
507 | v = v - ((v >> 1) & 0x5555555555555555ULL); |
508 | v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL); |
509 | v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL; |
510 | return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56); |
511 | #endif |
512 | } |
513 | }; |
514 | } // namespace detail |
515 | |
516 | /// Count the number of set bits in a value. |
517 | /// Ex. countPopulation(0xF000F000) = 8 |
518 | /// Returns 0 if the word is zero. |
519 | template <typename T> |
520 | inline unsigned countPopulation(T Value) { |
521 | static_assert(std::numeric_limits<T>::is_integer && |
522 | !std::numeric_limits<T>::is_signed, |
523 | "Only unsigned integral types are allowed."); |
524 | return detail::PopulationCounter<T, sizeof(T)>::count(Value); |
525 | } |
526 | |
527 | /// Return the log base 2 of the specified value. |
528 | inline double Log2(double Value) { |
529 | #if defined(__ANDROID_API__) && __ANDROID_API__ < 18 |
530 | return __builtin_log(Value) / __builtin_log(2.0); |
531 | #else |
532 | return log2(Value); |
533 | #endif |
534 | } |
535 | |
536 | /// Return the floor log base 2 of the specified value, -1 if the value is zero. |
537 | /// (32 bit edition.) |
538 | /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 |
539 | inline unsigned Log2_32(uint32_t Value) { |
540 | return 31 - countLeadingZeros(Value); |
541 | } |
542 | |
543 | /// Return the floor log base 2 of the specified value, -1 if the value is zero. |
544 | /// (64 bit edition.) |
545 | inline unsigned Log2_64(uint64_t Value) { |
546 | return 63 - countLeadingZeros(Value); |
547 | } |
548 | |
549 | /// Return the ceil log base 2 of the specified value, 32 if the value is zero. |
550 | /// (32 bit edition). |
551 | /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 |
552 | inline unsigned Log2_32_Ceil(uint32_t Value) { |
553 | return 32 - countLeadingZeros(Value - 1); |
554 | } |
555 | |
556 | /// Return the ceil log base 2 of the specified value, 64 if the value is zero. |
557 | /// (64 bit edition.) |
558 | inline unsigned Log2_64_Ceil(uint64_t Value) { |
559 | return 64 - countLeadingZeros(Value - 1); |
560 | } |
561 | |
562 | /// Return the greatest common divisor of the values using Euclid's algorithm. |
563 | inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) { |
564 | while (B) { |
565 | uint64_t T = B; |
566 | B = A % B; |
567 | A = T; |
568 | } |
569 | return A; |
570 | } |
571 | |
572 | /// This function takes a 64-bit integer and returns the bit equivalent double. |
573 | inline double BitsToDouble(uint64_t Bits) { |
574 | double D; |
575 | static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); |
576 | memcpy(&D, &Bits, sizeof(Bits)); |
577 | return D; |
578 | } |
579 | |
580 | /// This function takes a 32-bit integer and returns the bit equivalent float. |
581 | inline float BitsToFloat(uint32_t Bits) { |
582 | float F; |
583 | static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes"); |
584 | memcpy(&F, &Bits, sizeof(Bits)); |
585 | return F; |
586 | } |
587 | |
588 | /// This function takes a double and returns the bit equivalent 64-bit integer. |
589 | /// Note that copying doubles around changes the bits of NaNs on some hosts, |
590 | /// notably x86, so this routine cannot be used if these bits are needed. |
591 | inline uint64_t DoubleToBits(double Double) { |
592 | uint64_t Bits; |
593 | static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes"); |
594 | memcpy(&Bits, &Double, sizeof(Double)); |
595 | return Bits; |
596 | } |
597 | |
598 | /// This function takes a float and returns the bit equivalent 32-bit integer. |
599 | /// Note that copying floats around changes the bits of NaNs on some hosts, |
600 | /// notably x86, so this routine cannot be used if these bits are needed. |
601 | inline uint32_t FloatToBits(float Float) { |
602 | uint32_t Bits; |
603 | static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes"); |
604 | memcpy(&Bits, &Float, sizeof(Float)); |
605 | return Bits; |
606 | } |
607 | |
608 | /// A and B are either alignments or offsets. Return the minimum alignment that |
609 | /// may be assumed after adding the two together. |
610 | constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) { |
611 | // The largest power of 2 that divides both A and B. |
612 | // |
613 | // Replace "-Value" by "1+~Value" in the following commented code to avoid |
614 | // MSVC warning C4146 |
615 | // return (A | B) & -(A | B); |
616 | return (A | B) & (1 + ~(A | B)); |
617 | } |
618 | |
619 | /// Aligns \c Addr to \c Alignment bytes, rounding up. |
620 | /// |
621 | /// Alignment should be a power of two. This method rounds up, so |
622 | /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8. |
623 | inline uintptr_t alignAddr(const void *Addr, size_t Alignment) { |
624 | assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&((Alignment && isPowerOf2_64((uint64_t)Alignment) && "Alignment is not a power of two!") ? static_cast<void> (0) : __assert_fail ("Alignment && isPowerOf2_64((uint64_t)Alignment) && \"Alignment is not a power of two!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 625, __PRETTY_FUNCTION__)) |
625 | "Alignment is not a power of two!")((Alignment && isPowerOf2_64((uint64_t)Alignment) && "Alignment is not a power of two!") ? static_cast<void> (0) : __assert_fail ("Alignment && isPowerOf2_64((uint64_t)Alignment) && \"Alignment is not a power of two!\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 625, __PRETTY_FUNCTION__)); |
626 | |
627 | assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr)(((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr) ? static_cast <void> (0) : __assert_fail ("(uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 627, __PRETTY_FUNCTION__)); |
628 | |
629 | return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1)); |
630 | } |
631 | |
632 | /// Returns the necessary adjustment for aligning \c Ptr to \c Alignment |
633 | /// bytes, rounding up. |
634 | inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) { |
635 | return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr; |
636 | } |
637 | |
638 | /// Returns the next power of two (in 64-bits) that is strictly greater than A. |
639 | /// Returns zero on overflow. |
640 | inline uint64_t NextPowerOf2(uint64_t A) { |
641 | A |= (A >> 1); |
642 | A |= (A >> 2); |
643 | A |= (A >> 4); |
644 | A |= (A >> 8); |
645 | A |= (A >> 16); |
646 | A |= (A >> 32); |
647 | return A + 1; |
648 | } |
649 | |
650 | /// Returns the power of two which is less than or equal to the given value. |
651 | /// Essentially, it is a floor operation across the domain of powers of two. |
652 | inline uint64_t PowerOf2Floor(uint64_t A) { |
653 | if (!A) return 0; |
654 | return 1ull << (63 - countLeadingZeros(A, ZB_Undefined)); |
655 | } |
656 | |
657 | /// Returns the power of two which is greater than or equal to the given value. |
658 | /// Essentially, it is a ceil operation across the domain of powers of two. |
659 | inline uint64_t PowerOf2Ceil(uint64_t A) { |
660 | if (!A) |
661 | return 0; |
662 | return NextPowerOf2(A - 1); |
663 | } |
664 | |
665 | /// Returns the next integer (mod 2**64) that is greater than or equal to |
666 | /// \p Value and is a multiple of \p Align. \p Align must be non-zero. |
667 | /// |
668 | /// If non-zero \p Skew is specified, the return value will be a minimal |
669 | /// integer that is greater than or equal to \p Value and equal to |
670 | /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than |
671 | /// \p Align, its value is adjusted to '\p Skew mod \p Align'. |
672 | /// |
673 | /// Examples: |
674 | /// \code |
675 | /// alignTo(5, 8) = 8 |
676 | /// alignTo(17, 8) = 24 |
677 | /// alignTo(~0LL, 8) = 0 |
678 | /// alignTo(321, 255) = 510 |
679 | /// |
680 | /// alignTo(5, 8, 7) = 7 |
681 | /// alignTo(17, 8, 1) = 17 |
682 | /// alignTo(~0LL, 8, 3) = 3 |
683 | /// alignTo(321, 255, 42) = 552 |
684 | /// \endcode |
685 | inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { |
686 | assert(Align != 0u && "Align can't be 0.")((Align != 0u && "Align can't be 0.") ? static_cast< void> (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 686, __PRETTY_FUNCTION__)); |
687 | Skew %= Align; |
688 | return (Value + Align - 1 - Skew) / Align * Align + Skew; |
689 | } |
690 | |
691 | /// Returns the next integer (mod 2**64) that is greater than or equal to |
692 | /// \p Value and is a multiple of \c Align. \c Align must be non-zero. |
693 | template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) { |
694 | static_assert(Align != 0u, "Align must be non-zero"); |
695 | return (Value + Align - 1) / Align * Align; |
696 | } |
697 | |
698 | /// Returns the integer ceil(Numerator / Denominator). |
699 | inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) { |
700 | return alignTo(Numerator, Denominator) / Denominator; |
701 | } |
702 | |
703 | /// \c alignTo for contexts where a constant expression is required. |
704 | /// \sa alignTo |
705 | /// |
706 | /// \todo FIXME: remove when \c constexpr becomes really \c constexpr |
707 | template <uint64_t Align> |
708 | struct AlignTo { |
709 | static_assert(Align != 0u, "Align must be non-zero"); |
710 | template <uint64_t Value> |
711 | struct from_value { |
712 | static const uint64_t value = (Value + Align - 1) / Align * Align; |
713 | }; |
714 | }; |
715 | |
716 | /// Returns the largest uint64_t less than or equal to \p Value and is |
717 | /// \p Skew mod \p Align. \p Align must be non-zero |
718 | inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) { |
719 | assert(Align != 0u && "Align can't be 0.")((Align != 0u && "Align can't be 0.") ? static_cast< void> (0) : __assert_fail ("Align != 0u && \"Align can't be 0.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 719, __PRETTY_FUNCTION__)); |
720 | Skew %= Align; |
721 | return (Value - Skew) / Align * Align + Skew; |
722 | } |
723 | |
724 | /// Returns the offset to the next integer (mod 2**64) that is greater than |
725 | /// or equal to \p Value and is a multiple of \p Align. \p Align must be |
726 | /// non-zero. |
727 | inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) { |
728 | return alignTo(Value, Align) - Value; |
729 | } |
730 | |
731 | /// Sign-extend the number in the bottom B bits of X to a 32-bit integer. |
732 | /// Requires 0 < B <= 32. |
733 | template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) { |
734 | static_assert(B > 0, "Bit width can't be 0."); |
735 | static_assert(B <= 32, "Bit width out of range."); |
736 | return int32_t(X << (32 - B)) >> (32 - B); |
737 | } |
738 | |
739 | /// Sign-extend the number in the bottom B bits of X to a 32-bit integer. |
740 | /// Requires 0 < B < 32. |
741 | inline int32_t SignExtend32(uint32_t X, unsigned B) { |
742 | assert(B > 0 && "Bit width can't be 0.")((B > 0 && "Bit width can't be 0.") ? static_cast< void> (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 742, __PRETTY_FUNCTION__)); |
743 | assert(B <= 32 && "Bit width out of range.")((B <= 32 && "Bit width out of range.") ? static_cast <void> (0) : __assert_fail ("B <= 32 && \"Bit width out of range.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 743, __PRETTY_FUNCTION__)); |
744 | return int32_t(X << (32 - B)) >> (32 - B); |
745 | } |
746 | |
747 | /// Sign-extend the number in the bottom B bits of X to a 64-bit integer. |
748 | /// Requires 0 < B < 64. |
749 | template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) { |
750 | static_assert(B > 0, "Bit width can't be 0."); |
751 | static_assert(B <= 64, "Bit width out of range."); |
752 | return int64_t(x << (64 - B)) >> (64 - B); |
753 | } |
754 | |
755 | /// Sign-extend the number in the bottom B bits of X to a 64-bit integer. |
756 | /// Requires 0 < B < 64. |
757 | inline int64_t SignExtend64(uint64_t X, unsigned B) { |
758 | assert(B > 0 && "Bit width can't be 0.")((B > 0 && "Bit width can't be 0.") ? static_cast< void> (0) : __assert_fail ("B > 0 && \"Bit width can't be 0.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 758, __PRETTY_FUNCTION__)); |
759 | assert(B <= 64 && "Bit width out of range.")((B <= 64 && "Bit width out of range.") ? static_cast <void> (0) : __assert_fail ("B <= 64 && \"Bit width out of range.\"" , "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/MathExtras.h" , 759, __PRETTY_FUNCTION__)); |
760 | return int64_t(X << (64 - B)) >> (64 - B); |
761 | } |
762 | |
763 | /// Subtract two unsigned integers, X and Y, of type T and return the absolute |
764 | /// value of the result. |
765 | template <typename T> |
766 | typename std::enable_if<std::is_unsigned<T>::value, T>::type |
767 | AbsoluteDifference(T X, T Y) { |
768 | return std::max(X, Y) - std::min(X, Y); |
769 | } |
770 | |
771 | /// Add two unsigned integers, X and Y, of type T. Clamp the result to the |
772 | /// maximum representable value of T on overflow. ResultOverflowed indicates if |
773 | /// the result is larger than the maximum representable value of type T. |
774 | template <typename T> |
775 | typename std::enable_if<std::is_unsigned<T>::value, T>::type |
776 | SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) { |
777 | bool Dummy; |
778 | bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; |
779 | // Hacker's Delight, p. 29 |
780 | T Z = X + Y; |
781 | Overflowed = (Z < X || Z < Y); |
782 | if (Overflowed) |
783 | return std::numeric_limits<T>::max(); |
784 | else |
785 | return Z; |
786 | } |
787 | |
788 | /// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the |
789 | /// maximum representable value of T on overflow. ResultOverflowed indicates if |
790 | /// the result is larger than the maximum representable value of type T. |
791 | template <typename T> |
792 | typename std::enable_if<std::is_unsigned<T>::value, T>::type |
793 | SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) { |
794 | bool Dummy; |
795 | bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; |
796 | |
797 | // Hacker's Delight, p. 30 has a different algorithm, but we don't use that |
798 | // because it fails for uint16_t (where multiplication can have undefined |
799 | // behavior due to promotion to int), and requires a division in addition |
800 | // to the multiplication. |
801 | |
802 | Overflowed = false; |
803 | |
804 | // Log2(Z) would be either Log2Z or Log2Z + 1. |
805 | // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z |
806 | // will necessarily be less than Log2Max as desired. |
807 | int Log2Z = Log2_64(X) + Log2_64(Y); |
808 | const T Max = std::numeric_limits<T>::max(); |
809 | int Log2Max = Log2_64(Max); |
810 | if (Log2Z < Log2Max) { |
811 | return X * Y; |
812 | } |
813 | if (Log2Z > Log2Max) { |
814 | Overflowed = true; |
815 | return Max; |
816 | } |
817 | |
818 | // We're going to use the top bit, and maybe overflow one |
819 | // bit past it. Multiply all but the bottom bit then add |
820 | // that on at the end. |
821 | T Z = (X >> 1) * Y; |
822 | if (Z & ~(Max >> 1)) { |
823 | Overflowed = true; |
824 | return Max; |
825 | } |
826 | Z <<= 1; |
827 | if (X & 1) |
828 | return SaturatingAdd(Z, Y, ResultOverflowed); |
829 | |
830 | return Z; |
831 | } |
832 | |
833 | /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to |
834 | /// the product. Clamp the result to the maximum representable value of T on |
835 | /// overflow. ResultOverflowed indicates if the result is larger than the |
836 | /// maximum representable value of type T. |
837 | template <typename T> |
838 | typename std::enable_if<std::is_unsigned<T>::value, T>::type |
839 | SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) { |
840 | bool Dummy; |
841 | bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy; |
842 | |
843 | T Product = SaturatingMultiply(X, Y, &Overflowed); |
844 | if (Overflowed) |
845 | return Product; |
846 | |
847 | return SaturatingAdd(A, Product, &Overflowed); |
848 | } |
849 | |
850 | /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC. |
851 | extern const float huge_valf; |
852 | } // End llvm namespace |
853 | |
854 | #endif |