Bug Summary

File:llvm/include/llvm/MC/LaneBitmask.h
Warning:line 85, column 34
The result of the left shift is undefined due to shifting by '4294967295', which is greater or equal to the width of type 'llvm::LaneBitmask::Type'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CodeGenRegisters.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/utils/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/utils/TableGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp

1//===- CodeGenRegisters.cpp - Register and RegisterClass Info -------------===//
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// This file defines structures to encapsulate information gleaned from the
10// target register and register class definitions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenRegisters.h"
15#include "CodeGenTarget.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/BitVector.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/IntEqClasses.h"
20#include "llvm/ADT/SetVector.h"
21#include "llvm/ADT/SmallPtrSet.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/Twine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/TableGen/Error.h"
32#include "llvm/TableGen/Record.h"
33#include <algorithm>
34#include <cassert>
35#include <cstdint>
36#include <iterator>
37#include <map>
38#include <queue>
39#include <set>
40#include <string>
41#include <tuple>
42#include <utility>
43#include <vector>
44
45using namespace llvm;
46
47#define DEBUG_TYPE"regalloc-emitter" "regalloc-emitter"
48
49//===----------------------------------------------------------------------===//
50// CodeGenSubRegIndex
51//===----------------------------------------------------------------------===//
52
53CodeGenSubRegIndex::CodeGenSubRegIndex(Record *R, unsigned Enum)
54 : TheDef(R), EnumValue(Enum), AllSuperRegsCovered(true), Artificial(true) {
55 Name = std::string(R->getName());
56 if (R->getValue("Namespace"))
57 Namespace = std::string(R->getValueAsString("Namespace"));
58 Size = R->getValueAsInt("Size");
59 Offset = R->getValueAsInt("Offset");
60}
61
62CodeGenSubRegIndex::CodeGenSubRegIndex(StringRef N, StringRef Nspace,
63 unsigned Enum)
64 : TheDef(nullptr), Name(std::string(N)), Namespace(std::string(Nspace)),
65 Size(-1), Offset(-1), EnumValue(Enum), AllSuperRegsCovered(true),
66 Artificial(true) {}
67
68std::string CodeGenSubRegIndex::getQualifiedName() const {
69 std::string N = getNamespace();
70 if (!N.empty())
71 N += "::";
72 N += getName();
73 return N;
74}
75
76void CodeGenSubRegIndex::updateComponents(CodeGenRegBank &RegBank) {
77 if (!TheDef)
78 return;
79
80 std::vector<Record*> Comps = TheDef->getValueAsListOfDefs("ComposedOf");
81 if (!Comps.empty()) {
82 if (Comps.size() != 2)
83 PrintFatalError(TheDef->getLoc(),
84 "ComposedOf must have exactly two entries");
85 CodeGenSubRegIndex *A = RegBank.getSubRegIdx(Comps[0]);
86 CodeGenSubRegIndex *B = RegBank.getSubRegIdx(Comps[1]);
87 CodeGenSubRegIndex *X = A->addComposite(B, this);
88 if (X)
89 PrintFatalError(TheDef->getLoc(), "Ambiguous ComposedOf entries");
90 }
91
92 std::vector<Record*> Parts =
93 TheDef->getValueAsListOfDefs("CoveringSubRegIndices");
94 if (!Parts.empty()) {
95 if (Parts.size() < 2)
96 PrintFatalError(TheDef->getLoc(),
97 "CoveredBySubRegs must have two or more entries");
98 SmallVector<CodeGenSubRegIndex*, 8> IdxParts;
99 for (Record *Part : Parts)
100 IdxParts.push_back(RegBank.getSubRegIdx(Part));
101 setConcatenationOf(IdxParts);
102 }
103}
104
105LaneBitmask CodeGenSubRegIndex::computeLaneMask() const {
106 // Already computed?
107 if (LaneMask.any())
108 return LaneMask;
109
110 // Recursion guard, shouldn't be required.
111 LaneMask = LaneBitmask::getAll();
112
113 // The lane mask is simply the union of all sub-indices.
114 LaneBitmask M;
115 for (const auto &C : Composed)
116 M |= C.second->computeLaneMask();
117 assert(M.any() && "Missing lane mask, sub-register cycle?")((M.any() && "Missing lane mask, sub-register cycle?"
) ? static_cast<void> (0) : __assert_fail ("M.any() && \"Missing lane mask, sub-register cycle?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 117, __PRETTY_FUNCTION__))
;
118 LaneMask = M;
119 return LaneMask;
120}
121
122void CodeGenSubRegIndex::setConcatenationOf(
123 ArrayRef<CodeGenSubRegIndex*> Parts) {
124 if (ConcatenationOf.empty())
125 ConcatenationOf.assign(Parts.begin(), Parts.end());
126 else
127 assert(std::equal(Parts.begin(), Parts.end(),((std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin
()) && "parts consistent") ? static_cast<void> (
0) : __assert_fail ("std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin()) && \"parts consistent\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 128, __PRETTY_FUNCTION__))
128 ConcatenationOf.begin()) && "parts consistent")((std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin
()) && "parts consistent") ? static_cast<void> (
0) : __assert_fail ("std::equal(Parts.begin(), Parts.end(), ConcatenationOf.begin()) && \"parts consistent\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 128, __PRETTY_FUNCTION__))
;
129}
130
131void CodeGenSubRegIndex::computeConcatTransitiveClosure() {
132 for (SmallVectorImpl<CodeGenSubRegIndex*>::iterator
133 I = ConcatenationOf.begin(); I != ConcatenationOf.end(); /*empty*/) {
134 CodeGenSubRegIndex *SubIdx = *I;
135 SubIdx->computeConcatTransitiveClosure();
136#ifndef NDEBUG
137 for (CodeGenSubRegIndex *SRI : SubIdx->ConcatenationOf)
138 assert(SRI->ConcatenationOf.empty() && "No transitive closure?")((SRI->ConcatenationOf.empty() && "No transitive closure?"
) ? static_cast<void> (0) : __assert_fail ("SRI->ConcatenationOf.empty() && \"No transitive closure?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 138, __PRETTY_FUNCTION__))
;
139#endif
140
141 if (SubIdx->ConcatenationOf.empty()) {
142 ++I;
143 } else {
144 I = ConcatenationOf.erase(I);
145 I = ConcatenationOf.insert(I, SubIdx->ConcatenationOf.begin(),
146 SubIdx->ConcatenationOf.end());
147 I += SubIdx->ConcatenationOf.size();
148 }
149 }
150}
151
152//===----------------------------------------------------------------------===//
153// CodeGenRegister
154//===----------------------------------------------------------------------===//
155
156CodeGenRegister::CodeGenRegister(Record *R, unsigned Enum)
157 : TheDef(R),
158 EnumValue(Enum),
159 CostPerUse(R->getValueAsInt("CostPerUse")),
160 CoveredBySubRegs(R->getValueAsBit("CoveredBySubRegs")),
161 HasDisjunctSubRegs(false),
162 SubRegsComplete(false),
163 SuperRegsComplete(false),
164 TopoSig(~0u) {
165 Artificial = R->getValueAsBit("isArtificial");
166}
167
168void CodeGenRegister::buildObjectGraph(CodeGenRegBank &RegBank) {
169 std::vector<Record*> SRIs = TheDef->getValueAsListOfDefs("SubRegIndices");
170 std::vector<Record*> SRs = TheDef->getValueAsListOfDefs("SubRegs");
171
172 if (SRIs.size() != SRs.size())
173 PrintFatalError(TheDef->getLoc(),
174 "SubRegs and SubRegIndices must have the same size");
175
176 for (unsigned i = 0, e = SRIs.size(); i != e; ++i) {
177 ExplicitSubRegIndices.push_back(RegBank.getSubRegIdx(SRIs[i]));
178 ExplicitSubRegs.push_back(RegBank.getReg(SRs[i]));
179 }
180
181 // Also compute leading super-registers. Each register has a list of
182 // covered-by-subregs super-registers where it appears as the first explicit
183 // sub-register.
184 //
185 // This is used by computeSecondarySubRegs() to find candidates.
186 if (CoveredBySubRegs && !ExplicitSubRegs.empty())
187 ExplicitSubRegs.front()->LeadingSuperRegs.push_back(this);
188
189 // Add ad hoc alias links. This is a symmetric relationship between two
190 // registers, so build a symmetric graph by adding links in both ends.
191 std::vector<Record*> Aliases = TheDef->getValueAsListOfDefs("Aliases");
192 for (Record *Alias : Aliases) {
193 CodeGenRegister *Reg = RegBank.getReg(Alias);
194 ExplicitAliases.push_back(Reg);
195 Reg->ExplicitAliases.push_back(this);
196 }
197}
198
199const StringRef CodeGenRegister::getName() const {
200 assert(TheDef && "no def")((TheDef && "no def") ? static_cast<void> (0) :
__assert_fail ("TheDef && \"no def\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 200, __PRETTY_FUNCTION__))
;
201 return TheDef->getName();
202}
203
204namespace {
205
206// Iterate over all register units in a set of registers.
207class RegUnitIterator {
208 CodeGenRegister::Vec::const_iterator RegI, RegE;
209 CodeGenRegister::RegUnitList::iterator UnitI, UnitE;
210
211public:
212 RegUnitIterator(const CodeGenRegister::Vec &Regs):
213 RegI(Regs.begin()), RegE(Regs.end()) {
214
215 if (RegI != RegE) {
216 UnitI = (*RegI)->getRegUnits().begin();
217 UnitE = (*RegI)->getRegUnits().end();
218 advance();
219 }
220 }
221
222 bool isValid() const { return UnitI != UnitE; }
223
224 unsigned operator* () const { assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 224, __PRETTY_FUNCTION__))
; return *UnitI; }
225
226 const CodeGenRegister *getReg() const { assert(isValid())((isValid()) ? static_cast<void> (0) : __assert_fail ("isValid()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 226, __PRETTY_FUNCTION__))
; return *RegI; }
227
228 /// Preincrement. Move to the next unit.
229 void operator++() {
230 assert(isValid() && "Cannot advance beyond the last operand")((isValid() && "Cannot advance beyond the last operand"
) ? static_cast<void> (0) : __assert_fail ("isValid() && \"Cannot advance beyond the last operand\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 230, __PRETTY_FUNCTION__))
;
231 ++UnitI;
232 advance();
233 }
234
235protected:
236 void advance() {
237 while (UnitI == UnitE) {
238 if (++RegI == RegE)
239 break;
240 UnitI = (*RegI)->getRegUnits().begin();
241 UnitE = (*RegI)->getRegUnits().end();
242 }
243 }
244};
245
246} // end anonymous namespace
247
248// Return true of this unit appears in RegUnits.
249static bool hasRegUnit(CodeGenRegister::RegUnitList &RegUnits, unsigned Unit) {
250 return RegUnits.test(Unit);
251}
252
253// Inherit register units from subregisters.
254// Return true if the RegUnits changed.
255bool CodeGenRegister::inheritRegUnits(CodeGenRegBank &RegBank) {
256 bool changed = false;
257 for (const auto &SubReg : SubRegs) {
258 CodeGenRegister *SR = SubReg.second;
259 // Merge the subregister's units into this register's RegUnits.
260 changed |= (RegUnits |= SR->RegUnits);
261 }
262
263 return changed;
264}
265
266const CodeGenRegister::SubRegMap &
267CodeGenRegister::computeSubRegs(CodeGenRegBank &RegBank) {
268 // Only compute this map once.
269 if (SubRegsComplete)
270 return SubRegs;
271 SubRegsComplete = true;
272
273 HasDisjunctSubRegs = ExplicitSubRegs.size() > 1;
274
275 // First insert the explicit subregs and make sure they are fully indexed.
276 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
277 CodeGenRegister *SR = ExplicitSubRegs[i];
278 CodeGenSubRegIndex *Idx = ExplicitSubRegIndices[i];
279 if (!SR->Artificial)
280 Idx->Artificial = false;
281 if (!SubRegs.insert(std::make_pair(Idx, SR)).second)
282 PrintFatalError(TheDef->getLoc(), "SubRegIndex " + Idx->getName() +
283 " appears twice in Register " + getName());
284 // Map explicit sub-registers first, so the names take precedence.
285 // The inherited sub-registers are mapped below.
286 SubReg2Idx.insert(std::make_pair(SR, Idx));
287 }
288
289 // Keep track of inherited subregs and how they can be reached.
290 SmallPtrSet<CodeGenRegister*, 8> Orphans;
291
292 // Clone inherited subregs and place duplicate entries in Orphans.
293 // Here the order is important - earlier subregs take precedence.
294 for (CodeGenRegister *ESR : ExplicitSubRegs) {
295 const SubRegMap &Map = ESR->computeSubRegs(RegBank);
296 HasDisjunctSubRegs |= ESR->HasDisjunctSubRegs;
297
298 for (const auto &SR : Map) {
299 if (!SubRegs.insert(SR).second)
300 Orphans.insert(SR.second);
301 }
302 }
303
304 // Expand any composed subreg indices.
305 // If dsub_2 has ComposedOf = [qsub_1, dsub_0], and this register has a
306 // qsub_1 subreg, add a dsub_2 subreg. Keep growing Indices and process
307 // expanded subreg indices recursively.
308 SmallVector<CodeGenSubRegIndex*, 8> Indices = ExplicitSubRegIndices;
309 for (unsigned i = 0; i != Indices.size(); ++i) {
310 CodeGenSubRegIndex *Idx = Indices[i];
311 const CodeGenSubRegIndex::CompMap &Comps = Idx->getComposites();
312 CodeGenRegister *SR = SubRegs[Idx];
313 const SubRegMap &Map = SR->computeSubRegs(RegBank);
314
315 // Look at the possible compositions of Idx.
316 // They may not all be supported by SR.
317 for (CodeGenSubRegIndex::CompMap::const_iterator I = Comps.begin(),
318 E = Comps.end(); I != E; ++I) {
319 SubRegMap::const_iterator SRI = Map.find(I->first);
320 if (SRI == Map.end())
321 continue; // Idx + I->first doesn't exist in SR.
322 // Add I->second as a name for the subreg SRI->second, assuming it is
323 // orphaned, and the name isn't already used for something else.
324 if (SubRegs.count(I->second) || !Orphans.erase(SRI->second))
325 continue;
326 // We found a new name for the orphaned sub-register.
327 SubRegs.insert(std::make_pair(I->second, SRI->second));
328 Indices.push_back(I->second);
329 }
330 }
331
332 // Now Orphans contains the inherited subregisters without a direct index.
333 // Create inferred indexes for all missing entries.
334 // Work backwards in the Indices vector in order to compose subregs bottom-up.
335 // Consider this subreg sequence:
336 //
337 // qsub_1 -> dsub_0 -> ssub_0
338 //
339 // The qsub_1 -> dsub_0 composition becomes dsub_2, so the ssub_0 register
340 // can be reached in two different ways:
341 //
342 // qsub_1 -> ssub_0
343 // dsub_2 -> ssub_0
344 //
345 // We pick the latter composition because another register may have [dsub_0,
346 // dsub_1, dsub_2] subregs without necessarily having a qsub_1 subreg. The
347 // dsub_2 -> ssub_0 composition can be shared.
348 while (!Indices.empty() && !Orphans.empty()) {
349 CodeGenSubRegIndex *Idx = Indices.pop_back_val();
350 CodeGenRegister *SR = SubRegs[Idx];
351 const SubRegMap &Map = SR->computeSubRegs(RegBank);
352 for (const auto &SubReg : Map)
353 if (Orphans.erase(SubReg.second))
354 SubRegs[RegBank.getCompositeSubRegIndex(Idx, SubReg.first)] = SubReg.second;
355 }
356
357 // Compute the inverse SubReg -> Idx map.
358 for (const auto &SubReg : SubRegs) {
359 if (SubReg.second == this) {
360 ArrayRef<SMLoc> Loc;
361 if (TheDef)
362 Loc = TheDef->getLoc();
363 PrintFatalError(Loc, "Register " + getName() +
364 " has itself as a sub-register");
365 }
366
367 // Compute AllSuperRegsCovered.
368 if (!CoveredBySubRegs)
369 SubReg.first->AllSuperRegsCovered = false;
370
371 // Ensure that every sub-register has a unique name.
372 DenseMap<const CodeGenRegister*, CodeGenSubRegIndex*>::iterator Ins =
373 SubReg2Idx.insert(std::make_pair(SubReg.second, SubReg.first)).first;
374 if (Ins->second == SubReg.first)
375 continue;
376 // Trouble: Two different names for SubReg.second.
377 ArrayRef<SMLoc> Loc;
378 if (TheDef)
379 Loc = TheDef->getLoc();
380 PrintFatalError(Loc, "Sub-register can't have two names: " +
381 SubReg.second->getName() + " available as " +
382 SubReg.first->getName() + " and " + Ins->second->getName());
383 }
384
385 // Derive possible names for sub-register concatenations from any explicit
386 // sub-registers. By doing this before computeSecondarySubRegs(), we ensure
387 // that getConcatSubRegIndex() won't invent any concatenated indices that the
388 // user already specified.
389 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
390 CodeGenRegister *SR = ExplicitSubRegs[i];
391 if (!SR->CoveredBySubRegs || SR->ExplicitSubRegs.size() <= 1 ||
392 SR->Artificial)
393 continue;
394
395 // SR is composed of multiple sub-regs. Find their names in this register.
396 SmallVector<CodeGenSubRegIndex*, 8> Parts;
397 for (unsigned j = 0, e = SR->ExplicitSubRegs.size(); j != e; ++j) {
398 CodeGenSubRegIndex &I = *SR->ExplicitSubRegIndices[j];
399 if (!I.Artificial)
400 Parts.push_back(getSubRegIndex(SR->ExplicitSubRegs[j]));
401 }
402
403 // Offer this as an existing spelling for the concatenation of Parts.
404 CodeGenSubRegIndex &Idx = *ExplicitSubRegIndices[i];
405 Idx.setConcatenationOf(Parts);
406 }
407
408 // Initialize RegUnitList. Because getSubRegs is called recursively, this
409 // processes the register hierarchy in postorder.
410 //
411 // Inherit all sub-register units. It is good enough to look at the explicit
412 // sub-registers, the other registers won't contribute any more units.
413 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
414 CodeGenRegister *SR = ExplicitSubRegs[i];
415 RegUnits |= SR->RegUnits;
416 }
417
418 // Absent any ad hoc aliasing, we create one register unit per leaf register.
419 // These units correspond to the maximal cliques in the register overlap
420 // graph which is optimal.
421 //
422 // When there is ad hoc aliasing, we simply create one unit per edge in the
423 // undirected ad hoc aliasing graph. Technically, we could do better by
424 // identifying maximal cliques in the ad hoc graph, but cliques larger than 2
425 // are extremely rare anyway (I've never seen one), so we don't bother with
426 // the added complexity.
427 for (unsigned i = 0, e = ExplicitAliases.size(); i != e; ++i) {
428 CodeGenRegister *AR = ExplicitAliases[i];
429 // Only visit each edge once.
430 if (AR->SubRegsComplete)
431 continue;
432 // Create a RegUnit representing this alias edge, and add it to both
433 // registers.
434 unsigned Unit = RegBank.newRegUnit(this, AR);
435 RegUnits.set(Unit);
436 AR->RegUnits.set(Unit);
437 }
438
439 // Finally, create units for leaf registers without ad hoc aliases. Note that
440 // a leaf register with ad hoc aliases doesn't get its own unit - it isn't
441 // necessary. This means the aliasing leaf registers can share a single unit.
442 if (RegUnits.empty())
443 RegUnits.set(RegBank.newRegUnit(this));
444
445 // We have now computed the native register units. More may be adopted later
446 // for balancing purposes.
447 NativeRegUnits = RegUnits;
448
449 return SubRegs;
450}
451
452// In a register that is covered by its sub-registers, try to find redundant
453// sub-registers. For example:
454//
455// QQ0 = {Q0, Q1}
456// Q0 = {D0, D1}
457// Q1 = {D2, D3}
458//
459// We can infer that D1_D2 is also a sub-register, even if it wasn't named in
460// the register definition.
461//
462// The explicitly specified registers form a tree. This function discovers
463// sub-register relationships that would force a DAG.
464//
465void CodeGenRegister::computeSecondarySubRegs(CodeGenRegBank &RegBank) {
466 SmallVector<SubRegMap::value_type, 8> NewSubRegs;
467
468 std::queue<std::pair<CodeGenSubRegIndex*,CodeGenRegister*>> SubRegQueue;
469 for (std::pair<CodeGenSubRegIndex*,CodeGenRegister*> P : SubRegs)
470 SubRegQueue.push(P);
471
472 // Look at the leading super-registers of each sub-register. Those are the
473 // candidates for new sub-registers, assuming they are fully contained in
474 // this register.
475 while (!SubRegQueue.empty()) {
476 CodeGenSubRegIndex *SubRegIdx;
477 const CodeGenRegister *SubReg;
478 std::tie(SubRegIdx, SubReg) = SubRegQueue.front();
479 SubRegQueue.pop();
480
481 const CodeGenRegister::SuperRegList &Leads = SubReg->LeadingSuperRegs;
482 for (unsigned i = 0, e = Leads.size(); i != e; ++i) {
483 CodeGenRegister *Cand = const_cast<CodeGenRegister*>(Leads[i]);
484 // Already got this sub-register?
485 if (Cand == this || getSubRegIndex(Cand))
486 continue;
487 // Check if each component of Cand is already a sub-register.
488 assert(!Cand->ExplicitSubRegs.empty() &&((!Cand->ExplicitSubRegs.empty() && "Super-register has no sub-registers"
) ? static_cast<void> (0) : __assert_fail ("!Cand->ExplicitSubRegs.empty() && \"Super-register has no sub-registers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 489, __PRETTY_FUNCTION__))
489 "Super-register has no sub-registers")((!Cand->ExplicitSubRegs.empty() && "Super-register has no sub-registers"
) ? static_cast<void> (0) : __assert_fail ("!Cand->ExplicitSubRegs.empty() && \"Super-register has no sub-registers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 489, __PRETTY_FUNCTION__))
;
490 if (Cand->ExplicitSubRegs.size() == 1)
491 continue;
492 SmallVector<CodeGenSubRegIndex*, 8> Parts;
493 // We know that the first component is (SubRegIdx,SubReg). However we
494 // may still need to split it into smaller subregister parts.
495 assert(Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct")((Cand->ExplicitSubRegs[0] == SubReg && "LeadingSuperRegs correct"
) ? static_cast<void> (0) : __assert_fail ("Cand->ExplicitSubRegs[0] == SubReg && \"LeadingSuperRegs correct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 495, __PRETTY_FUNCTION__))
;
496 assert(getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct")((getSubRegIndex(SubReg) == SubRegIdx && "LeadingSuperRegs correct"
) ? static_cast<void> (0) : __assert_fail ("getSubRegIndex(SubReg) == SubRegIdx && \"LeadingSuperRegs correct\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 496, __PRETTY_FUNCTION__))
;
497 for (CodeGenRegister *SubReg : Cand->ExplicitSubRegs) {
498 if (CodeGenSubRegIndex *SubRegIdx = getSubRegIndex(SubReg)) {
499 if (SubRegIdx->ConcatenationOf.empty()) {
500 Parts.push_back(SubRegIdx);
501 } else
502 for (CodeGenSubRegIndex *SubIdx : SubRegIdx->ConcatenationOf)
503 Parts.push_back(SubIdx);
504 } else {
505 // Sub-register doesn't exist.
506 Parts.clear();
507 break;
508 }
509 }
510 // There is nothing to do if some Cand sub-register is not part of this
511 // register.
512 if (Parts.empty())
513 continue;
514
515 // Each part of Cand is a sub-register of this. Make the full Cand also
516 // a sub-register with a concatenated sub-register index.
517 CodeGenSubRegIndex *Concat = RegBank.getConcatSubRegIndex(Parts);
518 std::pair<CodeGenSubRegIndex*,CodeGenRegister*> NewSubReg =
519 std::make_pair(Concat, Cand);
520
521 if (!SubRegs.insert(NewSubReg).second)
522 continue;
523
524 // We inserted a new subregister.
525 NewSubRegs.push_back(NewSubReg);
526 SubRegQueue.push(NewSubReg);
527 SubReg2Idx.insert(std::make_pair(Cand, Concat));
528 }
529 }
530
531 // Create sub-register index composition maps for the synthesized indices.
532 for (unsigned i = 0, e = NewSubRegs.size(); i != e; ++i) {
533 CodeGenSubRegIndex *NewIdx = NewSubRegs[i].first;
534 CodeGenRegister *NewSubReg = NewSubRegs[i].second;
535 for (SubRegMap::const_iterator SI = NewSubReg->SubRegs.begin(),
536 SE = NewSubReg->SubRegs.end(); SI != SE; ++SI) {
537 CodeGenSubRegIndex *SubIdx = getSubRegIndex(SI->second);
538 if (!SubIdx)
539 PrintFatalError(TheDef->getLoc(), "No SubRegIndex for " +
540 SI->second->getName() + " in " + getName());
541 NewIdx->addComposite(SI->first, SubIdx);
542 }
543 }
544}
545
546void CodeGenRegister::computeSuperRegs(CodeGenRegBank &RegBank) {
547 // Only visit each register once.
548 if (SuperRegsComplete)
549 return;
550 SuperRegsComplete = true;
551
552 // Make sure all sub-registers have been visited first, so the super-reg
553 // lists will be topologically ordered.
554 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
555 I != E; ++I)
556 I->second->computeSuperRegs(RegBank);
557
558 // Now add this as a super-register on all sub-registers.
559 // Also compute the TopoSigId in post-order.
560 TopoSigId Id;
561 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
562 I != E; ++I) {
563 // Topological signature computed from SubIdx, TopoId(SubReg).
564 // Loops and idempotent indices have TopoSig = ~0u.
565 Id.push_back(I->first->EnumValue);
566 Id.push_back(I->second->TopoSig);
567
568 // Don't add duplicate entries.
569 if (!I->second->SuperRegs.empty() && I->second->SuperRegs.back() == this)
570 continue;
571 I->second->SuperRegs.push_back(this);
572 }
573 TopoSig = RegBank.getTopoSig(Id);
574}
575
576void
577CodeGenRegister::addSubRegsPreOrder(SetVector<const CodeGenRegister*> &OSet,
578 CodeGenRegBank &RegBank) const {
579 assert(SubRegsComplete && "Must precompute sub-registers")((SubRegsComplete && "Must precompute sub-registers")
? static_cast<void> (0) : __assert_fail ("SubRegsComplete && \"Must precompute sub-registers\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 579, __PRETTY_FUNCTION__))
;
580 for (unsigned i = 0, e = ExplicitSubRegs.size(); i != e; ++i) {
581 CodeGenRegister *SR = ExplicitSubRegs[i];
582 if (OSet.insert(SR))
583 SR->addSubRegsPreOrder(OSet, RegBank);
584 }
585 // Add any secondary sub-registers that weren't part of the explicit tree.
586 for (SubRegMap::const_iterator I = SubRegs.begin(), E = SubRegs.end();
587 I != E; ++I)
588 OSet.insert(I->second);
589}
590
591// Get the sum of this register's unit weights.
592unsigned CodeGenRegister::getWeight(const CodeGenRegBank &RegBank) const {
593 unsigned Weight = 0;
594 for (RegUnitList::iterator I = RegUnits.begin(), E = RegUnits.end();
595 I != E; ++I) {
596 Weight += RegBank.getRegUnit(*I).Weight;
597 }
598 return Weight;
599}
600
601//===----------------------------------------------------------------------===//
602// RegisterTuples
603//===----------------------------------------------------------------------===//
604
605// A RegisterTuples def is used to generate pseudo-registers from lists of
606// sub-registers. We provide a SetTheory expander class that returns the new
607// registers.
608namespace {
609
610struct TupleExpander : SetTheory::Expander {
611 // Reference to SynthDefs in the containing CodeGenRegBank, to keep track of
612 // the synthesized definitions for their lifetime.
613 std::vector<std::unique_ptr<Record>> &SynthDefs;
614
615 TupleExpander(std::vector<std::unique_ptr<Record>> &SynthDefs)
616 : SynthDefs(SynthDefs) {}
617
618 void expand(SetTheory &ST, Record *Def, SetTheory::RecSet &Elts) override {
619 std::vector<Record*> Indices = Def->getValueAsListOfDefs("SubRegIndices");
620 unsigned Dim = Indices.size();
621 ListInit *SubRegs = Def->getValueAsListInit("SubRegs");
622 if (Dim != SubRegs->size())
623 PrintFatalError(Def->getLoc(), "SubRegIndices and SubRegs size mismatch");
624 if (Dim < 2)
625 PrintFatalError(Def->getLoc(),
626 "Tuples must have at least 2 sub-registers");
627
628 // Evaluate the sub-register lists to be zipped.
629 unsigned Length = ~0u;
630 SmallVector<SetTheory::RecSet, 4> Lists(Dim);
631 for (unsigned i = 0; i != Dim; ++i) {
632 ST.evaluate(SubRegs->getElement(i), Lists[i], Def->getLoc());
633 Length = std::min(Length, unsigned(Lists[i].size()));
634 }
635
636 if (Length == 0)
637 return;
638
639 // Precompute some types.
640 Record *RegisterCl = Def->getRecords().getClass("Register");
641 RecTy *RegisterRecTy = RecordRecTy::get(RegisterCl);
642 std::vector<StringRef> RegNames =
643 Def->getValueAsListOfStrings("RegAsmNames");
644
645 // Zip them up.
646 for (unsigned n = 0; n != Length; ++n) {
647 std::string Name;
648 Record *Proto = Lists[0][n];
649 std::vector<Init*> Tuple;
650 unsigned CostPerUse = 0;
651 for (unsigned i = 0; i != Dim; ++i) {
652 Record *Reg = Lists[i][n];
653 if (i) Name += '_';
654 Name += Reg->getName();
655 Tuple.push_back(DefInit::get(Reg));
656 CostPerUse = std::max(CostPerUse,
657 unsigned(Reg->getValueAsInt("CostPerUse")));
658 }
659
660 StringInit *AsmName = StringInit::get("");
661 if (!RegNames.empty()) {
662 if (RegNames.size() <= n)
663 PrintFatalError(Def->getLoc(),
664 "Register tuple definition missing name for '" +
665 Name + "'.");
666 AsmName = StringInit::get(RegNames[n]);
667 }
668
669 // Create a new Record representing the synthesized register. This record
670 // is only for consumption by CodeGenRegister, it is not added to the
671 // RecordKeeper.
672 SynthDefs.emplace_back(
673 std::make_unique<Record>(Name, Def->getLoc(), Def->getRecords()));
674 Record *NewReg = SynthDefs.back().get();
675 Elts.insert(NewReg);
676
677 // Copy Proto super-classes.
678 ArrayRef<std::pair<Record *, SMRange>> Supers = Proto->getSuperClasses();
679 for (const auto &SuperPair : Supers)
680 NewReg->addSuperClass(SuperPair.first, SuperPair.second);
681
682 // Copy Proto fields.
683 for (unsigned i = 0, e = Proto->getValues().size(); i != e; ++i) {
684 RecordVal RV = Proto->getValues()[i];
685
686 // Skip existing fields, like NAME.
687 if (NewReg->getValue(RV.getNameInit()))
688 continue;
689
690 StringRef Field = RV.getName();
691
692 // Replace the sub-register list with Tuple.
693 if (Field == "SubRegs")
694 RV.setValue(ListInit::get(Tuple, RegisterRecTy));
695
696 if (Field == "AsmName")
697 RV.setValue(AsmName);
698
699 // CostPerUse is aggregated from all Tuple members.
700 if (Field == "CostPerUse")
701 RV.setValue(IntInit::get(CostPerUse));
702
703 // Composite registers are always covered by sub-registers.
704 if (Field == "CoveredBySubRegs")
705 RV.setValue(BitInit::get(true));
706
707 // Copy fields from the RegisterTuples def.
708 if (Field == "SubRegIndices" ||
709 Field == "CompositeIndices") {
710 NewReg->addValue(*Def->getValue(Field));
711 continue;
712 }
713
714 // Some fields get their default uninitialized value.
715 if (Field == "DwarfNumbers" ||
716 Field == "DwarfAlias" ||
717 Field == "Aliases") {
718 if (const RecordVal *DefRV = RegisterCl->getValue(Field))
719 NewReg->addValue(*DefRV);
720 continue;
721 }
722
723 // Everything else is copied from Proto.
724 NewReg->addValue(RV);
725 }
726 }
727 }
728};
729
730} // end anonymous namespace
731
732//===----------------------------------------------------------------------===//
733// CodeGenRegisterClass
734//===----------------------------------------------------------------------===//
735
736static void sortAndUniqueRegisters(CodeGenRegister::Vec &M) {
737 llvm::sort(M, deref<std::less<>>());
738 M.erase(std::unique(M.begin(), M.end(), deref<std::equal_to<>>()), M.end());
739}
740
741CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank, Record *R)
742 : TheDef(R), Name(std::string(R->getName())),
743 TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1) {
744 GeneratePressureSet = R->getValueAsBit("GeneratePressureSet");
745 std::vector<Record*> TypeList = R->getValueAsListOfDefs("RegTypes");
746 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
747 Record *Type = TypeList[i];
748 if (!Type->isSubClassOf("ValueType"))
749 PrintFatalError(R->getLoc(),
750 "RegTypes list member '" + Type->getName() +
751 "' does not derive from the ValueType class!");
752 VTs.push_back(getValueTypeByHwMode(Type, RegBank.getHwModes()));
753 }
754 assert(!VTs.empty() && "RegisterClass must contain at least one ValueType!")((!VTs.empty() && "RegisterClass must contain at least one ValueType!"
) ? static_cast<void> (0) : __assert_fail ("!VTs.empty() && \"RegisterClass must contain at least one ValueType!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 754, __PRETTY_FUNCTION__))
;
755
756 // Allocation order 0 is the full set. AltOrders provides others.
757 const SetTheory::RecVec *Elements = RegBank.getSets().expand(R);
758 ListInit *AltOrders = R->getValueAsListInit("AltOrders");
759 Orders.resize(1 + AltOrders->size());
760
761 // Default allocation order always contains all registers.
762 Artificial = true;
763 for (unsigned i = 0, e = Elements->size(); i != e; ++i) {
764 Orders[0].push_back((*Elements)[i]);
765 const CodeGenRegister *Reg = RegBank.getReg((*Elements)[i]);
766 Members.push_back(Reg);
767 Artificial &= Reg->Artificial;
768 TopoSigs.set(Reg->getTopoSig());
769 }
770 sortAndUniqueRegisters(Members);
771
772 // Alternative allocation orders may be subsets.
773 SetTheory::RecSet Order;
774 for (unsigned i = 0, e = AltOrders->size(); i != e; ++i) {
775 RegBank.getSets().evaluate(AltOrders->getElement(i), Order, R->getLoc());
776 Orders[1 + i].append(Order.begin(), Order.end());
777 // Verify that all altorder members are regclass members.
778 while (!Order.empty()) {
779 CodeGenRegister *Reg = RegBank.getReg(Order.back());
780 Order.pop_back();
781 if (!contains(Reg))
782 PrintFatalError(R->getLoc(), " AltOrder register " + Reg->getName() +
783 " is not a class member");
784 }
785 }
786
787 Namespace = R->getValueAsString("Namespace");
788
789 if (const RecordVal *RV = R->getValue("RegInfos"))
790 if (DefInit *DI = dyn_cast_or_null<DefInit>(RV->getValue()))
791 RSI = RegSizeInfoByHwMode(DI->getDef(), RegBank.getHwModes());
792 unsigned Size = R->getValueAsInt("Size");
793 assert((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&(((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
"Impossible to determine register size") ? static_cast<void
> (0) : __assert_fail ("(RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) && \"Impossible to determine register size\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 794, __PRETTY_FUNCTION__))
794 "Impossible to determine register size")(((RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) &&
"Impossible to determine register size") ? static_cast<void
> (0) : __assert_fail ("(RSI.hasDefault() || Size != 0 || VTs[0].isSimple()) && \"Impossible to determine register size\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 794, __PRETTY_FUNCTION__))
;
795 if (!RSI.hasDefault()) {
796 RegSizeInfo RI;
797 RI.RegSize = RI.SpillSize = Size ? Size
798 : VTs[0].getSimple().getSizeInBits();
799 RI.SpillAlignment = R->getValueAsInt("Alignment");
800 RSI.Map.insert({DefaultMode, RI});
801 }
802
803 CopyCost = R->getValueAsInt("CopyCost");
804 Allocatable = R->getValueAsBit("isAllocatable");
805 AltOrderSelect = R->getValueAsString("AltOrderSelect");
806 int AllocationPriority = R->getValueAsInt("AllocationPriority");
807 if (AllocationPriority < 0 || AllocationPriority > 63)
808 PrintFatalError(R->getLoc(), "AllocationPriority out of range [0,63]");
809 this->AllocationPriority = AllocationPriority;
810}
811
812// Create an inferred register class that was missing from the .td files.
813// Most properties will be inherited from the closest super-class after the
814// class structure has been computed.
815CodeGenRegisterClass::CodeGenRegisterClass(CodeGenRegBank &RegBank,
816 StringRef Name, Key Props)
817 : Members(*Props.Members), TheDef(nullptr), Name(std::string(Name)),
818 TopoSigs(RegBank.getNumTopoSigs()), EnumValue(-1), RSI(Props.RSI),
819 CopyCost(0), Allocatable(true), AllocationPriority(0) {
820 Artificial = true;
821 GeneratePressureSet = false;
822 for (const auto R : Members) {
823 TopoSigs.set(R->getTopoSig());
824 Artificial &= R->Artificial;
825 }
826}
827
828// Compute inherited propertied for a synthesized register class.
829void CodeGenRegisterClass::inheritProperties(CodeGenRegBank &RegBank) {
830 assert(!getDef() && "Only synthesized classes can inherit properties")((!getDef() && "Only synthesized classes can inherit properties"
) ? static_cast<void> (0) : __assert_fail ("!getDef() && \"Only synthesized classes can inherit properties\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 830, __PRETTY_FUNCTION__))
;
831 assert(!SuperClasses.empty() && "Synthesized class without super class")((!SuperClasses.empty() && "Synthesized class without super class"
) ? static_cast<void> (0) : __assert_fail ("!SuperClasses.empty() && \"Synthesized class without super class\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 831, __PRETTY_FUNCTION__))
;
832
833 // The last super-class is the smallest one.
834 CodeGenRegisterClass &Super = *SuperClasses.back();
835
836 // Most properties are copied directly.
837 // Exceptions are members, size, and alignment
838 Namespace = Super.Namespace;
839 VTs = Super.VTs;
840 CopyCost = Super.CopyCost;
841 Allocatable = Super.Allocatable;
842 AltOrderSelect = Super.AltOrderSelect;
843 AllocationPriority = Super.AllocationPriority;
844 GeneratePressureSet |= Super.GeneratePressureSet;
845
846 // Copy all allocation orders, filter out foreign registers from the larger
847 // super-class.
848 Orders.resize(Super.Orders.size());
849 for (unsigned i = 0, ie = Super.Orders.size(); i != ie; ++i)
850 for (unsigned j = 0, je = Super.Orders[i].size(); j != je; ++j)
851 if (contains(RegBank.getReg(Super.Orders[i][j])))
852 Orders[i].push_back(Super.Orders[i][j]);
853}
854
855bool CodeGenRegisterClass::contains(const CodeGenRegister *Reg) const {
856 return std::binary_search(Members.begin(), Members.end(), Reg,
857 deref<std::less<>>());
858}
859
860unsigned CodeGenRegisterClass::getWeight(const CodeGenRegBank& RegBank) const {
861 if (TheDef && !TheDef->isValueUnset("Weight"))
862 return TheDef->getValueAsInt("Weight");
863
864 if (Members.empty() || Artificial)
865 return 0;
866
867 return (*Members.begin())->getWeight(RegBank);
868}
869
870namespace llvm {
871
872 raw_ostream &operator<<(raw_ostream &OS, const CodeGenRegisterClass::Key &K) {
873 OS << "{ " << K.RSI;
874 for (const auto R : *K.Members)
875 OS << ", " << R->getName();
876 return OS << " }";
877 }
878
879} // end namespace llvm
880
881// This is a simple lexicographical order that can be used to search for sets.
882// It is not the same as the topological order provided by TopoOrderRC.
883bool CodeGenRegisterClass::Key::
884operator<(const CodeGenRegisterClass::Key &B) const {
885 assert(Members && B.Members)((Members && B.Members) ? static_cast<void> (0)
: __assert_fail ("Members && B.Members", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 885, __PRETTY_FUNCTION__))
;
886 return std::tie(*Members, RSI) < std::tie(*B.Members, B.RSI);
887}
888
889// Returns true if RC is a strict subclass.
890// RC is a sub-class of this class if it is a valid replacement for any
891// instruction operand where a register of this classis required. It must
892// satisfy these conditions:
893//
894// 1. All RC registers are also in this.
895// 2. The RC spill size must not be smaller than our spill size.
896// 3. RC spill alignment must be compatible with ours.
897//
898static bool testSubClass(const CodeGenRegisterClass *A,
899 const CodeGenRegisterClass *B) {
900 return A->RSI.isSubClassOf(B->RSI) &&
901 std::includes(A->getMembers().begin(), A->getMembers().end(),
902 B->getMembers().begin(), B->getMembers().end(),
903 deref<std::less<>>());
904}
905
906/// Sorting predicate for register classes. This provides a topological
907/// ordering that arranges all register classes before their sub-classes.
908///
909/// Register classes with the same registers, spill size, and alignment form a
910/// clique. They will be ordered alphabetically.
911///
912static bool TopoOrderRC(const CodeGenRegisterClass &PA,
913 const CodeGenRegisterClass &PB) {
914 auto *A = &PA;
915 auto *B = &PB;
916 if (A == B)
917 return false;
918
919 if (A->RSI < B->RSI)
920 return true;
921 if (A->RSI != B->RSI)
922 return false;
923
924 // Order by descending set size. Note that the classes' allocation order may
925 // not have been computed yet. The Members set is always vaild.
926 if (A->getMembers().size() > B->getMembers().size())
927 return true;
928 if (A->getMembers().size() < B->getMembers().size())
929 return false;
930
931 // Finally order by name as a tie breaker.
932 return StringRef(A->getName()) < B->getName();
933}
934
935std::string CodeGenRegisterClass::getQualifiedName() const {
936 if (Namespace.empty())
937 return getName();
938 else
939 return (Namespace + "::" + getName()).str();
940}
941
942// Compute sub-classes of all register classes.
943// Assume the classes are ordered topologically.
944void CodeGenRegisterClass::computeSubClasses(CodeGenRegBank &RegBank) {
945 auto &RegClasses = RegBank.getRegClasses();
946
947 // Visit backwards so sub-classes are seen first.
948 for (auto I = RegClasses.rbegin(), E = RegClasses.rend(); I != E; ++I) {
949 CodeGenRegisterClass &RC = *I;
950 RC.SubClasses.resize(RegClasses.size());
951 RC.SubClasses.set(RC.EnumValue);
952 if (RC.Artificial)
953 continue;
954
955 // Normally, all subclasses have IDs >= rci, unless RC is part of a clique.
956 for (auto I2 = I.base(), E2 = RegClasses.end(); I2 != E2; ++I2) {
957 CodeGenRegisterClass &SubRC = *I2;
958 if (RC.SubClasses.test(SubRC.EnumValue))
959 continue;
960 if (!testSubClass(&RC, &SubRC))
961 continue;
962 // SubRC is a sub-class. Grap all its sub-classes so we won't have to
963 // check them again.
964 RC.SubClasses |= SubRC.SubClasses;
965 }
966
967 // Sweep up missed clique members. They will be immediately preceding RC.
968 for (auto I2 = std::next(I); I2 != E && testSubClass(&RC, &*I2); ++I2)
969 RC.SubClasses.set(I2->EnumValue);
970 }
971
972 // Compute the SuperClasses lists from the SubClasses vectors.
973 for (auto &RC : RegClasses) {
974 const BitVector &SC = RC.getSubClasses();
975 auto I = RegClasses.begin();
976 for (int s = 0, next_s = SC.find_first(); next_s != -1;
977 next_s = SC.find_next(s)) {
978 std::advance(I, next_s - s);
979 s = next_s;
980 if (&*I == &RC)
981 continue;
982 I->SuperClasses.push_back(&RC);
983 }
984 }
985
986 // With the class hierarchy in place, let synthesized register classes inherit
987 // properties from their closest super-class. The iteration order here can
988 // propagate properties down multiple levels.
989 for (auto &RC : RegClasses)
990 if (!RC.getDef())
991 RC.inheritProperties(RegBank);
992}
993
994Optional<std::pair<CodeGenRegisterClass *, CodeGenRegisterClass *>>
995CodeGenRegisterClass::getMatchingSubClassWithSubRegs(
996 CodeGenRegBank &RegBank, const CodeGenSubRegIndex *SubIdx) const {
997 auto SizeOrder = [this](const CodeGenRegisterClass *A,
998 const CodeGenRegisterClass *B) {
999 // If there are multiple, identical register classes, prefer the original
1000 // register class.
1001 if (A->getMembers().size() == B->getMembers().size())
1002 return A == this;
1003 return A->getMembers().size() > B->getMembers().size();
1004 };
1005
1006 auto &RegClasses = RegBank.getRegClasses();
1007
1008 // Find all the subclasses of this one that fully support the sub-register
1009 // index and order them by size. BiggestSuperRC should always be first.
1010 CodeGenRegisterClass *BiggestSuperRegRC = getSubClassWithSubReg(SubIdx);
1011 if (!BiggestSuperRegRC)
1012 return None;
1013 BitVector SuperRegRCsBV = BiggestSuperRegRC->getSubClasses();
1014 std::vector<CodeGenRegisterClass *> SuperRegRCs;
1015 for (auto &RC : RegClasses)
1016 if (SuperRegRCsBV[RC.EnumValue])
1017 SuperRegRCs.emplace_back(&RC);
1018 llvm::stable_sort(SuperRegRCs, SizeOrder);
1019
1020 assert(SuperRegRCs.front() == BiggestSuperRegRC &&((SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first"
) ? static_cast<void> (0) : __assert_fail ("SuperRegRCs.front() == BiggestSuperRegRC && \"Biggest class wasn't first\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1021, __PRETTY_FUNCTION__))
1021 "Biggest class wasn't first")((SuperRegRCs.front() == BiggestSuperRegRC && "Biggest class wasn't first"
) ? static_cast<void> (0) : __assert_fail ("SuperRegRCs.front() == BiggestSuperRegRC && \"Biggest class wasn't first\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1021, __PRETTY_FUNCTION__))
;
1022
1023 // Find all the subreg classes and order them by size too.
1024 std::vector<std::pair<CodeGenRegisterClass *, BitVector>> SuperRegClasses;
1025 for (auto &RC: RegClasses) {
1026 BitVector SuperRegClassesBV(RegClasses.size());
1027 RC.getSuperRegClasses(SubIdx, SuperRegClassesBV);
1028 if (SuperRegClassesBV.any())
1029 SuperRegClasses.push_back(std::make_pair(&RC, SuperRegClassesBV));
1030 }
1031 llvm::sort(SuperRegClasses,
1032 [&](const std::pair<CodeGenRegisterClass *, BitVector> &A,
1033 const std::pair<CodeGenRegisterClass *, BitVector> &B) {
1034 return SizeOrder(A.first, B.first);
1035 });
1036
1037 // Find the biggest subclass and subreg class such that R:subidx is in the
1038 // subreg class for all R in subclass.
1039 //
1040 // For example:
1041 // All registers in X86's GR64 have a sub_32bit subregister but no class
1042 // exists that contains all the 32-bit subregisters because GR64 contains RIP
1043 // but GR32 does not contain EIP. Instead, we constrain SuperRegRC to
1044 // GR32_with_sub_8bit (which is identical to GR32_with_sub_32bit) and then,
1045 // having excluded RIP, we are able to find a SubRegRC (GR32).
1046 CodeGenRegisterClass *ChosenSuperRegClass = nullptr;
1047 CodeGenRegisterClass *SubRegRC = nullptr;
1048 for (auto *SuperRegRC : SuperRegRCs) {
1049 for (const auto &SuperRegClassPair : SuperRegClasses) {
1050 const BitVector &SuperRegClassBV = SuperRegClassPair.second;
1051 if (SuperRegClassBV[SuperRegRC->EnumValue]) {
1052 SubRegRC = SuperRegClassPair.first;
1053 ChosenSuperRegClass = SuperRegRC;
1054
1055 // If SubRegRC is bigger than SuperRegRC then there are members of
1056 // SubRegRC that don't have super registers via SubIdx. Keep looking to
1057 // find a better fit and fall back on this one if there isn't one.
1058 //
1059 // This is intended to prevent X86 from making odd choices such as
1060 // picking LOW32_ADDR_ACCESS_RBP instead of GR32 in the example above.
1061 // LOW32_ADDR_ACCESS_RBP is a valid choice but contains registers that
1062 // aren't subregisters of SuperRegRC whereas GR32 has a direct 1:1
1063 // mapping.
1064 if (SuperRegRC->getMembers().size() >= SubRegRC->getMembers().size())
1065 return std::make_pair(ChosenSuperRegClass, SubRegRC);
1066 }
1067 }
1068
1069 // If we found a fit but it wasn't quite ideal because SubRegRC had excess
1070 // registers, then we're done.
1071 if (ChosenSuperRegClass)
1072 return std::make_pair(ChosenSuperRegClass, SubRegRC);
1073 }
1074
1075 return None;
1076}
1077
1078void CodeGenRegisterClass::getSuperRegClasses(const CodeGenSubRegIndex *SubIdx,
1079 BitVector &Out) const {
1080 auto FindI = SuperRegClasses.find(SubIdx);
1081 if (FindI == SuperRegClasses.end())
1082 return;
1083 for (CodeGenRegisterClass *RC : FindI->second)
1084 Out.set(RC->EnumValue);
1085}
1086
1087// Populate a unique sorted list of units from a register set.
1088void CodeGenRegisterClass::buildRegUnitSet(const CodeGenRegBank &RegBank,
1089 std::vector<unsigned> &RegUnits) const {
1090 std::vector<unsigned> TmpUnits;
1091 for (RegUnitIterator UnitI(Members); UnitI.isValid(); ++UnitI) {
1092 const RegUnit &RU = RegBank.getRegUnit(*UnitI);
1093 if (!RU.Artificial)
1094 TmpUnits.push_back(*UnitI);
1095 }
1096 llvm::sort(TmpUnits);
1097 std::unique_copy(TmpUnits.begin(), TmpUnits.end(),
1098 std::back_inserter(RegUnits));
1099}
1100
1101//===----------------------------------------------------------------------===//
1102// CodeGenRegBank
1103//===----------------------------------------------------------------------===//
1104
1105CodeGenRegBank::CodeGenRegBank(RecordKeeper &Records,
1106 const CodeGenHwModes &Modes) : CGH(Modes) {
1107 // Configure register Sets to understand register classes and tuples.
1108 Sets.addFieldExpander("RegisterClass", "MemberList");
1109 Sets.addFieldExpander("CalleeSavedRegs", "SaveList");
1110 Sets.addExpander("RegisterTuples",
1111 std::make_unique<TupleExpander>(SynthDefs));
1112
1113 // Read in the user-defined (named) sub-register indices.
1114 // More indices will be synthesized later.
1115 std::vector<Record*> SRIs = Records.getAllDerivedDefinitions("SubRegIndex");
1116 llvm::sort(SRIs, LessRecord());
1117 for (unsigned i = 0, e = SRIs.size(); i != e; ++i)
1118 getSubRegIdx(SRIs[i]);
1119 // Build composite maps from ComposedOf fields.
1120 for (auto &Idx : SubRegIndices)
1121 Idx.updateComponents(*this);
1122
1123 // Read in the register definitions.
1124 std::vector<Record*> Regs = Records.getAllDerivedDefinitions("Register");
1125 llvm::sort(Regs, LessRecordRegister());
1126 // Assign the enumeration values.
1127 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1128 getReg(Regs[i]);
1129
1130 // Expand tuples and number the new registers.
1131 std::vector<Record*> Tups =
1132 Records.getAllDerivedDefinitions("RegisterTuples");
1133
1134 for (Record *R : Tups) {
1135 std::vector<Record *> TupRegs = *Sets.expand(R);
1136 llvm::sort(TupRegs, LessRecordRegister());
1137 for (Record *RC : TupRegs)
1138 getReg(RC);
1139 }
1140
1141 // Now all the registers are known. Build the object graph of explicit
1142 // register-register references.
1143 for (auto &Reg : Registers)
1144 Reg.buildObjectGraph(*this);
1145
1146 // Compute register name map.
1147 for (auto &Reg : Registers)
1148 // FIXME: This could just be RegistersByName[name] = register, except that
1149 // causes some failures in MIPS - perhaps they have duplicate register name
1150 // entries? (or maybe there's a reason for it - I don't know much about this
1151 // code, just drive-by refactoring)
1152 RegistersByName.insert(
1153 std::make_pair(Reg.TheDef->getValueAsString("AsmName"), &Reg));
1154
1155 // Precompute all sub-register maps.
1156 // This will create Composite entries for all inferred sub-register indices.
1157 for (auto &Reg : Registers)
1158 Reg.computeSubRegs(*this);
1159
1160 // Compute transitive closure of subregister index ConcatenationOf vectors
1161 // and initialize ConcatIdx map.
1162 for (CodeGenSubRegIndex &SRI : SubRegIndices) {
1163 SRI.computeConcatTransitiveClosure();
1164 if (!SRI.ConcatenationOf.empty())
1165 ConcatIdx.insert(std::make_pair(
1166 SmallVector<CodeGenSubRegIndex*,8>(SRI.ConcatenationOf.begin(),
1167 SRI.ConcatenationOf.end()), &SRI));
1168 }
1169
1170 // Infer even more sub-registers by combining leading super-registers.
1171 for (auto &Reg : Registers)
1172 if (Reg.CoveredBySubRegs)
1173 Reg.computeSecondarySubRegs(*this);
1174
1175 // After the sub-register graph is complete, compute the topologically
1176 // ordered SuperRegs list.
1177 for (auto &Reg : Registers)
1178 Reg.computeSuperRegs(*this);
1179
1180 // For each pair of Reg:SR, if both are non-artificial, mark the
1181 // corresponding sub-register index as non-artificial.
1182 for (auto &Reg : Registers) {
1183 if (Reg.Artificial)
1184 continue;
1185 for (auto P : Reg.getSubRegs()) {
1186 const CodeGenRegister *SR = P.second;
1187 if (!SR->Artificial)
1188 P.first->Artificial = false;
1189 }
1190 }
1191
1192 // Native register units are associated with a leaf register. They've all been
1193 // discovered now.
1194 NumNativeRegUnits = RegUnits.size();
1195
1196 // Read in register class definitions.
1197 std::vector<Record*> RCs = Records.getAllDerivedDefinitions("RegisterClass");
1198 if (RCs.empty())
1199 PrintFatalError("No 'RegisterClass' subclasses defined!");
1200
1201 // Allocate user-defined register classes.
1202 for (auto *R : RCs) {
1203 RegClasses.emplace_back(*this, R);
1204 CodeGenRegisterClass &RC = RegClasses.back();
1205 if (!RC.Artificial)
1206 addToMaps(&RC);
1207 }
1208
1209 // Infer missing classes to create a full algebra.
1210 computeInferredRegisterClasses();
1211
1212 // Order register classes topologically and assign enum values.
1213 RegClasses.sort(TopoOrderRC);
1214 unsigned i = 0;
1215 for (auto &RC : RegClasses)
1216 RC.EnumValue = i++;
1217 CodeGenRegisterClass::computeSubClasses(*this);
1218}
1219
1220// Create a synthetic CodeGenSubRegIndex without a corresponding Record.
1221CodeGenSubRegIndex*
1222CodeGenRegBank::createSubRegIndex(StringRef Name, StringRef Namespace) {
1223 SubRegIndices.emplace_back(Name, Namespace, SubRegIndices.size() + 1);
1224 return &SubRegIndices.back();
1225}
1226
1227CodeGenSubRegIndex *CodeGenRegBank::getSubRegIdx(Record *Def) {
1228 CodeGenSubRegIndex *&Idx = Def2SubRegIdx[Def];
1229 if (Idx)
1230 return Idx;
1231 SubRegIndices.emplace_back(Def, SubRegIndices.size() + 1);
1232 Idx = &SubRegIndices.back();
1233 return Idx;
1234}
1235
1236const CodeGenSubRegIndex *
1237CodeGenRegBank::findSubRegIdx(const Record* Def) const {
1238 auto I = Def2SubRegIdx.find(Def);
1239 return (I == Def2SubRegIdx.end()) ? nullptr : I->second;
1240}
1241
1242CodeGenRegister *CodeGenRegBank::getReg(Record *Def) {
1243 CodeGenRegister *&Reg = Def2Reg[Def];
1244 if (Reg)
1245 return Reg;
1246 Registers.emplace_back(Def, Registers.size() + 1);
1247 Reg = &Registers.back();
1248 return Reg;
1249}
1250
1251void CodeGenRegBank::addToMaps(CodeGenRegisterClass *RC) {
1252 if (Record *Def = RC->getDef())
1253 Def2RC.insert(std::make_pair(Def, RC));
1254
1255 // Duplicate classes are rejected by insert().
1256 // That's OK, we only care about the properties handled by CGRC::Key.
1257 CodeGenRegisterClass::Key K(*RC);
1258 Key2RC.insert(std::make_pair(K, RC));
1259}
1260
1261// Create a synthetic sub-class if it is missing.
1262CodeGenRegisterClass*
1263CodeGenRegBank::getOrCreateSubClass(const CodeGenRegisterClass *RC,
1264 const CodeGenRegister::Vec *Members,
1265 StringRef Name) {
1266 // Synthetic sub-class has the same size and alignment as RC.
1267 CodeGenRegisterClass::Key K(Members, RC->RSI);
1268 RCKeyMap::const_iterator FoundI = Key2RC.find(K);
1269 if (FoundI != Key2RC.end())
1270 return FoundI->second;
1271
1272 // Sub-class doesn't exist, create a new one.
1273 RegClasses.emplace_back(*this, Name, K);
1274 addToMaps(&RegClasses.back());
1275 return &RegClasses.back();
1276}
1277
1278CodeGenRegisterClass *CodeGenRegBank::getRegClass(Record *Def) {
1279 if (CodeGenRegisterClass *RC = Def2RC[Def])
1280 return RC;
1281
1282 PrintFatalError(Def->getLoc(), "Not a known RegisterClass!");
1283}
1284
1285CodeGenSubRegIndex*
1286CodeGenRegBank::getCompositeSubRegIndex(CodeGenSubRegIndex *A,
1287 CodeGenSubRegIndex *B) {
1288 // Look for an existing entry.
1289 CodeGenSubRegIndex *Comp = A->compose(B);
1290 if (Comp)
1291 return Comp;
1292
1293 // None exists, synthesize one.
1294 std::string Name = A->getName() + "_then_" + B->getName();
1295 Comp = createSubRegIndex(Name, A->getNamespace());
1296 A->addComposite(B, Comp);
1297 return Comp;
1298}
1299
1300CodeGenSubRegIndex *CodeGenRegBank::
1301getConcatSubRegIndex(const SmallVector<CodeGenSubRegIndex *, 8> &Parts) {
1302 assert(Parts.size() > 1 && "Need two parts to concatenate")((Parts.size() > 1 && "Need two parts to concatenate"
) ? static_cast<void> (0) : __assert_fail ("Parts.size() > 1 && \"Need two parts to concatenate\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1302, __PRETTY_FUNCTION__))
;
1303#ifndef NDEBUG
1304 for (CodeGenSubRegIndex *Idx : Parts) {
1305 assert(Idx->ConcatenationOf.empty() && "No transitive closure?")((Idx->ConcatenationOf.empty() && "No transitive closure?"
) ? static_cast<void> (0) : __assert_fail ("Idx->ConcatenationOf.empty() && \"No transitive closure?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1305, __PRETTY_FUNCTION__))
;
1306 }
1307#endif
1308
1309 // Look for an existing entry.
1310 CodeGenSubRegIndex *&Idx = ConcatIdx[Parts];
1311 if (Idx)
1312 return Idx;
1313
1314 // None exists, synthesize one.
1315 std::string Name = Parts.front()->getName();
1316 // Determine whether all parts are contiguous.
1317 bool isContinuous = true;
1318 unsigned Size = Parts.front()->Size;
1319 unsigned LastOffset = Parts.front()->Offset;
1320 unsigned LastSize = Parts.front()->Size;
1321 for (unsigned i = 1, e = Parts.size(); i != e; ++i) {
1322 Name += '_';
1323 Name += Parts[i]->getName();
1324 Size += Parts[i]->Size;
1325 if (Parts[i]->Offset != (LastOffset + LastSize))
1326 isContinuous = false;
1327 LastOffset = Parts[i]->Offset;
1328 LastSize = Parts[i]->Size;
1329 }
1330 Idx = createSubRegIndex(Name, Parts.front()->getNamespace());
1331 Idx->Size = Size;
1332 Idx->Offset = isContinuous ? Parts.front()->Offset : -1;
1333 Idx->ConcatenationOf.assign(Parts.begin(), Parts.end());
1334 return Idx;
1335}
1336
1337void CodeGenRegBank::computeComposites() {
1338 using RegMap = std::map<const CodeGenRegister*, const CodeGenRegister*>;
1339
1340 // Subreg -> { Reg->Reg }, where the right-hand side is the mapping from
1341 // register to (sub)register associated with the action of the left-hand
1342 // side subregister.
1343 std::map<const CodeGenSubRegIndex*, RegMap> SubRegAction;
1344 for (const CodeGenRegister &R : Registers) {
1345 const CodeGenRegister::SubRegMap &SM = R.getSubRegs();
1346 for (std::pair<const CodeGenSubRegIndex*, const CodeGenRegister*> P : SM)
1347 SubRegAction[P.first].insert({&R, P.second});
1348 }
1349
1350 // Calculate the composition of two subregisters as compositions of their
1351 // associated actions.
1352 auto compose = [&SubRegAction] (const CodeGenSubRegIndex *Sub1,
1353 const CodeGenSubRegIndex *Sub2) {
1354 RegMap C;
1355 const RegMap &Img1 = SubRegAction.at(Sub1);
1356 const RegMap &Img2 = SubRegAction.at(Sub2);
1357 for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Img1) {
1358 auto F = Img2.find(P.second);
1359 if (F != Img2.end())
1360 C.insert({P.first, F->second});
1361 }
1362 return C;
1363 };
1364
1365 // Check if the two maps agree on the intersection of their domains.
1366 auto agree = [] (const RegMap &Map1, const RegMap &Map2) {
1367 // Technically speaking, an empty map agrees with any other map, but
1368 // this could flag false positives. We're interested in non-vacuous
1369 // agreements.
1370 if (Map1.empty() || Map2.empty())
1371 return false;
1372 for (std::pair<const CodeGenRegister*, const CodeGenRegister*> P : Map1) {
1373 auto F = Map2.find(P.first);
1374 if (F == Map2.end() || P.second != F->second)
1375 return false;
1376 }
1377 return true;
1378 };
1379
1380 using CompositePair = std::pair<const CodeGenSubRegIndex*,
1381 const CodeGenSubRegIndex*>;
1382 SmallSet<CompositePair,4> UserDefined;
1383 for (const CodeGenSubRegIndex &Idx : SubRegIndices)
1384 for (auto P : Idx.getComposites())
1385 UserDefined.insert(std::make_pair(&Idx, P.first));
1386
1387 // Keep track of TopoSigs visited. We only need to visit each TopoSig once,
1388 // and many registers will share TopoSigs on regular architectures.
1389 BitVector TopoSigs(getNumTopoSigs());
1390
1391 for (const auto &Reg1 : Registers) {
1392 // Skip identical subreg structures already processed.
1393 if (TopoSigs.test(Reg1.getTopoSig()))
1394 continue;
1395 TopoSigs.set(Reg1.getTopoSig());
1396
1397 const CodeGenRegister::SubRegMap &SRM1 = Reg1.getSubRegs();
1398 for (CodeGenRegister::SubRegMap::const_iterator i1 = SRM1.begin(),
1399 e1 = SRM1.end(); i1 != e1; ++i1) {
1400 CodeGenSubRegIndex *Idx1 = i1->first;
1401 CodeGenRegister *Reg2 = i1->second;
1402 // Ignore identity compositions.
1403 if (&Reg1 == Reg2)
1404 continue;
1405 const CodeGenRegister::SubRegMap &SRM2 = Reg2->getSubRegs();
1406 // Try composing Idx1 with another SubRegIndex.
1407 for (CodeGenRegister::SubRegMap::const_iterator i2 = SRM2.begin(),
1408 e2 = SRM2.end(); i2 != e2; ++i2) {
1409 CodeGenSubRegIndex *Idx2 = i2->first;
1410 CodeGenRegister *Reg3 = i2->second;
1411 // Ignore identity compositions.
1412 if (Reg2 == Reg3)
1413 continue;
1414 // OK Reg1:IdxPair == Reg3. Find the index with Reg:Idx == Reg3.
1415 CodeGenSubRegIndex *Idx3 = Reg1.getSubRegIndex(Reg3);
1416 assert(Idx3 && "Sub-register doesn't have an index")((Idx3 && "Sub-register doesn't have an index") ? static_cast
<void> (0) : __assert_fail ("Idx3 && \"Sub-register doesn't have an index\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1416, __PRETTY_FUNCTION__))
;
1417
1418 // Conflicting composition? Emit a warning but allow it.
1419 if (CodeGenSubRegIndex *Prev = Idx1->addComposite(Idx2, Idx3)) {
1420 // If the composition was not user-defined, always emit a warning.
1421 if (!UserDefined.count({Idx1, Idx2}) ||
1422 agree(compose(Idx1, Idx2), SubRegAction.at(Idx3)))
1423 PrintWarning(Twine("SubRegIndex ") + Idx1->getQualifiedName() +
1424 " and " + Idx2->getQualifiedName() +
1425 " compose ambiguously as " + Prev->getQualifiedName() +
1426 " or " + Idx3->getQualifiedName());
1427 }
1428 }
1429 }
1430 }
1431}
1432
1433// Compute lane masks. This is similar to register units, but at the
1434// sub-register index level. Each bit in the lane mask is like a register unit
1435// class, and two lane masks will have a bit in common if two sub-register
1436// indices overlap in some register.
1437//
1438// Conservatively share a lane mask bit if two sub-register indices overlap in
1439// some registers, but not in others. That shouldn't happen a lot.
1440void CodeGenRegBank::computeSubRegLaneMasks() {
1441 // First assign individual bits to all the leaf indices.
1442 unsigned Bit = 0;
1443 // Determine mask of lanes that cover their registers.
1444 CoveringLanes = LaneBitmask::getAll();
1445 for (auto &Idx : SubRegIndices) {
1446 if (Idx.getComposites().empty()) {
1447 if (Bit > LaneBitmask::BitWidth) {
1448 PrintFatalError(
1449 Twine("Ran out of lanemask bits to represent subregister ")
1450 + Idx.getName());
1451 }
1452 Idx.LaneMask = LaneBitmask::getLane(Bit);
1453 ++Bit;
1454 } else {
1455 Idx.LaneMask = LaneBitmask::getNone();
1456 }
1457 }
1458
1459 // Compute transformation sequences for composeSubRegIndexLaneMask. The idea
1460 // here is that for each possible target subregister we look at the leafs
1461 // in the subregister graph that compose for this target and create
1462 // transformation sequences for the lanemasks. Each step in the sequence
1463 // consists of a bitmask and a bitrotate operation. As the rotation amounts
1464 // are usually the same for many subregisters we can easily combine the steps
1465 // by combining the masks.
1466 for (const auto &Idx : SubRegIndices) {
1467 const auto &Composites = Idx.getComposites();
1468 auto &LaneTransforms = Idx.CompositionLaneMaskTransform;
1469
1470 if (Composites.empty()) {
2
Assuming the condition is true
3
Taking true branch
1471 // Moving from a class with no subregisters we just had a single lane:
1472 // The subregister must be a leaf subregister and only occupies 1 bit.
1473 // Move the bit from the class without subregisters into that position.
1474 unsigned DstBit = Idx.LaneMask.getHighestLane();
4
Calling 'LaneBitmask::getHighestLane'
9
Returning from 'LaneBitmask::getHighestLane'
10
'DstBit' initialized to 4294967295
1475 assert(Idx.LaneMask == LaneBitmask::getLane(DstBit) &&((Idx.LaneMask == LaneBitmask::getLane(DstBit) && "Must be a leaf subregister"
) ? static_cast<void> (0) : __assert_fail ("Idx.LaneMask == LaneBitmask::getLane(DstBit) && \"Must be a leaf subregister\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1476, __PRETTY_FUNCTION__))
11
Passing the value 4294967295 via 1st parameter 'Lane'
12
Calling 'LaneBitmask::getLane'
1476 "Must be a leaf subregister")((Idx.LaneMask == LaneBitmask::getLane(DstBit) && "Must be a leaf subregister"
) ? static_cast<void> (0) : __assert_fail ("Idx.LaneMask == LaneBitmask::getLane(DstBit) && \"Must be a leaf subregister\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1476, __PRETTY_FUNCTION__))
;
1477 MaskRolPair MaskRol = { LaneBitmask::getLane(0), (uint8_t)DstBit };
1478 LaneTransforms.push_back(MaskRol);
1479 } else {
1480 // Go through all leaf subregisters and find the ones that compose with
1481 // Idx. These make out all possible valid bits in the lane mask we want to
1482 // transform. Looking only at the leafs ensure that only a single bit in
1483 // the mask is set.
1484 unsigned NextBit = 0;
1485 for (auto &Idx2 : SubRegIndices) {
1486 // Skip non-leaf subregisters.
1487 if (!Idx2.getComposites().empty())
1488 continue;
1489 // Replicate the behaviour from the lane mask generation loop above.
1490 unsigned SrcBit = NextBit;
1491 LaneBitmask SrcMask = LaneBitmask::getLane(SrcBit);
1492 if (NextBit < LaneBitmask::BitWidth-1)
1493 ++NextBit;
1494 assert(Idx2.LaneMask == SrcMask)((Idx2.LaneMask == SrcMask) ? static_cast<void> (0) : __assert_fail
("Idx2.LaneMask == SrcMask", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1494, __PRETTY_FUNCTION__))
;
1495
1496 // Get the composed subregister if there is any.
1497 auto C = Composites.find(&Idx2);
1498 if (C == Composites.end())
1499 continue;
1500 const CodeGenSubRegIndex *Composite = C->second;
1501 // The Composed subreg should be a leaf subreg too
1502 assert(Composite->getComposites().empty())((Composite->getComposites().empty()) ? static_cast<void
> (0) : __assert_fail ("Composite->getComposites().empty()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1502, __PRETTY_FUNCTION__))
;
1503
1504 // Create Mask+Rotate operation and merge with existing ops if possible.
1505 unsigned DstBit = Composite->LaneMask.getHighestLane();
1506 int Shift = DstBit - SrcBit;
1507 uint8_t RotateLeft = Shift >= 0 ? (uint8_t)Shift
1508 : LaneBitmask::BitWidth + Shift;
1509 for (auto &I : LaneTransforms) {
1510 if (I.RotateLeft == RotateLeft) {
1511 I.Mask |= SrcMask;
1512 SrcMask = LaneBitmask::getNone();
1513 }
1514 }
1515 if (SrcMask.any()) {
1516 MaskRolPair MaskRol = { SrcMask, RotateLeft };
1517 LaneTransforms.push_back(MaskRol);
1518 }
1519 }
1520 }
1521
1522 // Optimize if the transformation consists of one step only: Set mask to
1523 // 0xffffffff (including some irrelevant invalid bits) so that it should
1524 // merge with more entries later while compressing the table.
1525 if (LaneTransforms.size() == 1)
1526 LaneTransforms[0].Mask = LaneBitmask::getAll();
1527
1528 // Further compression optimization: For invalid compositions resulting
1529 // in a sequence with 0 entries we can just pick any other. Choose
1530 // Mask 0xffffffff with Rotation 0.
1531 if (LaneTransforms.size() == 0) {
1532 MaskRolPair P = { LaneBitmask::getAll(), 0 };
1533 LaneTransforms.push_back(P);
1534 }
1535 }
1536
1537 // FIXME: What if ad-hoc aliasing introduces overlaps that aren't represented
1538 // by the sub-register graph? This doesn't occur in any known targets.
1539
1540 // Inherit lanes from composites.
1541 for (const auto &Idx : SubRegIndices) {
1542 LaneBitmask Mask = Idx.computeLaneMask();
1543 // If some super-registers without CoveredBySubRegs use this index, we can
1544 // no longer assume that the lanes are covering their registers.
1545 if (!Idx.AllSuperRegsCovered)
1546 CoveringLanes &= ~Mask;
1547 }
1548
1549 // Compute lane mask combinations for register classes.
1550 for (auto &RegClass : RegClasses) {
1551 LaneBitmask LaneMask;
1552 for (const auto &SubRegIndex : SubRegIndices) {
1553 if (RegClass.getSubClassWithSubReg(&SubRegIndex) == nullptr)
1554 continue;
1555 LaneMask |= SubRegIndex.LaneMask;
1556 }
1557
1558 // For classes without any subregisters set LaneMask to 1 instead of 0.
1559 // This makes it easier for client code to handle classes uniformly.
1560 if (LaneMask.none())
1561 LaneMask = LaneBitmask::getLane(0);
1562
1563 RegClass.LaneMask = LaneMask;
1564 }
1565}
1566
1567namespace {
1568
1569// UberRegSet is a helper class for computeRegUnitWeights. Each UberRegSet is
1570// the transitive closure of the union of overlapping register
1571// classes. Together, the UberRegSets form a partition of the registers. If we
1572// consider overlapping register classes to be connected, then each UberRegSet
1573// is a set of connected components.
1574//
1575// An UberRegSet will likely be a horizontal slice of register names of
1576// the same width. Nontrivial subregisters should then be in a separate
1577// UberRegSet. But this property isn't required for valid computation of
1578// register unit weights.
1579//
1580// A Weight field caches the max per-register unit weight in each UberRegSet.
1581//
1582// A set of SingularDeterminants flags single units of some register in this set
1583// for which the unit weight equals the set weight. These units should not have
1584// their weight increased.
1585struct UberRegSet {
1586 CodeGenRegister::Vec Regs;
1587 unsigned Weight = 0;
1588 CodeGenRegister::RegUnitList SingularDeterminants;
1589
1590 UberRegSet() = default;
1591};
1592
1593} // end anonymous namespace
1594
1595// Partition registers into UberRegSets, where each set is the transitive
1596// closure of the union of overlapping register classes.
1597//
1598// UberRegSets[0] is a special non-allocatable set.
1599static void computeUberSets(std::vector<UberRegSet> &UberSets,
1600 std::vector<UberRegSet*> &RegSets,
1601 CodeGenRegBank &RegBank) {
1602 const auto &Registers = RegBank.getRegisters();
1603
1604 // The Register EnumValue is one greater than its index into Registers.
1605 assert(Registers.size() == Registers.back().EnumValue &&((Registers.size() == Registers.back().EnumValue && "register enum value mismatch"
) ? static_cast<void> (0) : __assert_fail ("Registers.size() == Registers.back().EnumValue && \"register enum value mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1606, __PRETTY_FUNCTION__))
1606 "register enum value mismatch")((Registers.size() == Registers.back().EnumValue && "register enum value mismatch"
) ? static_cast<void> (0) : __assert_fail ("Registers.size() == Registers.back().EnumValue && \"register enum value mismatch\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1606, __PRETTY_FUNCTION__))
;
1607
1608 // For simplicitly make the SetID the same as EnumValue.
1609 IntEqClasses UberSetIDs(Registers.size()+1);
1610 std::set<unsigned> AllocatableRegs;
1611 for (auto &RegClass : RegBank.getRegClasses()) {
1612 if (!RegClass.Allocatable)
1613 continue;
1614
1615 const CodeGenRegister::Vec &Regs = RegClass.getMembers();
1616 if (Regs.empty())
1617 continue;
1618
1619 unsigned USetID = UberSetIDs.findLeader((*Regs.begin())->EnumValue);
1620 assert(USetID && "register number 0 is invalid")((USetID && "register number 0 is invalid") ? static_cast
<void> (0) : __assert_fail ("USetID && \"register number 0 is invalid\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1620, __PRETTY_FUNCTION__))
;
1621
1622 AllocatableRegs.insert((*Regs.begin())->EnumValue);
1623 for (auto I = std::next(Regs.begin()), E = Regs.end(); I != E; ++I) {
1624 AllocatableRegs.insert((*I)->EnumValue);
1625 UberSetIDs.join(USetID, (*I)->EnumValue);
1626 }
1627 }
1628 // Combine non-allocatable regs.
1629 for (const auto &Reg : Registers) {
1630 unsigned RegNum = Reg.EnumValue;
1631 if (AllocatableRegs.count(RegNum))
1632 continue;
1633
1634 UberSetIDs.join(0, RegNum);
1635 }
1636 UberSetIDs.compress();
1637
1638 // Make the first UberSet a special unallocatable set.
1639 unsigned ZeroID = UberSetIDs[0];
1640
1641 // Insert Registers into the UberSets formed by union-find.
1642 // Do not resize after this.
1643 UberSets.resize(UberSetIDs.getNumClasses());
1644 unsigned i = 0;
1645 for (const CodeGenRegister &Reg : Registers) {
1646 unsigned USetID = UberSetIDs[Reg.EnumValue];
1647 if (!USetID)
1648 USetID = ZeroID;
1649 else if (USetID == ZeroID)
1650 USetID = 0;
1651
1652 UberRegSet *USet = &UberSets[USetID];
1653 USet->Regs.push_back(&Reg);
1654 sortAndUniqueRegisters(USet->Regs);
1655 RegSets[i++] = USet;
1656 }
1657}
1658
1659// Recompute each UberSet weight after changing unit weights.
1660static void computeUberWeights(std::vector<UberRegSet> &UberSets,
1661 CodeGenRegBank &RegBank) {
1662 // Skip the first unallocatable set.
1663 for (std::vector<UberRegSet>::iterator I = std::next(UberSets.begin()),
1664 E = UberSets.end(); I != E; ++I) {
1665
1666 // Initialize all unit weights in this set, and remember the max units/reg.
1667 const CodeGenRegister *Reg = nullptr;
1668 unsigned MaxWeight = 0, Weight = 0;
1669 for (RegUnitIterator UnitI(I->Regs); UnitI.isValid(); ++UnitI) {
1670 if (Reg != UnitI.getReg()) {
1671 if (Weight > MaxWeight)
1672 MaxWeight = Weight;
1673 Reg = UnitI.getReg();
1674 Weight = 0;
1675 }
1676 if (!RegBank.getRegUnit(*UnitI).Artificial) {
1677 unsigned UWeight = RegBank.getRegUnit(*UnitI).Weight;
1678 if (!UWeight) {
1679 UWeight = 1;
1680 RegBank.increaseRegUnitWeight(*UnitI, UWeight);
1681 }
1682 Weight += UWeight;
1683 }
1684 }
1685 if (Weight > MaxWeight)
1686 MaxWeight = Weight;
1687 if (I->Weight != MaxWeight) {
1688 LLVM_DEBUG(dbgs() << "UberSet " << I - UberSets.begin() << " Weight "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
1689 << MaxWeight;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
1690 for (auto &Unitdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
1691 : I->Regs) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
1692 << " " << Unit->getName();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
1693 dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UberSet " << I
- UberSets.begin() << " Weight " << MaxWeight; for
(auto &Unit : I->Regs) dbgs() << " " << Unit
->getName(); dbgs() << "\n"; } } while (false)
;
1694 // Update the set weight.
1695 I->Weight = MaxWeight;
1696 }
1697
1698 // Find singular determinants.
1699 for (const auto R : I->Regs) {
1700 if (R->getRegUnits().count() == 1 && R->getWeight(RegBank) == I->Weight) {
1701 I->SingularDeterminants |= R->getRegUnits();
1702 }
1703 }
1704 }
1705}
1706
1707// normalizeWeight is a computeRegUnitWeights helper that adjusts the weight of
1708// a register and its subregisters so that they have the same weight as their
1709// UberSet. Self-recursion processes the subregister tree in postorder so
1710// subregisters are normalized first.
1711//
1712// Side effects:
1713// - creates new adopted register units
1714// - causes superregisters to inherit adopted units
1715// - increases the weight of "singular" units
1716// - induces recomputation of UberWeights.
1717static bool normalizeWeight(CodeGenRegister *Reg,
1718 std::vector<UberRegSet> &UberSets,
1719 std::vector<UberRegSet*> &RegSets,
1720 BitVector &NormalRegs,
1721 CodeGenRegister::RegUnitList &NormalUnits,
1722 CodeGenRegBank &RegBank) {
1723 NormalRegs.resize(std::max(Reg->EnumValue + 1, NormalRegs.size()));
1724 if (NormalRegs.test(Reg->EnumValue))
1725 return false;
1726 NormalRegs.set(Reg->EnumValue);
1727
1728 bool Changed = false;
1729 const CodeGenRegister::SubRegMap &SRM = Reg->getSubRegs();
1730 for (CodeGenRegister::SubRegMap::const_iterator SRI = SRM.begin(),
1731 SRE = SRM.end(); SRI != SRE; ++SRI) {
1732 if (SRI->second == Reg)
1733 continue; // self-cycles happen
1734
1735 Changed |= normalizeWeight(SRI->second, UberSets, RegSets,
1736 NormalRegs, NormalUnits, RegBank);
1737 }
1738 // Postorder register normalization.
1739
1740 // Inherit register units newly adopted by subregisters.
1741 if (Reg->inheritRegUnits(RegBank))
1742 computeUberWeights(UberSets, RegBank);
1743
1744 // Check if this register is too skinny for its UberRegSet.
1745 UberRegSet *UberSet = RegSets[RegBank.getRegIndex(Reg)];
1746
1747 unsigned RegWeight = Reg->getWeight(RegBank);
1748 if (UberSet->Weight > RegWeight) {
1749 // A register unit's weight can be adjusted only if it is the singular unit
1750 // for this register, has not been used to normalize a subregister's set,
1751 // and has not already been used to singularly determine this UberRegSet.
1752 unsigned AdjustUnit = *Reg->getRegUnits().begin();
1753 if (Reg->getRegUnits().count() != 1
1754 || hasRegUnit(NormalUnits, AdjustUnit)
1755 || hasRegUnit(UberSet->SingularDeterminants, AdjustUnit)) {
1756 // We don't have an adjustable unit, so adopt a new one.
1757 AdjustUnit = RegBank.newRegUnit(UberSet->Weight - RegWeight);
1758 Reg->adoptRegUnit(AdjustUnit);
1759 // Adopting a unit does not immediately require recomputing set weights.
1760 }
1761 else {
1762 // Adjust the existing single unit.
1763 if (!RegBank.getRegUnit(AdjustUnit).Artificial)
1764 RegBank.increaseRegUnitWeight(AdjustUnit, UberSet->Weight - RegWeight);
1765 // The unit may be shared among sets and registers within this set.
1766 computeUberWeights(UberSets, RegBank);
1767 }
1768 Changed = true;
1769 }
1770
1771 // Mark these units normalized so superregisters can't change their weights.
1772 NormalUnits |= Reg->getRegUnits();
1773
1774 return Changed;
1775}
1776
1777// Compute a weight for each register unit created during getSubRegs.
1778//
1779// The goal is that two registers in the same class will have the same weight,
1780// where each register's weight is defined as sum of its units' weights.
1781void CodeGenRegBank::computeRegUnitWeights() {
1782 std::vector<UberRegSet> UberSets;
1783 std::vector<UberRegSet*> RegSets(Registers.size());
1784 computeUberSets(UberSets, RegSets, *this);
1785 // UberSets and RegSets are now immutable.
1786
1787 computeUberWeights(UberSets, *this);
1788
1789 // Iterate over each Register, normalizing the unit weights until reaching
1790 // a fix point.
1791 unsigned NumIters = 0;
1792 for (bool Changed = true; Changed; ++NumIters) {
1793 assert(NumIters <= NumNativeRegUnits && "Runaway register unit weights")((NumIters <= NumNativeRegUnits && "Runaway register unit weights"
) ? static_cast<void> (0) : __assert_fail ("NumIters <= NumNativeRegUnits && \"Runaway register unit weights\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1793, __PRETTY_FUNCTION__))
;
1794 Changed = false;
1795 for (auto &Reg : Registers) {
1796 CodeGenRegister::RegUnitList NormalUnits;
1797 BitVector NormalRegs;
1798 Changed |= normalizeWeight(&Reg, UberSets, RegSets, NormalRegs,
1799 NormalUnits, *this);
1800 }
1801 }
1802}
1803
1804// Find a set in UniqueSets with the same elements as Set.
1805// Return an iterator into UniqueSets.
1806static std::vector<RegUnitSet>::const_iterator
1807findRegUnitSet(const std::vector<RegUnitSet> &UniqueSets,
1808 const RegUnitSet &Set) {
1809 std::vector<RegUnitSet>::const_iterator
1810 I = UniqueSets.begin(), E = UniqueSets.end();
1811 for(;I != E; ++I) {
1812 if (I->Units == Set.Units)
1813 break;
1814 }
1815 return I;
1816}
1817
1818// Return true if the RUSubSet is a subset of RUSuperSet.
1819static bool isRegUnitSubSet(const std::vector<unsigned> &RUSubSet,
1820 const std::vector<unsigned> &RUSuperSet) {
1821 return std::includes(RUSuperSet.begin(), RUSuperSet.end(),
1822 RUSubSet.begin(), RUSubSet.end());
1823}
1824
1825/// Iteratively prune unit sets. Prune subsets that are close to the superset,
1826/// but with one or two registers removed. We occasionally have registers like
1827/// APSR and PC thrown in with the general registers. We also see many
1828/// special-purpose register subsets, such as tail-call and Thumb
1829/// encodings. Generating all possible overlapping sets is combinatorial and
1830/// overkill for modeling pressure. Ideally we could fix this statically in
1831/// tablegen by (1) having the target define register classes that only include
1832/// the allocatable registers and marking other classes as non-allocatable and
1833/// (2) having a way to mark special purpose classes as "don't-care" classes for
1834/// the purpose of pressure. However, we make an attempt to handle targets that
1835/// are not nicely defined by merging nearly identical register unit sets
1836/// statically. This generates smaller tables. Then, dynamically, we adjust the
1837/// set limit by filtering the reserved registers.
1838///
1839/// Merge sets only if the units have the same weight. For example, on ARM,
1840/// Q-tuples with ssub index 0 include all S regs but also include D16+. We
1841/// should not expand the S set to include D regs.
1842void CodeGenRegBank::pruneUnitSets() {
1843 assert(RegClassUnitSets.empty() && "this invalidates RegClassUnitSets")((RegClassUnitSets.empty() && "this invalidates RegClassUnitSets"
) ? static_cast<void> (0) : __assert_fail ("RegClassUnitSets.empty() && \"this invalidates RegClassUnitSets\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1843, __PRETTY_FUNCTION__))
;
1844
1845 // Form an equivalence class of UnitSets with no significant difference.
1846 std::vector<unsigned> SuperSetIDs;
1847 for (unsigned SubIdx = 0, EndIdx = RegUnitSets.size();
1848 SubIdx != EndIdx; ++SubIdx) {
1849 const RegUnitSet &SubSet = RegUnitSets[SubIdx];
1850 unsigned SuperIdx = 0;
1851 for (; SuperIdx != EndIdx; ++SuperIdx) {
1852 if (SuperIdx == SubIdx)
1853 continue;
1854
1855 unsigned UnitWeight = RegUnits[SubSet.Units[0]].Weight;
1856 const RegUnitSet &SuperSet = RegUnitSets[SuperIdx];
1857 if (isRegUnitSubSet(SubSet.Units, SuperSet.Units)
1858 && (SubSet.Units.size() + 3 > SuperSet.Units.size())
1859 && UnitWeight == RegUnits[SuperSet.Units[0]].Weight
1860 && UnitWeight == RegUnits[SuperSet.Units.back()].Weight) {
1861 LLVM_DEBUG(dbgs() << "UnitSet " << SubIdx << " subsumed by " << SuperIdxdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << SubIdx
<< " subsumed by " << SuperIdx << "\n"; } }
while (false)
1862 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << SubIdx
<< " subsumed by " << SuperIdx << "\n"; } }
while (false)
;
1863 // We can pick any of the set names for the merged set. Go for the
1864 // shortest one to avoid picking the name of one of the classes that are
1865 // artificially created by tablegen. So "FPR128_lo" instead of
1866 // "QQQQ_with_qsub3_in_FPR128_lo".
1867 if (RegUnitSets[SubIdx].Name.size() < RegUnitSets[SuperIdx].Name.size())
1868 RegUnitSets[SuperIdx].Name = RegUnitSets[SubIdx].Name;
1869 break;
1870 }
1871 }
1872 if (SuperIdx == EndIdx)
1873 SuperSetIDs.push_back(SubIdx);
1874 }
1875 // Populate PrunedUnitSets with each equivalence class's superset.
1876 std::vector<RegUnitSet> PrunedUnitSets(SuperSetIDs.size());
1877 for (unsigned i = 0, e = SuperSetIDs.size(); i != e; ++i) {
1878 unsigned SuperIdx = SuperSetIDs[i];
1879 PrunedUnitSets[i].Name = RegUnitSets[SuperIdx].Name;
1880 PrunedUnitSets[i].Units.swap(RegUnitSets[SuperIdx].Units);
1881 }
1882 RegUnitSets.swap(PrunedUnitSets);
1883}
1884
1885// Create a RegUnitSet for each RegClass that contains all units in the class
1886// including adopted units that are necessary to model register pressure. Then
1887// iteratively compute RegUnitSets such that the union of any two overlapping
1888// RegUnitSets is repreresented.
1889//
1890// RegisterInfoEmitter will map each RegClass to its RegUnitClass and any
1891// RegUnitSet that is a superset of that RegUnitClass.
1892void CodeGenRegBank::computeRegUnitSets() {
1893 assert(RegUnitSets.empty() && "dirty RegUnitSets")((RegUnitSets.empty() && "dirty RegUnitSets") ? static_cast
<void> (0) : __assert_fail ("RegUnitSets.empty() && \"dirty RegUnitSets\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1893, __PRETTY_FUNCTION__))
;
1894
1895 // Compute a unique RegUnitSet for each RegClass.
1896 auto &RegClasses = getRegClasses();
1897 for (auto &RC : RegClasses) {
1898 if (!RC.Allocatable || RC.Artificial || !RC.GeneratePressureSet)
1899 continue;
1900
1901 // Speculatively grow the RegUnitSets to hold the new set.
1902 RegUnitSets.resize(RegUnitSets.size() + 1);
1903 RegUnitSets.back().Name = RC.getName();
1904
1905 // Compute a sorted list of units in this class.
1906 RC.buildRegUnitSet(*this, RegUnitSets.back().Units);
1907
1908 // Find an existing RegUnitSet.
1909 std::vector<RegUnitSet>::const_iterator SetI =
1910 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1911 if (SetI != std::prev(RegUnitSets.end()))
1912 RegUnitSets.pop_back();
1913 }
1914
1915 LLVM_DEBUG(dbgs() << "\nBefore pruning:\n"; for (unsigned USIdx = 0,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1916 USEnd = RegUnitSets.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1917 USIdx < USEnd; ++USIdx) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1918 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1919 for (auto &U : RegUnitSets[USIdx].Units)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1920 printRegUnitName(U);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1921 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
1922 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore pruning:\n"
; for (unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx <
USEnd; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; }; } } while (false)
;
1923
1924 // Iteratively prune unit sets.
1925 pruneUnitSets();
1926
1927 LLVM_DEBUG(dbgs() << "\nBefore union:\n"; for (unsigned USIdx = 0,do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1928 USEnd = RegUnitSets.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1929 USIdx < USEnd; ++USIdx) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1930 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1931 for (auto &U : RegUnitSets[USIdx].Units)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1932 printRegUnitName(U);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1933 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
1934 } dbgs() << "\nUnion sets:\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\nBefore union:\n"; for
(unsigned USIdx = 0, USEnd = RegUnitSets.size(); USIdx < USEnd
; ++USIdx) { dbgs() << "UnitSet " << USIdx <<
" " << RegUnitSets[USIdx].Name << ":"; for (auto
&U : RegUnitSets[USIdx].Units) printRegUnitName(U); dbgs
() << "\n"; } dbgs() << "\nUnion sets:\n"; } } while
(false)
;
1935
1936 // Iterate over all unit sets, including new ones added by this loop.
1937 unsigned NumRegUnitSubSets = RegUnitSets.size();
1938 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
1939 // In theory, this is combinatorial. In practice, it needs to be bounded
1940 // by a small number of sets for regpressure to be efficient.
1941 // If the assert is hit, we need to implement pruning.
1942 assert(Idx < (2*NumRegUnitSubSets) && "runaway unit set inference")((Idx < (2*NumRegUnitSubSets) && "runaway unit set inference"
) ? static_cast<void> (0) : __assert_fail ("Idx < (2*NumRegUnitSubSets) && \"runaway unit set inference\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 1942, __PRETTY_FUNCTION__))
;
1943
1944 // Compare new sets with all original classes.
1945 for (unsigned SearchIdx = (Idx >= NumRegUnitSubSets) ? 0 : Idx+1;
1946 SearchIdx != EndIdx; ++SearchIdx) {
1947 std::set<unsigned> Intersection;
1948 std::set_intersection(RegUnitSets[Idx].Units.begin(),
1949 RegUnitSets[Idx].Units.end(),
1950 RegUnitSets[SearchIdx].Units.begin(),
1951 RegUnitSets[SearchIdx].Units.end(),
1952 std::inserter(Intersection, Intersection.begin()));
1953 if (Intersection.empty())
1954 continue;
1955
1956 // Speculatively grow the RegUnitSets to hold the new set.
1957 RegUnitSets.resize(RegUnitSets.size() + 1);
1958 RegUnitSets.back().Name =
1959 RegUnitSets[Idx].Name + "_with_" + RegUnitSets[SearchIdx].Name;
1960
1961 std::set_union(RegUnitSets[Idx].Units.begin(),
1962 RegUnitSets[Idx].Units.end(),
1963 RegUnitSets[SearchIdx].Units.begin(),
1964 RegUnitSets[SearchIdx].Units.end(),
1965 std::inserter(RegUnitSets.back().Units,
1966 RegUnitSets.back().Units.begin()));
1967
1968 // Find an existing RegUnitSet, or add the union to the unique sets.
1969 std::vector<RegUnitSet>::const_iterator SetI =
1970 findRegUnitSet(RegUnitSets, RegUnitSets.back());
1971 if (SetI != std::prev(RegUnitSets.end()))
1972 RegUnitSets.pop_back();
1973 else {
1974 LLVM_DEBUG(dbgs() << "UnitSet " << RegUnitSets.size() - 1 << " "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << RegUnitSets
.size() - 1 << " " << RegUnitSets.back().Name <<
":"; for (auto &U : RegUnitSets.back().Units) printRegUnitName
(U); dbgs() << "\n";; } } while (false)
1975 << RegUnitSets.back().Name << ":";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << RegUnitSets
.size() - 1 << " " << RegUnitSets.back().Name <<
":"; for (auto &U : RegUnitSets.back().Units) printRegUnitName
(U); dbgs() << "\n";; } } while (false)
1976 for (auto &Udo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << RegUnitSets
.size() - 1 << " " << RegUnitSets.back().Name <<
":"; for (auto &U : RegUnitSets.back().Units) printRegUnitName
(U); dbgs() << "\n";; } } while (false)
1977 : RegUnitSets.back().Units) printRegUnitName(U);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << RegUnitSets
.size() - 1 << " " << RegUnitSets.back().Name <<
":"; for (auto &U : RegUnitSets.back().Units) printRegUnitName
(U); dbgs() << "\n";; } } while (false)
1978 dbgs() << "\n";)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "UnitSet " << RegUnitSets
.size() - 1 << " " << RegUnitSets.back().Name <<
":"; for (auto &U : RegUnitSets.back().Units) printRegUnitName
(U); dbgs() << "\n";; } } while (false)
;
1979 }
1980 }
1981 }
1982
1983 // Iteratively prune unit sets after inferring supersets.
1984 pruneUnitSets();
1985
1986 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1987 dbgs() << "\n"; for (unsigned USIdx = 0, USEnd = RegUnitSets.size();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1988 USIdx < USEnd; ++USIdx) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1989 dbgs() << "UnitSet " << USIdx << " " << RegUnitSets[USIdx].Name << ":";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1990 for (auto &U : RegUnitSets[USIdx].Units)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1991 printRegUnitName(U);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1992 dbgs() << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
1993 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; for (unsigned USIdx
= 0, USEnd = RegUnitSets.size(); USIdx < USEnd; ++USIdx) {
dbgs() << "UnitSet " << USIdx << " " <<
RegUnitSets[USIdx].Name << ":"; for (auto &U : RegUnitSets
[USIdx].Units) printRegUnitName(U); dbgs() << "\n"; }; }
} while (false)
;
1994
1995 // For each register class, list the UnitSets that are supersets.
1996 RegClassUnitSets.resize(RegClasses.size());
1997 int RCIdx = -1;
1998 for (auto &RC : RegClasses) {
1999 ++RCIdx;
2000 if (!RC.Allocatable)
2001 continue;
2002
2003 // Recompute the sorted list of units in this class.
2004 std::vector<unsigned> RCRegUnits;
2005 RC.buildRegUnitSet(*this, RCRegUnits);
2006
2007 // Don't increase pressure for unallocatable regclasses.
2008 if (RCRegUnits.empty())
2009 continue;
2010
2011 LLVM_DEBUG(dbgs() << "RC " << RC.getName() << " Units: \n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "RC " << RC.getName
() << " Units: \n"; for (auto U : RCRegUnits) printRegUnitName
(U); dbgs() << "\n UnitSetIDs:"; } } while (false)
2012 for (auto Udo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "RC " << RC.getName
() << " Units: \n"; for (auto U : RCRegUnits) printRegUnitName
(U); dbgs() << "\n UnitSetIDs:"; } } while (false)
2013 : RCRegUnits) printRegUnitName(U);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "RC " << RC.getName
() << " Units: \n"; for (auto U : RCRegUnits) printRegUnitName
(U); dbgs() << "\n UnitSetIDs:"; } } while (false)
2014 dbgs() << "\n UnitSetIDs:")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "RC " << RC.getName
() << " Units: \n"; for (auto U : RCRegUnits) printRegUnitName
(U); dbgs() << "\n UnitSetIDs:"; } } while (false)
;
2015
2016 // Find all supersets.
2017 for (unsigned USIdx = 0, USEnd = RegUnitSets.size();
2018 USIdx != USEnd; ++USIdx) {
2019 if (isRegUnitSubSet(RCRegUnits, RegUnitSets[USIdx].Units)) {
2020 LLVM_DEBUG(dbgs() << " " << USIdx)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << " " << USIdx; }
} while (false)
;
2021 RegClassUnitSets[RCIdx].push_back(USIdx);
2022 }
2023 }
2024 LLVM_DEBUG(dbgs() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("regalloc-emitter")) { dbgs() << "\n"; } } while (false
)
;
2025 assert(!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass")((!RegClassUnitSets[RCIdx].empty() && "missing unit set for regclass"
) ? static_cast<void> (0) : __assert_fail ("!RegClassUnitSets[RCIdx].empty() && \"missing unit set for regclass\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2025, __PRETTY_FUNCTION__))
;
2026 }
2027
2028 // For each register unit, ensure that we have the list of UnitSets that
2029 // contain the unit. Normally, this matches an existing list of UnitSets for a
2030 // register class. If not, we create a new entry in RegClassUnitSets as a
2031 // "fake" register class.
2032 for (unsigned UnitIdx = 0, UnitEnd = NumNativeRegUnits;
2033 UnitIdx < UnitEnd; ++UnitIdx) {
2034 std::vector<unsigned> RUSets;
2035 for (unsigned i = 0, e = RegUnitSets.size(); i != e; ++i) {
2036 RegUnitSet &RUSet = RegUnitSets[i];
2037 if (!is_contained(RUSet.Units, UnitIdx))
2038 continue;
2039 RUSets.push_back(i);
2040 }
2041 unsigned RCUnitSetsIdx = 0;
2042 for (unsigned e = RegClassUnitSets.size();
2043 RCUnitSetsIdx != e; ++RCUnitSetsIdx) {
2044 if (RegClassUnitSets[RCUnitSetsIdx] == RUSets) {
2045 break;
2046 }
2047 }
2048 RegUnits[UnitIdx].RegClassUnitSetsIdx = RCUnitSetsIdx;
2049 if (RCUnitSetsIdx == RegClassUnitSets.size()) {
2050 // Create a new list of UnitSets as a "fake" register class.
2051 RegClassUnitSets.resize(RCUnitSetsIdx + 1);
2052 RegClassUnitSets[RCUnitSetsIdx].swap(RUSets);
2053 }
2054 }
2055}
2056
2057void CodeGenRegBank::computeRegUnitLaneMasks() {
2058 for (auto &Register : Registers) {
2059 // Create an initial lane mask for all register units.
2060 const auto &RegUnits = Register.getRegUnits();
2061 CodeGenRegister::RegUnitLaneMaskList
2062 RegUnitLaneMasks(RegUnits.count(), LaneBitmask::getNone());
2063 // Iterate through SubRegisters.
2064 typedef CodeGenRegister::SubRegMap SubRegMap;
2065 const SubRegMap &SubRegs = Register.getSubRegs();
2066 for (SubRegMap::const_iterator S = SubRegs.begin(),
2067 SE = SubRegs.end(); S != SE; ++S) {
2068 CodeGenRegister *SubReg = S->second;
2069 // Ignore non-leaf subregisters, their lane masks are fully covered by
2070 // the leaf subregisters anyway.
2071 if (!SubReg->getSubRegs().empty())
2072 continue;
2073 CodeGenSubRegIndex *SubRegIndex = S->first;
2074 const CodeGenRegister *SubRegister = S->second;
2075 LaneBitmask LaneMask = SubRegIndex->LaneMask;
2076 // Distribute LaneMask to Register Units touched.
2077 for (unsigned SUI : SubRegister->getRegUnits()) {
2078 bool Found = false;
2079 unsigned u = 0;
2080 for (unsigned RU : RegUnits) {
2081 if (SUI == RU) {
2082 RegUnitLaneMasks[u] |= LaneMask;
2083 assert(!Found)((!Found) ? static_cast<void> (0) : __assert_fail ("!Found"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2083, __PRETTY_FUNCTION__))
;
2084 Found = true;
2085 }
2086 ++u;
2087 }
2088 (void)Found;
2089 assert(Found)((Found) ? static_cast<void> (0) : __assert_fail ("Found"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2089, __PRETTY_FUNCTION__))
;
2090 }
2091 }
2092 Register.setRegUnitLaneMasks(RegUnitLaneMasks);
2093 }
2094}
2095
2096void CodeGenRegBank::computeDerivedInfo() {
2097 computeComposites();
2098 computeSubRegLaneMasks();
1
Calling 'CodeGenRegBank::computeSubRegLaneMasks'
2099
2100 // Compute a weight for each register unit created during getSubRegs.
2101 // This may create adopted register units (with unit # >= NumNativeRegUnits).
2102 computeRegUnitWeights();
2103
2104 // Compute a unique set of RegUnitSets. One for each RegClass and inferred
2105 // supersets for the union of overlapping sets.
2106 computeRegUnitSets();
2107
2108 computeRegUnitLaneMasks();
2109
2110 // Compute register class HasDisjunctSubRegs/CoveredBySubRegs flag.
2111 for (CodeGenRegisterClass &RC : RegClasses) {
2112 RC.HasDisjunctSubRegs = false;
2113 RC.CoveredBySubRegs = true;
2114 for (const CodeGenRegister *Reg : RC.getMembers()) {
2115 RC.HasDisjunctSubRegs |= Reg->HasDisjunctSubRegs;
2116 RC.CoveredBySubRegs &= Reg->CoveredBySubRegs;
2117 }
2118 }
2119
2120 // Get the weight of each set.
2121 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2122 RegUnitSets[Idx].Weight = getRegUnitSetWeight(RegUnitSets[Idx].Units);
2123
2124 // Find the order of each set.
2125 RegUnitSetOrder.reserve(RegUnitSets.size());
2126 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx)
2127 RegUnitSetOrder.push_back(Idx);
2128
2129 llvm::stable_sort(RegUnitSetOrder, [this](unsigned ID1, unsigned ID2) {
2130 return getRegPressureSet(ID1).Units.size() <
2131 getRegPressureSet(ID2).Units.size();
2132 });
2133 for (unsigned Idx = 0, EndIdx = RegUnitSets.size(); Idx != EndIdx; ++Idx) {
2134 RegUnitSets[RegUnitSetOrder[Idx]].Order = Idx;
2135 }
2136}
2137
2138//
2139// Synthesize missing register class intersections.
2140//
2141// Make sure that sub-classes of RC exists such that getCommonSubClass(RC, X)
2142// returns a maximal register class for all X.
2143//
2144void CodeGenRegBank::inferCommonSubClass(CodeGenRegisterClass *RC) {
2145 assert(!RegClasses.empty())((!RegClasses.empty()) ? static_cast<void> (0) : __assert_fail
("!RegClasses.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2145, __PRETTY_FUNCTION__))
;
2146 // Stash the iterator to the last element so that this loop doesn't visit
2147 // elements added by the getOrCreateSubClass call within it.
2148 for (auto I = RegClasses.begin(), E = std::prev(RegClasses.end());
2149 I != std::next(E); ++I) {
2150 CodeGenRegisterClass *RC1 = RC;
2151 CodeGenRegisterClass *RC2 = &*I;
2152 if (RC1 == RC2)
2153 continue;
2154
2155 // Compute the set intersection of RC1 and RC2.
2156 const CodeGenRegister::Vec &Memb1 = RC1->getMembers();
2157 const CodeGenRegister::Vec &Memb2 = RC2->getMembers();
2158 CodeGenRegister::Vec Intersection;
2159 std::set_intersection(Memb1.begin(), Memb1.end(), Memb2.begin(),
2160 Memb2.end(),
2161 std::inserter(Intersection, Intersection.begin()),
2162 deref<std::less<>>());
2163
2164 // Skip disjoint class pairs.
2165 if (Intersection.empty())
2166 continue;
2167
2168 // If RC1 and RC2 have different spill sizes or alignments, use the
2169 // stricter one for sub-classing. If they are equal, prefer RC1.
2170 if (RC2->RSI.hasStricterSpillThan(RC1->RSI))
2171 std::swap(RC1, RC2);
2172
2173 getOrCreateSubClass(RC1, &Intersection,
2174 RC1->getName() + "_and_" + RC2->getName());
2175 }
2176}
2177
2178//
2179// Synthesize missing sub-classes for getSubClassWithSubReg().
2180//
2181// Make sure that the set of registers in RC with a given SubIdx sub-register
2182// form a register class. Update RC->SubClassWithSubReg.
2183//
2184void CodeGenRegBank::inferSubClassWithSubReg(CodeGenRegisterClass *RC) {
2185 // Map SubRegIndex to set of registers in RC supporting that SubRegIndex.
2186 typedef std::map<const CodeGenSubRegIndex *, CodeGenRegister::Vec,
2187 deref<std::less<>>>
2188 SubReg2SetMap;
2189
2190 // Compute the set of registers supporting each SubRegIndex.
2191 SubReg2SetMap SRSets;
2192 for (const auto R : RC->getMembers()) {
2193 if (R->Artificial)
2194 continue;
2195 const CodeGenRegister::SubRegMap &SRM = R->getSubRegs();
2196 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2197 E = SRM.end(); I != E; ++I) {
2198 if (!I->first->Artificial)
2199 SRSets[I->first].push_back(R);
2200 }
2201 }
2202
2203 for (auto I : SRSets)
2204 sortAndUniqueRegisters(I.second);
2205
2206 // Find matching classes for all SRSets entries. Iterate in SubRegIndex
2207 // numerical order to visit synthetic indices last.
2208 for (const auto &SubIdx : SubRegIndices) {
2209 if (SubIdx.Artificial)
2210 continue;
2211 SubReg2SetMap::const_iterator I = SRSets.find(&SubIdx);
2212 // Unsupported SubRegIndex. Skip it.
2213 if (I == SRSets.end())
2214 continue;
2215 // In most cases, all RC registers support the SubRegIndex.
2216 if (I->second.size() == RC->getMembers().size()) {
2217 RC->setSubClassWithSubReg(&SubIdx, RC);
2218 continue;
2219 }
2220 // This is a real subset. See if we have a matching class.
2221 CodeGenRegisterClass *SubRC =
2222 getOrCreateSubClass(RC, &I->second,
2223 RC->getName() + "_with_" + I->first->getName());
2224 RC->setSubClassWithSubReg(&SubIdx, SubRC);
2225 }
2226}
2227
2228//
2229// Synthesize missing sub-classes of RC for getMatchingSuperRegClass().
2230//
2231// Create sub-classes of RC such that getMatchingSuperRegClass(RC, SubIdx, X)
2232// has a maximal result for any SubIdx and any X >= FirstSubRegRC.
2233//
2234
2235void CodeGenRegBank::inferMatchingSuperRegClass(CodeGenRegisterClass *RC,
2236 std::list<CodeGenRegisterClass>::iterator FirstSubRegRC) {
2237 SmallVector<std::pair<const CodeGenRegister*,
2238 const CodeGenRegister*>, 16> SSPairs;
2239 BitVector TopoSigs(getNumTopoSigs());
2240
2241 // Iterate in SubRegIndex numerical order to visit synthetic indices last.
2242 for (auto &SubIdx : SubRegIndices) {
2243 // Skip indexes that aren't fully supported by RC's registers. This was
2244 // computed by inferSubClassWithSubReg() above which should have been
2245 // called first.
2246 if (RC->getSubClassWithSubReg(&SubIdx) != RC)
2247 continue;
2248
2249 // Build list of (Super, Sub) pairs for this SubIdx.
2250 SSPairs.clear();
2251 TopoSigs.reset();
2252 for (const auto Super : RC->getMembers()) {
2253 const CodeGenRegister *Sub = Super->getSubRegs().find(&SubIdx)->second;
2254 assert(Sub && "Missing sub-register")((Sub && "Missing sub-register") ? static_cast<void
> (0) : __assert_fail ("Sub && \"Missing sub-register\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2254, __PRETTY_FUNCTION__))
;
2255 SSPairs.push_back(std::make_pair(Super, Sub));
2256 TopoSigs.set(Sub->getTopoSig());
2257 }
2258
2259 // Iterate over sub-register class candidates. Ignore classes created by
2260 // this loop. They will never be useful.
2261 // Store an iterator to the last element (not end) so that this loop doesn't
2262 // visit newly inserted elements.
2263 assert(!RegClasses.empty())((!RegClasses.empty()) ? static_cast<void> (0) : __assert_fail
("!RegClasses.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2263, __PRETTY_FUNCTION__))
;
2264 for (auto I = FirstSubRegRC, E = std::prev(RegClasses.end());
2265 I != std::next(E); ++I) {
2266 CodeGenRegisterClass &SubRC = *I;
2267 if (SubRC.Artificial)
2268 continue;
2269 // Topological shortcut: SubRC members have the wrong shape.
2270 if (!TopoSigs.anyCommon(SubRC.getTopoSigs()))
2271 continue;
2272 // Compute the subset of RC that maps into SubRC.
2273 CodeGenRegister::Vec SubSetVec;
2274 for (unsigned i = 0, e = SSPairs.size(); i != e; ++i)
2275 if (SubRC.contains(SSPairs[i].second))
2276 SubSetVec.push_back(SSPairs[i].first);
2277
2278 if (SubSetVec.empty())
2279 continue;
2280
2281 // RC injects completely into SubRC.
2282 sortAndUniqueRegisters(SubSetVec);
2283 if (SubSetVec.size() == SSPairs.size()) {
2284 SubRC.addSuperRegClass(&SubIdx, RC);
2285 continue;
2286 }
2287
2288 // Only a subset of RC maps into SubRC. Make sure it is represented by a
2289 // class.
2290 getOrCreateSubClass(RC, &SubSetVec, RC->getName() + "_with_" +
2291 SubIdx.getName() + "_in_" +
2292 SubRC.getName());
2293 }
2294 }
2295}
2296
2297//
2298// Infer missing register classes.
2299//
2300void CodeGenRegBank::computeInferredRegisterClasses() {
2301 assert(!RegClasses.empty())((!RegClasses.empty()) ? static_cast<void> (0) : __assert_fail
("!RegClasses.empty()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2301, __PRETTY_FUNCTION__))
;
2302 // When this function is called, the register classes have not been sorted
2303 // and assigned EnumValues yet. That means getSubClasses(),
2304 // getSuperClasses(), and hasSubClass() functions are defunct.
2305
2306 // Use one-before-the-end so it doesn't move forward when new elements are
2307 // added.
2308 auto FirstNewRC = std::prev(RegClasses.end());
2309
2310 // Visit all register classes, including the ones being added by the loop.
2311 // Watch out for iterator invalidation here.
2312 for (auto I = RegClasses.begin(), E = RegClasses.end(); I != E; ++I) {
2313 CodeGenRegisterClass *RC = &*I;
2314 if (RC->Artificial)
2315 continue;
2316
2317 // Synthesize answers for getSubClassWithSubReg().
2318 inferSubClassWithSubReg(RC);
2319
2320 // Synthesize answers for getCommonSubClass().
2321 inferCommonSubClass(RC);
2322
2323 // Synthesize answers for getMatchingSuperRegClass().
2324 inferMatchingSuperRegClass(RC);
2325
2326 // New register classes are created while this loop is running, and we need
2327 // to visit all of them. I particular, inferMatchingSuperRegClass needs
2328 // to match old super-register classes with sub-register classes created
2329 // after inferMatchingSuperRegClass was called. At this point,
2330 // inferMatchingSuperRegClass has checked SuperRC = [0..rci] with SubRC =
2331 // [0..FirstNewRC). We need to cover SubRC = [FirstNewRC..rci].
2332 if (I == FirstNewRC) {
2333 auto NextNewRC = std::prev(RegClasses.end());
2334 for (auto I2 = RegClasses.begin(), E2 = std::next(FirstNewRC); I2 != E2;
2335 ++I2)
2336 inferMatchingSuperRegClass(&*I2, E2);
2337 FirstNewRC = NextNewRC;
2338 }
2339 }
2340}
2341
2342/// getRegisterClassForRegister - Find the register class that contains the
2343/// specified physical register. If the register is not in a register class,
2344/// return null. If the register is in multiple classes, and the classes have a
2345/// superset-subset relationship and the same set of types, return the
2346/// superclass. Otherwise return null.
2347const CodeGenRegisterClass*
2348CodeGenRegBank::getRegClassForRegister(Record *R) {
2349 const CodeGenRegister *Reg = getReg(R);
2350 const CodeGenRegisterClass *FoundRC = nullptr;
2351 for (const auto &RC : getRegClasses()) {
2352 if (!RC.contains(Reg))
2353 continue;
2354
2355 // If this is the first class that contains the register,
2356 // make a note of it and go on to the next class.
2357 if (!FoundRC) {
2358 FoundRC = &RC;
2359 continue;
2360 }
2361
2362 // If a register's classes have different types, return null.
2363 if (RC.getValueTypes() != FoundRC->getValueTypes())
2364 return nullptr;
2365
2366 // Check to see if the previously found class that contains
2367 // the register is a subclass of the current class. If so,
2368 // prefer the superclass.
2369 if (RC.hasSubClass(FoundRC)) {
2370 FoundRC = &RC;
2371 continue;
2372 }
2373
2374 // Check to see if the previously found class that contains
2375 // the register is a superclass of the current class. If so,
2376 // prefer the superclass.
2377 if (FoundRC->hasSubClass(&RC))
2378 continue;
2379
2380 // Multiple classes, and neither is a superclass of the other.
2381 // Return null.
2382 return nullptr;
2383 }
2384 return FoundRC;
2385}
2386
2387const CodeGenRegisterClass *
2388CodeGenRegBank::getMinimalPhysRegClass(Record *RegRecord,
2389 ValueTypeByHwMode *VT) {
2390 const CodeGenRegister *Reg = getReg(RegRecord);
2391 const CodeGenRegisterClass *BestRC = nullptr;
2392 for (const auto &RC : getRegClasses()) {
2393 if ((!VT || RC.hasType(*VT)) &&
2394 RC.contains(Reg) && (!BestRC || BestRC->hasSubClass(&RC)))
2395 BestRC = &RC;
2396 }
2397
2398 assert(BestRC && "Couldn't find the register class")((BestRC && "Couldn't find the register class") ? static_cast
<void> (0) : __assert_fail ("BestRC && \"Couldn't find the register class\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/utils/TableGen/CodeGenRegisters.cpp"
, 2398, __PRETTY_FUNCTION__))
;
2399 return BestRC;
2400}
2401
2402BitVector CodeGenRegBank::computeCoveredRegisters(ArrayRef<Record*> Regs) {
2403 SetVector<const CodeGenRegister*> Set;
2404
2405 // First add Regs with all sub-registers.
2406 for (unsigned i = 0, e = Regs.size(); i != e; ++i) {
2407 CodeGenRegister *Reg = getReg(Regs[i]);
2408 if (Set.insert(Reg))
2409 // Reg is new, add all sub-registers.
2410 // The pre-ordering is not important here.
2411 Reg->addSubRegsPreOrder(Set, *this);
2412 }
2413
2414 // Second, find all super-registers that are completely covered by the set.
2415 for (unsigned i = 0; i != Set.size(); ++i) {
2416 const CodeGenRegister::SuperRegList &SR = Set[i]->getSuperRegs();
2417 for (unsigned j = 0, e = SR.size(); j != e; ++j) {
2418 const CodeGenRegister *Super = SR[j];
2419 if (!Super->CoveredBySubRegs || Set.count(Super))
2420 continue;
2421 // This new super-register is covered by its sub-registers.
2422 bool AllSubsInSet = true;
2423 const CodeGenRegister::SubRegMap &SRM = Super->getSubRegs();
2424 for (CodeGenRegister::SubRegMap::const_iterator I = SRM.begin(),
2425 E = SRM.end(); I != E; ++I)
2426 if (!Set.count(I->second)) {
2427 AllSubsInSet = false;
2428 break;
2429 }
2430 // All sub-registers in Set, add Super as well.
2431 // We will visit Super later to recheck its super-registers.
2432 if (AllSubsInSet)
2433 Set.insert(Super);
2434 }
2435 }
2436
2437 // Convert to BitVector.
2438 BitVector BV(Registers.size() + 1);
2439 for (unsigned i = 0, e = Set.size(); i != e; ++i)
2440 BV.set(Set[i]->EnumValue);
2441 return BV;
2442}
2443
2444void CodeGenRegBank::printRegUnitName(unsigned Unit) const {
2445 if (Unit < NumNativeRegUnits)
2446 dbgs() << ' ' << RegUnits[Unit].Roots[0]->getName();
2447 else
2448 dbgs() << " #" << Unit;
2449}

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/MC/LaneBitmask.h

1//===- llvm/MC/LaneBitmask.h ------------------------------------*- C++ -*-===//
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/// \file
10/// A common definition of LaneBitmask for use in TableGen and CodeGen.
11///
12/// A lane mask is a bitmask representing the covering of a register with
13/// sub-registers.
14///
15/// This is typically used to track liveness at sub-register granularity.
16/// Lane masks for sub-register indices are similar to register units for
17/// physical registers. The individual bits in a lane mask can't be assigned
18/// any specific meaning. They can be used to check if two sub-register
19/// indices overlap.
20///
21/// Iff the target has a register such that:
22///
23/// getSubReg(Reg, A) overlaps getSubReg(Reg, B)
24///
25/// then:
26///
27/// (getSubRegIndexLaneMask(A) & getSubRegIndexLaneMask(B)) != 0
28
29#ifndef LLVM_MC_LANEBITMASK_H
30#define LLVM_MC_LANEBITMASK_H
31
32#include "llvm/Support/Compiler.h"
33#include "llvm/Support/Format.h"
34#include "llvm/Support/Printable.h"
35#include "llvm/Support/raw_ostream.h"
36
37namespace llvm {
38
39 struct LaneBitmask {
40 // When changing the underlying type, change the format string as well.
41 using Type = uint64_t;
42 enum : unsigned { BitWidth = 8*sizeof(Type) };
43 constexpr static const char *const FormatStr = "%016lX";
44
45 constexpr LaneBitmask() = default;
46 explicit constexpr LaneBitmask(Type V) : Mask(V) {}
47
48 constexpr bool operator== (LaneBitmask M) const { return Mask == M.Mask; }
49 constexpr bool operator!= (LaneBitmask M) const { return Mask != M.Mask; }
50 constexpr bool operator< (LaneBitmask M) const { return Mask < M.Mask; }
51 constexpr bool none() const { return Mask == 0; }
52 constexpr bool any() const { return Mask != 0; }
53 constexpr bool all() const { return ~Mask == 0; }
54
55 constexpr LaneBitmask operator~() const {
56 return LaneBitmask(~Mask);
57 }
58 constexpr LaneBitmask operator|(LaneBitmask M) const {
59 return LaneBitmask(Mask | M.Mask);
60 }
61 constexpr LaneBitmask operator&(LaneBitmask M) const {
62 return LaneBitmask(Mask & M.Mask);
63 }
64 LaneBitmask &operator|=(LaneBitmask M) {
65 Mask |= M.Mask;
66 return *this;
67 }
68 LaneBitmask &operator&=(LaneBitmask M) {
69 Mask &= M.Mask;
70 return *this;
71 }
72
73 constexpr Type getAsInteger() const { return Mask; }
74
75 unsigned getNumLanes() const {
76 return countPopulation(Mask);
77 }
78 unsigned getHighestLane() const {
79 return Log2_64(Mask);
5
Calling 'Log2_64'
7
Returning from 'Log2_64'
8
Returning the value 4294967295
80 }
81
82 static constexpr LaneBitmask getNone() { return LaneBitmask(0); }
83 static constexpr LaneBitmask getAll() { return ~LaneBitmask(0); }
84 static constexpr LaneBitmask getLane(unsigned Lane) {
85 return LaneBitmask(Type(1) << Lane);
13
The result of the left shift is undefined due to shifting by '4294967295', which is greater or equal to the width of type 'llvm::LaneBitmask::Type'
86 }
87
88 private:
89 Type Mask = 0;
90 };
91
92 /// Create Printable object to print LaneBitmasks on a \ref raw_ostream.
93 inline Printable PrintLaneMask(LaneBitmask LaneMask) {
94 return Printable([LaneMask](raw_ostream &OS) {
95 OS << format(LaneBitmask::FormatStr, LaneMask.getAsInteger());
96 });
97 }
98
99} // end namespace llvm
100
101#endif // LLVM_MC_LANEBITMASK_H

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h

1//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
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// This file contains some functions that are useful for math stuff.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14#define LLVM_SUPPORT_MATHEXTRAS_H
15
16#include "llvm/Support/Compiler.h"
17#include <algorithm>
18#include <cassert>
19#include <climits>
20#include <cmath>
21#include <cstdint>
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>
34extern "C" {
35unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
36unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
37unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
38unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
39}
40#endif
41
42namespace llvm {
43
44/// The behavior an operation has on an input of 0.
45enum ZeroBehavior {
46 /// The returned value is undefined.
47 ZB_Undefined,
48 /// The returned value is numeric_limits<T>::max()
49 ZB_Max,
50 /// The returned value is numeric_limits<T>::digits
51 ZB_Width
52};
53
54/// Mathematical constants.
55namespace numbers {
56// TODO: Track C++20 std::numbers.
57// TODO: Favor using the hexadecimal FP constants (requires C++17).
58constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
59 egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
60 ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
61 ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
62 log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
63 log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
64 pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
65 inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
66 sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
67 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
68 sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
69 inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
70 sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
71 inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
72 phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
73constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
74 egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
75 ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
76 ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
77 log2ef = 1.44269504F, // (0x1.715476P+0)
78 log10ef = .434294482F, // (0x1.bcb7b2P-2)
79 pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
80 inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
81 sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
82 inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
83 sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
84 inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
85 sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
86 inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
87 phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
88} // namespace numbers
89
90namespace detail {
91template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
92 static unsigned count(T Val, ZeroBehavior) {
93 if (!Val)
94 return std::numeric_limits<T>::digits;
95 if (Val & 0x1)
96 return 0;
97
98 // Bisection method.
99 unsigned ZeroBits = 0;
100 T Shift = std::numeric_limits<T>::digits >> 1;
101 T Mask = std::numeric_limits<T>::max() >> Shift;
102 while (Shift) {
103 if ((Val & Mask) == 0) {
104 Val >>= Shift;
105 ZeroBits |= Shift;
106 }
107 Shift >>= 1;
108 Mask >>= Shift;
109 }
110 return ZeroBits;
111 }
112};
113
114#if defined(__GNUC__4) || defined(_MSC_VER)
115template <typename T> struct TrailingZerosCounter<T, 4> {
116 static unsigned count(T Val, ZeroBehavior ZB) {
117 if (ZB != ZB_Undefined && Val == 0)
118 return 32;
119
120#if __has_builtin(__builtin_ctz)1 || defined(__GNUC__4)
121 return __builtin_ctz(Val);
122#elif defined(_MSC_VER)
123 unsigned long Index;
124 _BitScanForward(&Index, Val);
125 return Index;
126#endif
127 }
128};
129
130#if !defined(_MSC_VER) || defined(_M_X64)
131template <typename T> struct TrailingZerosCounter<T, 8> {
132 static unsigned count(T Val, ZeroBehavior ZB) {
133 if (ZB != ZB_Undefined && Val == 0)
134 return 64;
135
136#if __has_builtin(__builtin_ctzll)1 || defined(__GNUC__4)
137 return __builtin_ctzll(Val);
138#elif defined(_MSC_VER)
139 unsigned long Index;
140 _BitScanForward64(&Index, Val);
141 return Index;
142#endif
143 }
144};
145#endif
146#endif
147} // namespace detail
148
149/// Count number of 0's from the least significant bit to the most
150/// stopping at the first 1.
151///
152/// Only unsigned integral types are allowed.
153///
154/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
155/// valid arguments.
156template <typename T>
157unsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
158 static_assert(std::numeric_limits<T>::is_integer &&
159 !std::numeric_limits<T>::is_signed,
160 "Only unsigned integral types are allowed.");
161 return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
162}
163
164namespace detail {
165template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
166 static unsigned count(T Val, ZeroBehavior) {
167 if (!Val)
168 return std::numeric_limits<T>::digits;
169
170 // Bisection method.
171 unsigned ZeroBits = 0;
172 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
173 T Tmp = Val >> Shift;
174 if (Tmp)
175 Val = Tmp;
176 else
177 ZeroBits |= Shift;
178 }
179 return ZeroBits;
180 }
181};
182
183#if defined(__GNUC__4) || defined(_MSC_VER)
184template <typename T> struct LeadingZerosCounter<T, 4> {
185 static unsigned count(T Val, ZeroBehavior ZB) {
186 if (ZB != ZB_Undefined && Val == 0)
187 return 32;
188
189#if __has_builtin(__builtin_clz)1 || defined(__GNUC__4)
190 return __builtin_clz(Val);
191#elif defined(_MSC_VER)
192 unsigned long Index;
193 _BitScanReverse(&Index, Val);
194 return Index ^ 31;
195#endif
196 }
197};
198
199#if !defined(_MSC_VER) || defined(_M_X64)
200template <typename T> struct LeadingZerosCounter<T, 8> {
201 static unsigned count(T Val, ZeroBehavior ZB) {
202 if (ZB != ZB_Undefined && Val == 0)
203 return 64;
204
205#if __has_builtin(__builtin_clzll)1 || defined(__GNUC__4)
206 return __builtin_clzll(Val);
207#elif defined(_MSC_VER)
208 unsigned long Index;
209 _BitScanReverse64(&Index, Val);
210 return Index ^ 63;
211#endif
212 }
213};
214#endif
215#endif
216} // namespace detail
217
218/// Count number of 0's from the most significant bit to the least
219/// stopping at the first 1.
220///
221/// Only unsigned integral types are allowed.
222///
223/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
224/// valid arguments.
225template <typename T>
226unsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
227 static_assert(std::numeric_limits<T>::is_integer &&
228 !std::numeric_limits<T>::is_signed,
229 "Only unsigned integral types are allowed.");
230 return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
231}
232
233/// Get the index of the first set bit starting from the least
234/// significant bit.
235///
236/// Only unsigned integral types are allowed.
237///
238/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
239/// valid arguments.
240template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
241 if (ZB == ZB_Max && Val == 0)
242 return std::numeric_limits<T>::max();
243
244 return countTrailingZeros(Val, ZB_Undefined);
245}
246
247/// Create a bitmask with the N right-most bits set to 1, and all other
248/// bits set to 0. Only unsigned types are allowed.
249template <typename T> T maskTrailingOnes(unsigned N) {
250 static_assert(std::is_unsigned<T>::value, "Invalid type!");
251 const unsigned Bits = CHAR_BIT8 * sizeof(T);
252 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 252, __PRETTY_FUNCTION__))
;
253 return N == 0 ? 0 : (T(-1) >> (Bits - N));
254}
255
256/// Create a bitmask with the N left-most bits set to 1, and all other
257/// bits set to 0. Only unsigned types are allowed.
258template <typename T> T maskLeadingOnes(unsigned N) {
259 return ~maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
260}
261
262/// Create a bitmask with the N right-most bits set to 0, and all other
263/// bits set to 1. Only unsigned types are allowed.
264template <typename T> T maskTrailingZeros(unsigned N) {
265 return maskLeadingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
266}
267
268/// Create a bitmask with the N left-most bits set to 0, and all other
269/// bits set to 1. Only unsigned types are allowed.
270template <typename T> T maskLeadingZeros(unsigned N) {
271 return maskTrailingOnes<T>(CHAR_BIT8 * sizeof(T) - N);
272}
273
274/// Get the index of the last set bit starting from the least
275/// significant bit.
276///
277/// Only unsigned integral types are allowed.
278///
279/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
280/// valid arguments.
281template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
282 if (ZB == ZB_Max && Val == 0)
283 return std::numeric_limits<T>::max();
284
285 // Use ^ instead of - because both gcc and llvm can remove the associated ^
286 // in the __builtin_clz intrinsic on x86.
287 return countLeadingZeros(Val, ZB_Undefined) ^
288 (std::numeric_limits<T>::digits - 1);
289}
290
291/// Macro compressed bit reversal table for 256 bits.
292///
293/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
294static const unsigned char BitReverseTable256[256] = {
295#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
296#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
297#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
298 R6(0), R6(2), R6(1), R6(3)
299#undef R2
300#undef R4
301#undef R6
302};
303
304/// Reverse the bits in \p Val.
305template <typename T>
306T reverseBits(T Val) {
307 unsigned char in[sizeof(Val)];
308 unsigned char out[sizeof(Val)];
309 std::memcpy(in, &Val, sizeof(Val));
310 for (unsigned i = 0; i < sizeof(Val); ++i)
311 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
312 std::memcpy(&Val, out, sizeof(Val));
313 return Val;
314}
315
316// NOTE: The following support functions use the _32/_64 extensions instead of
317// type overloading so that signed and unsigned integers can be used without
318// ambiguity.
319
320/// Return the high 32 bits of a 64 bit value.
321constexpr inline uint32_t Hi_32(uint64_t Value) {
322 return static_cast<uint32_t>(Value >> 32);
323}
324
325/// Return the low 32 bits of a 64 bit value.
326constexpr inline uint32_t Lo_32(uint64_t Value) {
327 return static_cast<uint32_t>(Value);
328}
329
330/// Make a 64-bit integer from a high / low pair of 32-bit integers.
331constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
332 return ((uint64_t)High << 32) | (uint64_t)Low;
333}
334
335/// Checks if an integer fits into the given bit width.
336template <unsigned N> constexpr inline bool isInt(int64_t x) {
337 return N >= 64 || (-(INT64_C(1)1L<<(N-1)) <= x && x < (INT64_C(1)1L<<(N-1)));
338}
339// Template specializations to get better code for common cases.
340template <> constexpr inline bool isInt<8>(int64_t x) {
341 return static_cast<int8_t>(x) == x;
342}
343template <> constexpr inline bool isInt<16>(int64_t x) {
344 return static_cast<int16_t>(x) == x;
345}
346template <> constexpr inline bool isInt<32>(int64_t x) {
347 return static_cast<int32_t>(x) == x;
348}
349
350/// Checks if a signed integer is an N bit number shifted left by S.
351template <unsigned N, unsigned S>
352constexpr inline bool isShiftedInt(int64_t x) {
353 static_assert(
354 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
355 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
356 return isInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
357}
358
359/// Checks if an unsigned integer fits into the given bit width.
360///
361/// This is written as two functions rather than as simply
362///
363/// return N >= 64 || X < (UINT64_C(1) << N);
364///
365/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
366/// left too many places.
367template <unsigned N>
368constexpr inline std::enable_if_t<(N < 64), bool> isUInt(uint64_t X) {
369 static_assert(N > 0, "isUInt<0> doesn't make sense");
370 return X < (UINT64_C(1)1UL << (N));
371}
372template <unsigned N>
373constexpr inline std::enable_if_t<N >= 64, bool> isUInt(uint64_t X) {
374 return true;
375}
376
377// Template specializations to get better code for common cases.
378template <> constexpr inline bool isUInt<8>(uint64_t x) {
379 return static_cast<uint8_t>(x) == x;
380}
381template <> constexpr inline bool isUInt<16>(uint64_t x) {
382 return static_cast<uint16_t>(x) == x;
383}
384template <> constexpr inline bool isUInt<32>(uint64_t x) {
385 return static_cast<uint32_t>(x) == x;
386}
387
388/// Checks if a unsigned integer is an N bit number shifted left by S.
389template <unsigned N, unsigned S>
390constexpr inline bool isShiftedUInt(uint64_t x) {
391 static_assert(
392 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
393 static_assert(N + S <= 64,
394 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
395 // Per the two static_asserts above, S must be strictly less than 64. So
396 // 1 << S is not undefined behavior.
397 return isUInt<N + S>(x) && (x % (UINT64_C(1)1UL << S) == 0);
398}
399
400/// Gets the maximum value for a N-bit unsigned integer.
401inline uint64_t maxUIntN(uint64_t N) {
402 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 402, __PRETTY_FUNCTION__))
;
403
404 // uint64_t(1) << 64 is undefined behavior, so we can't do
405 // (uint64_t(1) << N) - 1
406 // without checking first that N != 64. But this works and doesn't have a
407 // branch.
408 return UINT64_MAX(18446744073709551615UL) >> (64 - N);
409}
410
411/// Gets the minimum value for a N-bit signed integer.
412inline int64_t minIntN(int64_t N) {
413 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 413, __PRETTY_FUNCTION__))
;
414
415 return -(UINT64_C(1)1UL<<(N-1));
416}
417
418/// Gets the maximum value for a N-bit signed integer.
419inline int64_t maxIntN(int64_t N) {
420 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 420, __PRETTY_FUNCTION__))
;
421
422 // This relies on two's complement wraparound when N == 64, so we convert to
423 // int64_t only at the very end to avoid UB.
424 return (UINT64_C(1)1UL << (N - 1)) - 1;
425}
426
427/// Checks if an unsigned integer fits into the given (dynamic) bit width.
428inline bool isUIntN(unsigned N, uint64_t x) {
429 return N >= 64 || x <= maxUIntN(N);
430}
431
432/// Checks if an signed integer fits into the given (dynamic) bit width.
433inline bool isIntN(unsigned N, int64_t x) {
434 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
435}
436
437/// Return true if the argument is a non-empty sequence of ones starting at the
438/// least significant bit with the remainder zero (32 bit version).
439/// Ex. isMask_32(0x0000FFFFU) == true.
440constexpr inline bool isMask_32(uint32_t Value) {
441 return Value && ((Value + 1) & Value) == 0;
442}
443
444/// Return true if the argument is a non-empty sequence of ones starting at the
445/// least significant bit with the remainder zero (64 bit version).
446constexpr inline bool isMask_64(uint64_t Value) {
447 return Value && ((Value + 1) & Value) == 0;
448}
449
450/// Return true if the argument contains a non-empty sequence of ones with the
451/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
452constexpr inline bool isShiftedMask_32(uint32_t Value) {
453 return Value && isMask_32((Value - 1) | Value);
454}
455
456/// Return true if the argument contains a non-empty sequence of ones with the
457/// remainder zero (64 bit version.)
458constexpr inline bool isShiftedMask_64(uint64_t Value) {
459 return Value && isMask_64((Value - 1) | Value);
460}
461
462/// Return true if the argument is a power of two > 0.
463/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
464constexpr inline bool isPowerOf2_32(uint32_t Value) {
465 return Value && !(Value & (Value - 1));
466}
467
468/// Return true if the argument is a power of two > 0 (64 bit edition.)
469constexpr inline bool isPowerOf2_64(uint64_t Value) {
470 return Value && !(Value & (Value - 1));
471}
472
473/// Count the number of ones from the most significant bit to the first
474/// zero bit.
475///
476/// Ex. countLeadingOnes(0xFF0FFF00) == 8.
477/// Only unsigned integral types are allowed.
478///
479/// \param ZB the behavior on an input of all ones. Only ZB_Width and
480/// ZB_Undefined are valid arguments.
481template <typename T>
482unsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
483 static_assert(std::numeric_limits<T>::is_integer &&
484 !std::numeric_limits<T>::is_signed,
485 "Only unsigned integral types are allowed.");
486 return countLeadingZeros<T>(~Value, ZB);
487}
488
489/// Count the number of ones from the least significant bit to the first
490/// zero bit.
491///
492/// Ex. countTrailingOnes(0x00FF00FF) == 8.
493/// Only unsigned integral types are allowed.
494///
495/// \param ZB the behavior on an input of all ones. Only ZB_Width and
496/// ZB_Undefined are valid arguments.
497template <typename T>
498unsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
499 static_assert(std::numeric_limits<T>::is_integer &&
500 !std::numeric_limits<T>::is_signed,
501 "Only unsigned integral types are allowed.");
502 return countTrailingZeros<T>(~Value, ZB);
503}
504
505namespace detail {
506template <typename T, std::size_t SizeOfT> struct PopulationCounter {
507 static unsigned count(T Value) {
508 // Generic version, forward to 32 bits.
509 static_assert(SizeOfT <= 4, "Not implemented!");
510#if defined(__GNUC__4)
511 return __builtin_popcount(Value);
512#else
513 uint32_t v = Value;
514 v = v - ((v >> 1) & 0x55555555);
515 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
516 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
517#endif
518 }
519};
520
521template <typename T> struct PopulationCounter<T, 8> {
522 static unsigned count(T Value) {
523#if defined(__GNUC__4)
524 return __builtin_popcountll(Value);
525#else
526 uint64_t v = Value;
527 v = v - ((v >> 1) & 0x5555555555555555ULL);
528 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
529 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
530 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
531#endif
532 }
533};
534} // namespace detail
535
536/// Count the number of set bits in a value.
537/// Ex. countPopulation(0xF000F000) = 8
538/// Returns 0 if the word is zero.
539template <typename T>
540inline unsigned countPopulation(T Value) {
541 static_assert(std::numeric_limits<T>::is_integer &&
542 !std::numeric_limits<T>::is_signed,
543 "Only unsigned integral types are allowed.");
544 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
545}
546
547/// Compile time Log2.
548/// Valid only for positive powers of two.
549template <size_t kValue> constexpr inline size_t CTLog2() {
550 static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
551 "Value is not a valid power of 2");
552 return 1 + CTLog2<kValue / 2>();
553}
554
555template <> constexpr inline size_t CTLog2<1>() { return 0; }
556
557/// Return the log base 2 of the specified value.
558inline double Log2(double Value) {
559#if defined(__ANDROID_API__) && __ANDROID_API__ < 18
560 return __builtin_log(Value) / __builtin_log(2.0);
561#else
562 return log2(Value);
563#endif
564}
565
566/// Return the floor log base 2 of the specified value, -1 if the value is zero.
567/// (32 bit edition.)
568/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
569inline unsigned Log2_32(uint32_t Value) {
570 return 31 - countLeadingZeros(Value);
571}
572
573/// Return the floor log base 2 of the specified value, -1 if the value is zero.
574/// (64 bit edition.)
575inline unsigned Log2_64(uint64_t Value) {
576 return 63 - countLeadingZeros(Value);
6
Returning the value 4294967295
577}
578
579/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
580/// (32 bit edition).
581/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
582inline unsigned Log2_32_Ceil(uint32_t Value) {
583 return 32 - countLeadingZeros(Value - 1);
584}
585
586/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
587/// (64 bit edition.)
588inline unsigned Log2_64_Ceil(uint64_t Value) {
589 return 64 - countLeadingZeros(Value - 1);
590}
591
592/// Return the greatest common divisor of the values using Euclid's algorithm.
593template <typename T>
594inline T greatestCommonDivisor(T A, T B) {
595 while (B) {
596 T Tmp = B;
597 B = A % B;
598 A = Tmp;
599 }
600 return A;
601}
602
603inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
604 return greatestCommonDivisor<uint64_t>(A, B);
605}
606
607/// This function takes a 64-bit integer and returns the bit equivalent double.
608inline double BitsToDouble(uint64_t Bits) {
609 double D;
610 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
611 memcpy(&D, &Bits, sizeof(Bits));
612 return D;
613}
614
615/// This function takes a 32-bit integer and returns the bit equivalent float.
616inline float BitsToFloat(uint32_t Bits) {
617 float F;
618 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
619 memcpy(&F, &Bits, sizeof(Bits));
620 return F;
621}
622
623/// This function takes a double and returns the bit equivalent 64-bit integer.
624/// Note that copying doubles around changes the bits of NaNs on some hosts,
625/// notably x86, so this routine cannot be used if these bits are needed.
626inline uint64_t DoubleToBits(double Double) {
627 uint64_t Bits;
628 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
629 memcpy(&Bits, &Double, sizeof(Double));
630 return Bits;
631}
632
633/// This function takes a float and returns the bit equivalent 32-bit integer.
634/// Note that copying floats around changes the bits of NaNs on some hosts,
635/// notably x86, so this routine cannot be used if these bits are needed.
636inline uint32_t FloatToBits(float Float) {
637 uint32_t Bits;
638 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
639 memcpy(&Bits, &Float, sizeof(Float));
640 return Bits;
641}
642
643/// A and B are either alignments or offsets. Return the minimum alignment that
644/// may be assumed after adding the two together.
645constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
646 // The largest power of 2 that divides both A and B.
647 //
648 // Replace "-Value" by "1+~Value" in the following commented code to avoid
649 // MSVC warning C4146
650 // return (A | B) & -(A | B);
651 return (A | B) & (1 + ~(A | B));
652}
653
654/// Returns the next power of two (in 64-bits) that is strictly greater than A.
655/// Returns zero on overflow.
656inline uint64_t NextPowerOf2(uint64_t A) {
657 A |= (A >> 1);
658 A |= (A >> 2);
659 A |= (A >> 4);
660 A |= (A >> 8);
661 A |= (A >> 16);
662 A |= (A >> 32);
663 return A + 1;
664}
665
666/// Returns the power of two which is less than or equal to the given value.
667/// Essentially, it is a floor operation across the domain of powers of two.
668inline uint64_t PowerOf2Floor(uint64_t A) {
669 if (!A) return 0;
670 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
671}
672
673/// Returns the power of two which is greater than or equal to the given value.
674/// Essentially, it is a ceil operation across the domain of powers of two.
675inline uint64_t PowerOf2Ceil(uint64_t A) {
676 if (!A)
677 return 0;
678 return NextPowerOf2(A - 1);
679}
680
681/// Returns the next integer (mod 2**64) that is greater than or equal to
682/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
683///
684/// If non-zero \p Skew is specified, the return value will be a minimal
685/// integer that is greater than or equal to \p Value and equal to
686/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
687/// \p Align, its value is adjusted to '\p Skew mod \p Align'.
688///
689/// Examples:
690/// \code
691/// alignTo(5, 8) = 8
692/// alignTo(17, 8) = 24
693/// alignTo(~0LL, 8) = 0
694/// alignTo(321, 255) = 510
695///
696/// alignTo(5, 8, 7) = 7
697/// alignTo(17, 8, 1) = 17
698/// alignTo(~0LL, 8, 3) = 3
699/// alignTo(321, 255, 42) = 552
700/// \endcode
701inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
702 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 702, __PRETTY_FUNCTION__))
;
703 Skew %= Align;
704 return (Value + Align - 1 - Skew) / Align * Align + Skew;
705}
706
707/// Returns the next integer (mod 2**64) that is greater than or equal to
708/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
709template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
710 static_assert(Align != 0u, "Align must be non-zero");
711 return (Value + Align - 1) / Align * Align;
712}
713
714/// Returns the integer ceil(Numerator / Denominator).
715inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
716 return alignTo(Numerator, Denominator) / Denominator;
717}
718
719/// Returns the integer nearest(Numerator / Denominator).
720inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
721 return (Numerator + (Denominator / 2)) / Denominator;
722}
723
724/// Returns the largest uint64_t less than or equal to \p Value and is
725/// \p Skew mod \p Align. \p Align must be non-zero
726inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
727 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 727, __PRETTY_FUNCTION__))
;
728 Skew %= Align;
729 return (Value - Skew) / Align * Align + Skew;
730}
731
732/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
733/// Requires 0 < B <= 32.
734template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
735 static_assert(B > 0, "Bit width can't be 0.");
736 static_assert(B <= 32, "Bit width out of range.");
737 return int32_t(X << (32 - B)) >> (32 - B);
738}
739
740/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
741/// Requires 0 < B < 32.
742inline int32_t SignExtend32(uint32_t X, unsigned B) {
743 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 743, __PRETTY_FUNCTION__))
;
744 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 744, __PRETTY_FUNCTION__))
;
745 return int32_t(X << (32 - B)) >> (32 - B);
746}
747
748/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
749/// Requires 0 < B < 64.
750template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
751 static_assert(B > 0, "Bit width can't be 0.");
752 static_assert(B <= 64, "Bit width out of range.");
753 return int64_t(x << (64 - B)) >> (64 - B);
754}
755
756/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
757/// Requires 0 < B < 64.
758inline int64_t SignExtend64(uint64_t X, unsigned B) {
759 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 759, __PRETTY_FUNCTION__))
;
760 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-11~++20200309111110+2c36c23f347/llvm/include/llvm/Support/MathExtras.h"
, 760, __PRETTY_FUNCTION__))
;
761 return int64_t(X << (64 - B)) >> (64 - B);
762}
763
764/// Subtract two unsigned integers, X and Y, of type T and return the absolute
765/// value of the result.
766template <typename T>
767std::enable_if_t<std::is_unsigned<T>::value, T> 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.
774template <typename T>
775std::enable_if_t<std::is_unsigned<T>::value, T>
776SaturatingAdd(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.
791template <typename T>
792std::enable_if_t<std::is_unsigned<T>::value, T>
793SaturatingMultiply(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.
837template <typename T>
838std::enable_if_t<std::is_unsigned<T>::value, T>
839SaturatingMultiplyAdd(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.
851extern const float huge_valf;
852
853
854/// Add two signed integers, computing the two's complement truncated result,
855/// returning true if overflow occured.
856template <typename T>
857std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
858#if __has_builtin(__builtin_add_overflow)1
859 return __builtin_add_overflow(X, Y, &Result);
860#else
861 // Perform the unsigned addition.
862 using U = std::make_unsigned_t<T>;
863 const U UX = static_cast<U>(X);
864 const U UY = static_cast<U>(Y);
865 const U UResult = UX + UY;
866
867 // Convert to signed.
868 Result = static_cast<T>(UResult);
869
870 // Adding two positive numbers should result in a positive number.
871 if (X > 0 && Y > 0)
872 return Result <= 0;
873 // Adding two negatives should result in a negative number.
874 if (X < 0 && Y < 0)
875 return Result >= 0;
876 return false;
877#endif
878}
879
880/// Subtract two signed integers, computing the two's complement truncated
881/// result, returning true if an overflow ocurred.
882template <typename T>
883std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
884#if __has_builtin(__builtin_sub_overflow)1
885 return __builtin_sub_overflow(X, Y, &Result);
886#else
887 // Perform the unsigned addition.
888 using U = std::make_unsigned_t<T>;
889 const U UX = static_cast<U>(X);
890 const U UY = static_cast<U>(Y);
891 const U UResult = UX - UY;
892
893 // Convert to signed.
894 Result = static_cast<T>(UResult);
895
896 // Subtracting a positive number from a negative results in a negative number.
897 if (X <= 0 && Y > 0)
898 return Result >= 0;
899 // Subtracting a negative number from a positive results in a positive number.
900 if (X >= 0 && Y < 0)
901 return Result <= 0;
902 return false;
903#endif
904}
905
906/// Multiply two signed integers, computing the two's complement truncated
907/// result, returning true if an overflow ocurred.
908template <typename T>
909std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
910 // Perform the unsigned multiplication on absolute values.
911 using U = std::make_unsigned_t<T>;
912 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
913 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
914 const U UResult = UX * UY;
915
916 // Convert to signed.
917 const bool IsNegative = (X < 0) ^ (Y < 0);
918 Result = IsNegative ? (0 - UResult) : UResult;
919
920 // If any of the args was 0, result is 0 and no overflow occurs.
921 if (UX == 0 || UY == 0)
922 return false;
923
924 // UX and UY are in [1, 2^n], where n is the number of digits.
925 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
926 // positive) divided by an argument compares to the other.
927 if (IsNegative)
928 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
929 else
930 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
931}
932
933} // End llvm namespace
934
935#endif