blob: b3e0f5f027a8a80c8a84f094d4a2d20f4b98d3df [file] [log] [blame]
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001//===- subzero/src/IceOperand.h - High-level operands -----------*- C++ -*-===//
2//
3// The Subzero Code Generator
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Andrew Scull9612d322015-07-06 14:53:25 -07009///
10/// \file
Jim Stichnoth92a6e5b2015-12-02 16:52:44 -080011/// \brief Declares the Operand class and its target-independent subclasses.
12///
Andrew Scull6ef79492015-09-09 15:50:42 -070013/// The main classes are Variable, which represents an LLVM variable that is
14/// either register- or stack-allocated, and the Constant hierarchy, which
15/// represents integer, floating-point, and/or symbolic constants.
Andrew Scull9612d322015-07-06 14:53:25 -070016///
Jim Stichnothf7c9a142014-04-29 10:52:43 -070017//===----------------------------------------------------------------------===//
18
19#ifndef SUBZERO_SRC_ICEOPERAND_H
20#define SUBZERO_SRC_ICEOPERAND_H
21
22#include "IceDefs.h"
John Portoe82b5602016-02-24 15:58:55 -080023#include "IceCfg.h"
Jan Voungfe14fb82014-10-13 15:56:32 -070024#include "IceGlobalContext.h"
Jim Stichnoth467ffe52016-03-29 15:01:06 -070025#include "IceStringPool.h"
Jim Stichnothf7c9a142014-04-29 10:52:43 -070026#include "IceTypes.h"
27
Jim Stichnothb36757e2015-10-05 13:55:11 -070028#include "llvm/Support/Format.h"
29
John Porto27fddcc2016-02-02 15:06:09 -080030#include <limits>
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -080031#include <type_traits>
John Porto27fddcc2016-02-02 15:06:09 -080032
Jim Stichnothf7c9a142014-04-29 10:52:43 -070033namespace Ice {
34
35class Operand {
Jim Stichnothc6ead202015-02-24 09:30:30 -080036 Operand() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -070037 Operand(const Operand &) = delete;
38 Operand &operator=(const Operand &) = delete;
39
Jim Stichnothf7c9a142014-04-29 10:52:43 -070040public:
Andrew Scull6ef79492015-09-09 15:50:42 -070041 static constexpr size_t MaxTargetKinds = 10;
Jim Stichnothf7c9a142014-04-29 10:52:43 -070042 enum OperandKind {
43 kConst_Base,
Jan Voungbc004632014-09-16 15:09:10 -070044 kConstInteger32,
45 kConstInteger64,
Jim Stichnothf7c9a142014-04-29 10:52:43 -070046 kConstFloat,
47 kConstDouble,
48 kConstRelocatable,
Matt Walad8f4a7d2014-06-18 09:55:03 -070049 kConstUndef,
Jim Stichnoth800dab22014-09-20 12:25:02 -070050 kConst_Target, // leave space for target-specific constant kinds
Andrew Scull6ef79492015-09-09 15:50:42 -070051 kConst_Max = kConst_Target + MaxTargetKinds,
Jim Stichnothf7c9a142014-04-29 10:52:43 -070052 kVariable,
Andrew Scull6d47bcd2015-09-17 17:10:05 -070053 kVariable64On32,
Eric Holk80ee5b32016-05-06 14:28:04 -070054 kVariableBoolean,
Jim Stichnoth800dab22014-09-20 12:25:02 -070055 kVariable_Target, // leave space for target-specific variable kinds
Andrew Scull6ef79492015-09-09 15:50:42 -070056 kVariable_Max = kVariable_Target + MaxTargetKinds,
Andrew Scull57e12682015-09-16 11:30:19 -070057 // Target-specific operand classes use kTarget as the starting point for
58 // their Kind enum space. Note that the value-spaces are shared across
59 // targets. To avoid confusion over the definition of shared values, an
60 // object specific to one target should never be passed to a different
61 // target.
Andrew Scull6ef79492015-09-09 15:50:42 -070062 kTarget,
63 kTarget_Max = std::numeric_limits<uint8_t>::max(),
Jim Stichnothf7c9a142014-04-29 10:52:43 -070064 };
Andrew Scull6ef79492015-09-09 15:50:42 -070065 static_assert(kTarget <= kTarget_Max, "Must not be above max.");
Jim Stichnothf7c9a142014-04-29 10:52:43 -070066 OperandKind getKind() const { return Kind; }
67 Type getType() const { return Ty; }
68
Andrew Scull6ef79492015-09-09 15:50:42 -070069 /// Every Operand keeps an array of the Variables referenced in the operand.
70 /// This is so that the liveness operations can get quick access to the
71 /// variables of interest, without having to dig so far into the operand.
Jim Stichnothf7c9a142014-04-29 10:52:43 -070072 SizeT getNumVars() const { return NumVars; }
73 Variable *getVar(SizeT I) const {
74 assert(I < getNumVars());
75 return Vars[I];
76 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -070077 virtual void emit(const Cfg *Func) const = 0;
Andrew Scull9612d322015-07-06 14:53:25 -070078
79 /// \name Dumping functions.
80 /// @{
81
Andrew Scull57e12682015-09-16 11:30:19 -070082 /// The dump(Func,Str) implementation must be sure to handle the situation
83 /// where Func==nullptr.
Jim Stichnoth2e8bfbb2014-09-16 10:16:00 -070084 virtual void dump(const Cfg *Func, Ostream &Str) const = 0;
85 void dump(const Cfg *Func) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -070086 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -080087 return;
Jim Stichnoth2e8bfbb2014-09-16 10:16:00 -070088 assert(Func);
89 dump(Func, Func->getContext()->getStrDump());
90 }
Karl Schimpfb6c96af2014-11-17 10:58:39 -080091 void dump(Ostream &Str) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -070092 if (BuildDefs::dump())
Jim Stichnothae953202014-12-20 06:17:49 -080093 dump(nullptr, Str);
Karl Schimpfb6c96af2014-11-17 10:58:39 -080094 }
Andrew Scull9612d322015-07-06 14:53:25 -070095 /// @}
Jim Stichnothf7c9a142014-04-29 10:52:43 -070096
Sean Kleinfc707ff2016-02-29 16:44:07 -080097 virtual ~Operand() = default;
Andrew Scull00741a02015-09-16 19:04:09 -070098
Eric Holk80ee5b32016-05-06 14:28:04 -070099 virtual Variable *asBoolean() { return nullptr; }
100
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700101protected:
Andrew Scull6ef79492015-09-09 15:50:42 -0700102 Operand(OperandKind Kind, Type Ty) : Ty(Ty), Kind(Kind) {
103 // It is undefined behavior to have a larger value in the enum
104 assert(Kind <= kTarget_Max);
105 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700106
107 const Type Ty;
108 const OperandKind Kind;
Andrew Scull9612d322015-07-06 14:53:25 -0700109 /// Vars and NumVars are initialized by the derived class.
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700110 SizeT NumVars = 0;
111 Variable **Vars = nullptr;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700112};
113
Jim Stichnothdd842db2015-01-27 12:53:53 -0800114template <class StreamType>
Karl Schimpf97501832014-09-16 13:35:32 -0700115inline StreamType &operator<<(StreamType &Str, const Operand &Op) {
116 Op.dump(Str);
117 return Str;
118}
119
Andrew Scull57e12682015-09-16 11:30:19 -0700120/// Constant is the abstract base class for constants. All constants are
121/// allocated from a global arena and are pooled.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700122class Constant : public Operand {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800123 Constant() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -0700124 Constant(const Constant &) = delete;
125 Constant &operator=(const Constant &) = delete;
126
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700127public:
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -0800128 // Declare the lookup counter to take minimal space in a non-DUMP build.
129 using CounterType =
130 std::conditional<BuildDefs::dump(), uint64_t, uint8_t>::type;
Jan Voung76bb0be2015-05-14 09:26:19 -0700131 void emit(const Cfg *Func) const override { emit(Func->getTarget()); }
132 virtual void emit(TargetLowering *Target) const = 0;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700133
134 static bool classof(const Operand *Operand) {
135 OperandKind Kind = Operand->getKind();
Andrew Scull6ef79492015-09-09 15:50:42 -0700136 return Kind >= kConst_Base && Kind <= kConst_Max;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700137 }
138
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700139 const GlobalString getLabelName() const { return LabelName; }
140
Andrew Scull57e12682015-09-16 11:30:19 -0700141 /// Judge if this given immediate should be randomized or pooled By default
142 /// should return false, only constant integers should truly go through this
143 /// method.
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700144 virtual bool shouldBeRandomizedOrPooled() const { return false; }
Qining Lu253dc8a2015-06-22 10:10:23 -0700145
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -0800146 bool getShouldBePooled() const { return ShouldBePooled; }
Qining Lu253dc8a2015-06-22 10:10:23 -0700147
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -0800148 // This should be thread-safe because the constant pool lock is acquired
149 // before the method is invoked.
150 void updateLookupCount() {
151 if (!BuildDefs::dump())
152 return;
153 ++LookupCount;
154 }
155 CounterType getLookupCount() const { return LookupCount; }
Qining Lu253dc8a2015-06-22 10:10:23 -0700156
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700157protected:
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -0800158 Constant(OperandKind Kind, Type Ty) : Operand(Kind, Ty) {
Jim Stichnothae953202014-12-20 06:17:49 -0800159 Vars = nullptr;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700160 NumVars = 0;
161 }
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700162 /// Set the ShouldBePooled field to the proper value after the object is fully
163 /// initialized.
164 void initShouldBePooled();
165 GlobalString LabelName;
Andrew Scull9612d322015-07-06 14:53:25 -0700166 /// Whether we should pool this constant. Usually Float/Double and pooled
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700167 /// Integers should be flagged true. Ideally this field would be const, but
168 /// it needs to be initialized only after the subclass is fully constructed.
Jim Stichnoth9f9aa2c2016-03-07 08:25:24 -0800169 bool ShouldBePooled = false;
170 /// Note: If ShouldBePooled is ever removed from the base class, we will want
171 /// to completely disable LookupCount in a non-DUMP build to save space.
172 CounterType LookupCount = 0;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700173};
174
Andrew Scull9612d322015-07-06 14:53:25 -0700175/// ConstantPrimitive<> wraps a primitive type.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700176template <typename T, Operand::OperandKind K>
177class ConstantPrimitive : public Constant {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800178 ConstantPrimitive() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -0700179 ConstantPrimitive(const ConstantPrimitive &) = delete;
180 ConstantPrimitive &operator=(const ConstantPrimitive &) = delete;
181
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700182public:
Andrew Scull8072bae2015-09-14 16:01:26 -0700183 using PrimType = T;
Jan Voung91a3e2c2015-01-09 13:01:42 -0800184
Jim Stichnothb36757e2015-10-05 13:55:11 -0700185 static ConstantPrimitive *create(GlobalContext *Ctx, Type Ty,
186 PrimType Value) {
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700187 auto *Const =
188 new (Ctx->allocate<ConstantPrimitive>()) ConstantPrimitive(Ty, Value);
189 Const->initShouldBePooled();
190 if (Const->getShouldBePooled())
191 Const->initName(Ctx);
192 return Const;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700193 }
Jan Voung91a3e2c2015-01-09 13:01:42 -0800194 PrimType getValue() const { return Value; }
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700195 using Constant::emit;
196 void emit(TargetLowering *Target) const final;
197 using Constant::dump;
198 void dump(const Cfg *, Ostream &Str) const override {
199 if (BuildDefs::dump())
200 Str << getValue();
201 }
202
203 static bool classof(const Operand *Operand) {
204 return Operand->getKind() == K;
205 }
206
207 virtual bool shouldBeRandomizedOrPooled() const override { return false; }
208
209private:
210 ConstantPrimitive(Type Ty, PrimType Value) : Constant(K, Ty), Value(Value) {}
211
212 void initName(GlobalContext *Ctx) {
213 std::string Buffer;
214 llvm::raw_string_ostream Str(Buffer);
Jim Stichnothe922c232016-04-09 08:54:20 -0700215 constexpr bool IsCompact = !BuildDefs::dump();
216 if (IsCompact) {
217 switch (getType()) {
218 case IceType_f32:
219 Str << "$F";
220 break;
221 case IceType_f64:
222 Str << "$D";
223 break;
224 default:
225 // For constant pooling diversification
226 Str << ".L$" << getType() << "$";
227 break;
228 }
229 } else {
230 Str << ".L$" << getType() << "$";
231 }
Jim Stichnothb36757e2015-10-05 13:55:11 -0700232 // Print hex characters byte by byte, starting from the most significant
233 // byte. NOTE: This ordering assumes Subzero runs on a little-endian
234 // platform. That means the possibility of different label names depending
235 // on the endian-ness of the platform where Subzero runs.
236 for (unsigned i = 0; i < sizeof(Value); ++i) {
237 constexpr unsigned HexWidthChars = 2;
238 unsigned Offset = sizeof(Value) - 1 - i;
239 Str << llvm::format_hex_no_prefix(
240 *(Offset + (const unsigned char *)&Value), HexWidthChars);
241 }
242 // For a floating-point value in DecorateAsm mode, also append the value in
243 // human-readable sprintf form, changing '+' to 'p' and '-' to 'm' to
244 // maintain valid asm labels.
Jim Stichnothe922c232016-04-09 08:54:20 -0700245 if (BuildDefs::dump() && std::is_floating_point<PrimType>::value &&
Karl Schimpfd4699942016-04-02 09:55:31 -0700246 getFlags().getDecorateAsm()) {
Jim Stichnothb36757e2015-10-05 13:55:11 -0700247 char Buf[30];
248 snprintf(Buf, llvm::array_lengthof(Buf), "$%g", (double)Value);
249 for (unsigned i = 0; i < llvm::array_lengthof(Buf) && Buf[i]; ++i) {
250 if (Buf[i] == '-')
251 Buf[i] = 'm';
252 else if (Buf[i] == '+')
253 Buf[i] = 'p';
254 }
255 Str << Buf;
256 }
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700257 LabelName = GlobalString::createWithString(Ctx, Str.str());
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800258 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700259
Jan Voung91a3e2c2015-01-09 13:01:42 -0800260 const PrimType Value;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700261};
262
Andrew Scull8072bae2015-09-14 16:01:26 -0700263using ConstantInteger32 = ConstantPrimitive<int32_t, Operand::kConstInteger32>;
264using ConstantInteger64 = ConstantPrimitive<int64_t, Operand::kConstInteger64>;
265using ConstantFloat = ConstantPrimitive<float, Operand::kConstFloat>;
266using ConstantDouble = ConstantPrimitive<double, Operand::kConstDouble>;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700267
Jim Stichnothdd842db2015-01-27 12:53:53 -0800268template <>
269inline void ConstantInteger32::dump(const Cfg *, Ostream &Str) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700270 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800271 return;
Jim Stichnothcabfa302014-09-03 15:19:12 -0700272 if (getType() == IceType_i1)
273 Str << (getValue() ? "true" : "false");
274 else
Jan Voungbc004632014-09-16 15:09:10 -0700275 Str << static_cast<int32_t>(getValue());
276}
277
Andrew Scull9612d322015-07-06 14:53:25 -0700278/// Specialization of the template member function for ConstantInteger32
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700279template <> bool ConstantInteger32::shouldBeRandomizedOrPooled() const;
Qining Lu253dc8a2015-06-22 10:10:23 -0700280
Jim Stichnothdd842db2015-01-27 12:53:53 -0800281template <>
282inline void ConstantInteger64::dump(const Cfg *, Ostream &Str) const {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700283 if (!BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800284 return;
Jan Voungbc004632014-09-16 15:09:10 -0700285 assert(getType() == IceType_i64);
286 Str << static_cast<int64_t>(getValue());
Jim Stichnothcabfa302014-09-03 15:19:12 -0700287}
288
John Porto27fddcc2016-02-02 15:06:09 -0800289/// RelocOffset allows symbolic references in ConstantRelocatables' offsets,
290/// e.g., 8 + LabelOffset, where label offset is the location (code or data)
291/// of a Label that is only determinable during ELF emission.
292class RelocOffset final {
293 RelocOffset(const RelocOffset &) = delete;
294 RelocOffset &operator=(const RelocOffset &) = delete;
295
296public:
Jim Stichnoth3e324002016-03-08 16:18:40 -0800297 template <typename T> static RelocOffset *create(T *AllocOwner) {
298 return new (AllocOwner->template allocate<RelocOffset>()) RelocOffset();
John Porto27fddcc2016-02-02 15:06:09 -0800299 }
300
301 static RelocOffset *create(GlobalContext *Ctx, RelocOffsetT Value) {
302 return new (Ctx->allocate<RelocOffset>()) RelocOffset(Value);
303 }
304
John Porto6e8d3fa2016-02-04 10:35:20 -0800305 void setSubtract(bool Value) { Subtract = Value; }
John Porto27fddcc2016-02-02 15:06:09 -0800306 bool hasOffset() const { return HasOffset; }
307
308 RelocOffsetT getOffset() const {
309 assert(HasOffset);
310 return Offset;
311 }
312
313 void setOffset(const RelocOffsetT Value) {
314 assert(!HasOffset);
John Porto6e8d3fa2016-02-04 10:35:20 -0800315 if (Subtract) {
316 assert(Value != std::numeric_limits<RelocOffsetT>::lowest());
317 Offset = -Value;
318 } else {
319 Offset = Value;
320 }
John Porto27fddcc2016-02-02 15:06:09 -0800321 HasOffset = true;
322 }
323
324private:
325 RelocOffset() = default;
326 explicit RelocOffset(RelocOffsetT Offset) { setOffset(Offset); }
327
John Porto6e8d3fa2016-02-04 10:35:20 -0800328 bool Subtract = false;
John Porto27fddcc2016-02-02 15:06:09 -0800329 bool HasOffset = false;
330 RelocOffsetT Offset;
331};
332
Andrew Scull57e12682015-09-16 11:30:19 -0700333/// RelocatableTuple bundles the parameters that are used to construct an
334/// ConstantRelocatable. It is done this way so that ConstantRelocatable can fit
335/// into the global constant pool template mechanism.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700336class RelocatableTuple {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800337 RelocatableTuple() = delete;
Jim Stichnoth0795ba02014-10-01 14:23:01 -0700338 RelocatableTuple &operator=(const RelocatableTuple &) = delete;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700339
340public:
John Portoe82b5602016-02-24 15:58:55 -0800341 RelocatableTuple(const RelocOffsetT Offset,
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700342 const RelocOffsetArray &OffsetExpr, GlobalString Name)
Jim Stichnoth98ba0062016-03-07 09:26:22 -0800343 : Offset(Offset), OffsetExpr(OffsetExpr), Name(Name) {}
John Porto27fddcc2016-02-02 15:06:09 -0800344
John Portoe82b5602016-02-24 15:58:55 -0800345 RelocatableTuple(const RelocOffsetT Offset,
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700346 const RelocOffsetArray &OffsetExpr, GlobalString Name,
347 const std::string &EmitString)
John Portoe82b5602016-02-24 15:58:55 -0800348 : Offset(Offset), OffsetExpr(OffsetExpr), Name(Name),
Jim Stichnoth98ba0062016-03-07 09:26:22 -0800349 EmitString(EmitString) {}
John Portoe82b5602016-02-24 15:58:55 -0800350
Jim Stichnothd2cb4362014-11-20 11:24:42 -0800351 RelocatableTuple(const RelocatableTuple &) = default;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700352
John Portoe82b5602016-02-24 15:58:55 -0800353 const RelocOffsetT Offset;
John Porto27fddcc2016-02-02 15:06:09 -0800354 const RelocOffsetArray OffsetExpr;
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700355 const GlobalString Name;
356 const std::string EmitString;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700357};
358
Jim Stichnothd2cb4362014-11-20 11:24:42 -0800359bool operator==(const RelocatableTuple &A, const RelocatableTuple &B);
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700360
Andrew Scull57e12682015-09-16 11:30:19 -0700361/// ConstantRelocatable represents a symbolic constant combined with a fixed
362/// offset.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700363class ConstantRelocatable : public Constant {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800364 ConstantRelocatable() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -0700365 ConstantRelocatable(const ConstantRelocatable &) = delete;
366 ConstantRelocatable &operator=(const ConstantRelocatable &) = delete;
367
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700368public:
Jim Stichnoth3e324002016-03-08 16:18:40 -0800369 template <typename T>
370 static ConstantRelocatable *create(T *AllocOwner, Type Ty,
Jim Stichnothb36757e2015-10-05 13:55:11 -0700371 const RelocatableTuple &Tuple) {
Jim Stichnoth3e324002016-03-08 16:18:40 -0800372 return new (AllocOwner->template allocate<ConstantRelocatable>())
373 ConstantRelocatable(Ty, Tuple.Offset, Tuple.OffsetExpr, Tuple.Name,
374 Tuple.EmitString);
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700375 }
Jan Voungfe14fb82014-10-13 15:56:32 -0700376
John Porto27fddcc2016-02-02 15:06:09 -0800377 RelocOffsetT getOffset() const {
John Portoe82b5602016-02-24 15:58:55 -0800378 RelocOffsetT Ret = Offset;
John Porto27fddcc2016-02-02 15:06:09 -0800379 for (const auto *const OffsetReloc : OffsetExpr) {
John Portoe82b5602016-02-24 15:58:55 -0800380 Ret += OffsetReloc->getOffset();
John Porto27fddcc2016-02-02 15:06:09 -0800381 }
John Portoe82b5602016-02-24 15:58:55 -0800382 return Ret;
John Porto27fddcc2016-02-02 15:06:09 -0800383 }
384
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700385 const std::string &getEmitString() const { return EmitString; }
John Porto27fddcc2016-02-02 15:06:09 -0800386
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700387 GlobalString getName() const { return Name; }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700388 using Constant::emit;
Jan Voung76bb0be2015-05-14 09:26:19 -0700389 void emit(TargetLowering *Target) const final;
Jim Stichnoth8ff4b282016-01-04 15:39:06 -0800390 void emitWithoutPrefix(const TargetLowering *Target,
391 const char *Suffix = "") const;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700392 using Constant::dump;
Jim Stichnothb56c8f42014-09-26 09:28:46 -0700393 void dump(const Cfg *Func, Ostream &Str) const override;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700394
395 static bool classof(const Operand *Operand) {
396 OperandKind Kind = Operand->getKind();
397 return Kind == kConstRelocatable;
398 }
399
400private:
John Portoe82b5602016-02-24 15:58:55 -0800401 ConstantRelocatable(Type Ty, const RelocOffsetT Offset,
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700402 const RelocOffsetArray &OffsetExpr, GlobalString Name,
403 const std::string &EmitString)
John Portoe82b5602016-02-24 15:58:55 -0800404 : Constant(kConstRelocatable, Ty), Offset(Offset), OffsetExpr(OffsetExpr),
Jim Stichnoth98ba0062016-03-07 09:26:22 -0800405 Name(Name), EmitString(EmitString) {}
John Porto27fddcc2016-02-02 15:06:09 -0800406
John Portoe82b5602016-02-24 15:58:55 -0800407 const RelocOffsetT Offset; /// fixed, known offset to add
408 const RelocOffsetArray OffsetExpr; /// fixed, unknown offset to add
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700409 const GlobalString Name; /// optional for debug/dump
410 const std::string EmitString; /// optional for textual emission
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700411};
412
Andrew Scull57e12682015-09-16 11:30:19 -0700413/// ConstantUndef represents an unspecified bit pattern. Although it is legal to
414/// lower ConstantUndef to any value, backends should try to make code
415/// generation deterministic by lowering ConstantUndefs to 0.
Matt Walad8f4a7d2014-06-18 09:55:03 -0700416class ConstantUndef : public Constant {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800417 ConstantUndef() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -0700418 ConstantUndef(const ConstantUndef &) = delete;
419 ConstantUndef &operator=(const ConstantUndef &) = delete;
420
Matt Walad8f4a7d2014-06-18 09:55:03 -0700421public:
Jim Stichnothb36757e2015-10-05 13:55:11 -0700422 static ConstantUndef *create(GlobalContext *Ctx, Type Ty) {
Jim Stichnothb36757e2015-10-05 13:55:11 -0700423 return new (Ctx->allocate<ConstantUndef>()) ConstantUndef(Ty);
Matt Walad8f4a7d2014-06-18 09:55:03 -0700424 }
425
426 using Constant::emit;
Jan Voung76bb0be2015-05-14 09:26:19 -0700427 void emit(TargetLowering *Target) const final;
Jim Stichnoth2e8bfbb2014-09-16 10:16:00 -0700428 using Constant::dump;
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800429 void dump(const Cfg *, Ostream &Str) const override {
Jim Stichnoth20b71f52015-06-24 15:52:24 -0700430 if (BuildDefs::dump())
Karl Schimpfb6c96af2014-11-17 10:58:39 -0800431 Str << "undef";
432 }
Matt Walad8f4a7d2014-06-18 09:55:03 -0700433
434 static bool classof(const Operand *Operand) {
435 return Operand->getKind() == kConstUndef;
436 }
437
438private:
Jim Stichnothb36757e2015-10-05 13:55:11 -0700439 ConstantUndef(Type Ty) : Constant(kConstUndef, Ty) {}
Matt Walad8f4a7d2014-06-18 09:55:03 -0700440};
441
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800442/// RegNumT is for holding target-specific register numbers, plus the sentinel
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800443/// value if no register is assigned. Its public ctor allows direct use of enum
444/// values, such as RegNumT(Reg_eax), but not things like RegNumT(Reg_eax+1).
445/// This is to try to prevent inappropriate assumptions about enum ordering. If
446/// needed, the fromInt() method can be used, such as when a RegNumT is based
447/// on a bitvector index.
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800448class RegNumT {
449public:
450 using BaseType = uint32_t;
451 RegNumT() = default;
452 RegNumT(const RegNumT &) = default;
453 template <typename AnyEnum>
454 RegNumT(AnyEnum Value,
455 typename std::enable_if<std::is_enum<AnyEnum>::value, int>::type = 0)
456 : Value(Value) {
457 validate(Value);
458 }
459 RegNumT &operator=(const RegNumT &) = default;
460 operator unsigned() const { return Value; }
461 /// Asserts that the register is valid, i.e. not NoRegisterValue. Note that
462 /// the ctor already does the target-specific limit check.
463 void assertIsValid() const { assert(Value != NoRegisterValue); }
464 static RegNumT fromInt(BaseType Value) { return RegNumT(Value); }
465 /// Marks cases that inappropriately add/subtract RegNumT values, and
466 /// therefore need to be fixed because they make assumptions about register
467 /// enum value ordering. TODO(stichnot): Remove fixme() as soon as all
468 /// current uses are fixed/removed.
469 static RegNumT fixme(BaseType Value) { return RegNumT(Value); }
470 /// The target's staticInit() method should call setLimit() to register the
471 /// upper bound of allowable values.
472 static void setLimit(BaseType Value) {
473 // Make sure it's only called once.
474 assert(Limit == 0);
475 assert(Value != 0);
476 Limit = Value;
477 }
478 // Define NoRegisterValue as an enum value so that it can be used as an
479 // argument for the public ctor if desired.
480 enum { NoRegisterValue = std::numeric_limits<BaseType>::max() };
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800481
482 bool hasValue() const { return Value != NoRegisterValue; }
483 bool hasNoValue() const { return !hasValue(); }
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800484
485private:
486 BaseType Value = NoRegisterValue;
487 static BaseType Limit;
488 /// Private ctor called only by fromInt() and fixme().
489 RegNumT(BaseType Value) : Value(Value) { validate(Value); }
490 /// The ctor calls this to validate against the target-supplied limit.
491 static void validate(BaseType Value) {
492 (void)Value;
493 assert(Value == NoRegisterValue || Value < Limit);
494 }
495 /// Disallow operators that inappropriately make assumptions about register
496 /// enum value ordering.
497 bool operator<(const RegNumT &) = delete;
498 bool operator<=(const RegNumT &) = delete;
499 bool operator>(const RegNumT &) = delete;
500 bool operator>=(const RegNumT &) = delete;
501};
502
John Portoe82b5602016-02-24 15:58:55 -0800503/// RegNumBVIter wraps SmallBitVector so that instead of this pattern:
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800504///
505/// for (int i = V.find_first(); i != -1; i = V.find_next(i)) {
506/// RegNumT RegNum = RegNumT::fromInt(i);
507/// ...
508/// }
509///
510/// this cleaner pattern can be used:
511///
512/// for (RegNumT RegNum : RegNumBVIter(V)) {
513/// ...
514/// }
John Portoe82b5602016-02-24 15:58:55 -0800515template <class B> class RegNumBVIterImpl {
516 using T = B;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800517 static constexpr int Sentinel = -1;
John Portoe82b5602016-02-24 15:58:55 -0800518 RegNumBVIterImpl() = delete;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800519
520public:
521 class Iterator {
522 Iterator() = delete;
523 Iterator &operator=(const Iterator &) = delete;
524
525 public:
526 explicit Iterator(const T &V) : V(V), Current(V.find_first()) {}
527 Iterator(const T &V, int Value) : V(V), Current(Value) {}
528 Iterator(const Iterator &) = default;
529 RegNumT operator*() {
530 assert(Current != Sentinel);
531 return RegNumT::fromInt(Current);
532 }
533 Iterator &operator++() {
534 assert(Current != Sentinel);
535 Current = V.find_next(Current);
536 return *this;
537 }
538 bool operator!=(Iterator &Other) { return Current != Other.Current; }
539
540 private:
541 const T &V;
542 int Current;
543 };
544
John Portoe82b5602016-02-24 15:58:55 -0800545 RegNumBVIterImpl(const RegNumBVIterImpl &) = default;
546 RegNumBVIterImpl &operator=(const RegNumBVIterImpl &) = delete;
547 explicit RegNumBVIterImpl(const T &V) : V(V) {}
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800548 Iterator begin() { return Iterator(V); }
549 Iterator end() { return Iterator(V, Sentinel); }
550
551private:
552 const T &V;
553};
554
John Portoe82b5602016-02-24 15:58:55 -0800555template <class B> RegNumBVIterImpl<B> RegNumBVIter(const B &BV) {
556 return RegNumBVIterImpl<B>(BV);
557}
558
Andrew Scull57e12682015-09-16 11:30:19 -0700559/// RegWeight is a wrapper for a uint32_t weight value, with a special value
560/// that represents infinite weight, and an addWeight() method that ensures that
561/// W+infinity=infinity.
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700562class RegWeight {
563public:
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800564 using BaseType = uint32_t;
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700565 RegWeight() = default;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800566 explicit RegWeight(BaseType Weight) : Weight(Weight) {}
Jim Stichnoth7e571362015-01-09 11:43:26 -0800567 RegWeight(const RegWeight &) = default;
568 RegWeight &operator=(const RegWeight &) = default;
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800569 constexpr static BaseType Inf = ~0; /// Force regalloc to give a register
570 constexpr static BaseType Zero = 0; /// Force regalloc NOT to give a register
571 constexpr static BaseType Max = Inf - 1; /// Max natural weight.
572 void addWeight(BaseType Delta) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700573 if (Delta == Inf)
574 Weight = Inf;
575 else if (Weight != Inf)
Andrew Scullaa6c1092015-09-03 17:50:30 -0700576 if (Utils::add_overflow(Weight, Delta, &Weight) || Weight == Inf)
577 Weight = Max;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700578 }
579 void addWeight(const RegWeight &Other) { addWeight(Other.Weight); }
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800580 void setWeight(BaseType Val) { Weight = Val; }
581 BaseType getWeight() const { return Weight; }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700582
583private:
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800584 BaseType Weight = 0;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700585};
586Ostream &operator<<(Ostream &Str, const RegWeight &W);
587bool operator<(const RegWeight &A, const RegWeight &B);
588bool operator<=(const RegWeight &A, const RegWeight &B);
589bool operator==(const RegWeight &A, const RegWeight &B);
590
Andrew Scull57e12682015-09-16 11:30:19 -0700591/// LiveRange is a set of instruction number intervals representing a variable's
592/// live range. Generally there is one interval per basic block where the
593/// variable is live, but adjacent intervals get coalesced into a single
594/// interval.
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700595class LiveRange {
596public:
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700597 LiveRange() = default;
Andrew Scull57e12682015-09-16 11:30:19 -0700598 /// Special constructor for building a kill set. The advantage is that we can
599 /// reserve the right amount of space in advance.
Andrew Scull00741a02015-09-16 19:04:09 -0700600 explicit LiveRange(const CfgVector<InstNumberT> &Kills) {
Jim Stichnoth2a7fcbb2014-12-04 11:45:03 -0800601 Range.reserve(Kills.size());
602 for (InstNumberT I : Kills)
603 addSegment(I, I);
604 }
Jim Stichnoth87ff3a12014-11-14 10:27:29 -0800605 LiveRange(const LiveRange &) = default;
606 LiveRange &operator=(const LiveRange &) = default;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700607
608 void reset() {
609 Range.clear();
Jim Stichnoth037fa1d2014-10-07 11:09:33 -0700610 untrim();
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700611 }
612 void addSegment(InstNumberT Start, InstNumberT End);
613
614 bool endsBefore(const LiveRange &Other) const;
Jim Stichnoth037fa1d2014-10-07 11:09:33 -0700615 bool overlaps(const LiveRange &Other, bool UseTrimmed = false) const;
616 bool overlapsInst(InstNumberT OtherBegin, bool UseTrimmed = false) const;
Jim Stichnoth47752552014-10-13 17:15:08 -0700617 bool containsValue(InstNumberT Value, bool IsDest) const;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700618 bool isEmpty() const { return Range.empty(); }
619 InstNumberT getStart() const {
620 return Range.empty() ? -1 : Range.begin()->first;
621 }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700622 InstNumberT getEnd() const {
623 return Range.empty() ? -1 : Range.rbegin()->second;
624 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700625
Jim Stichnoth037fa1d2014-10-07 11:09:33 -0700626 void untrim() { TrimmedBegin = Range.begin(); }
627 void trim(InstNumberT Lower);
628
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700629 void dump(Ostream &Str) const;
630
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700631private:
Andrew Scull8072bae2015-09-14 16:01:26 -0700632 using RangeElementType = std::pair<InstNumberT, InstNumberT>;
Andrew Scull9612d322015-07-06 14:53:25 -0700633 /// RangeType is arena-allocated from the Cfg's allocator.
Andrew Scull00741a02015-09-16 19:04:09 -0700634 using RangeType = CfgVector<RangeElementType>;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700635 RangeType Range;
Andrew Scull57e12682015-09-16 11:30:19 -0700636 /// TrimmedBegin is an optimization for the overlaps() computation. Since the
637 /// linear-scan algorithm always calls it as overlaps(Cur) and Cur advances
638 /// monotonically according to live range start, we can optimize overlaps() by
639 /// ignoring all segments that end before the start of Cur's range. The
640 /// linear-scan code enables this by calling trim() on the ranges of interest
641 /// as Cur advances. Note that linear-scan also has to initialize TrimmedBegin
642 /// at the beginning by calling untrim().
Jim Stichnoth037fa1d2014-10-07 11:09:33 -0700643 RangeType::const_iterator TrimmedBegin;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700644};
645
646Ostream &operator<<(Ostream &Str, const LiveRange &L);
647
Andrew Scull9612d322015-07-06 14:53:25 -0700648/// Variable represents an operand that is register-allocated or
Andrew Scull57e12682015-09-16 11:30:19 -0700649/// stack-allocated. If it is register-allocated, it will ultimately have a
650/// non-negative RegNum field.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700651class Variable : public Operand {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800652 Variable() = delete;
Jim Stichnoth0795ba02014-10-01 14:23:01 -0700653 Variable(const Variable &) = delete;
654 Variable &operator=(const Variable &) = delete;
Jim Stichnoth800dab22014-09-20 12:25:02 -0700655
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700656 enum RegRequirement : uint8_t {
Andrew Scull11c9a322015-08-28 14:24:14 -0700657 RR_MayHaveRegister,
658 RR_MustHaveRegister,
659 RR_MustNotHaveRegister,
660 };
661
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700662public:
Jim Stichnoth9a04c072014-12-11 15:51:42 -0800663 static Variable *create(Cfg *Func, Type Ty, SizeT Index) {
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700664 return new (Func->allocate<Variable>())
665 Variable(Func, kVariable, Ty, Index);
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700666 }
667
668 SizeT getIndex() const { return Number; }
Jim Stichnotha91c3412016-04-05 15:31:43 -0700669 std::string getName() const {
670 if (Name.hasStdString())
671 return Name.toString();
672 return "__" + std::to_string(getIndex());
673 }
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700674 virtual void setName(const Cfg *Func, const std::string &NewName) {
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700675 if (NewName.empty())
676 return;
677 Name = VariableString::createWithString(Func, NewName);
Karl Schimpfc132b762014-09-11 09:43:47 -0700678 }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700679
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700680 bool getIsArg() const { return IsArgument; }
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700681 virtual void setIsArg(bool Val = true) { IsArgument = Val; }
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700682 bool getIsImplicitArg() const { return IsImplicitArgument; }
683 void setIsImplicitArg(bool Val = true) { IsImplicitArgument = Val; }
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700684
Jim Stichnoth47752552014-10-13 17:15:08 -0700685 void setIgnoreLiveness() { IgnoreLiveness = true; }
Jim Stichnothcc89c952016-03-31 11:55:23 -0700686 bool getIgnoreLiveness() const {
687 return IgnoreLiveness || IsRematerializable;
688 }
Jim Stichnoth47752552014-10-13 17:15:08 -0700689
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700690 int32_t getStackOffset() const { return StackOffset; }
691 void setStackOffset(int32_t Offset) { StackOffset = Offset; }
Jim Stichnoth238b4c12015-10-01 07:46:38 -0700692 /// Returns the variable's stack offset in symbolic form, to improve
693 /// readability in DecorateAsm mode.
Jim Stichnotha91c3412016-04-05 15:31:43 -0700694 std::string getSymbolicStackOffset() const {
Jim Stichnoth98ba0062016-03-07 09:26:22 -0800695 if (!BuildDefs::dump())
696 return "";
Jim Stichnotha91c3412016-04-05 15:31:43 -0700697 return "lv$" + getName();
Jim Stichnoth238b4c12015-10-01 07:46:38 -0700698 }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700699
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800700 bool hasReg() const { return getRegNum().hasValue(); }
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800701 RegNumT getRegNum() const { return RegNum; }
702 void setRegNum(RegNumT NewRegNum) {
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700703 // Regnum shouldn't be set more than once.
704 assert(!hasReg() || RegNum == NewRegNum);
705 RegNum = NewRegNum;
706 }
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800707 bool hasRegTmp() const { return getRegNumTmp().hasValue(); }
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800708 RegNumT getRegNumTmp() const { return RegNumTmp; }
709 void setRegNumTmp(RegNumT NewRegNum) { RegNumTmp = NewRegNum; }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700710
Andrew Scull11c9a322015-08-28 14:24:14 -0700711 RegWeight getWeight(const Cfg *Func) const;
712
713 void setMustHaveReg() { RegRequirement = RR_MustHaveRegister; }
714 bool mustHaveReg() const { return RegRequirement == RR_MustHaveRegister; }
715 void setMustNotHaveReg() { RegRequirement = RR_MustNotHaveRegister; }
716 bool mustNotHaveReg() const {
717 return RegRequirement == RR_MustNotHaveRegister;
718 }
Jim Stichnoth8aa39662016-02-10 11:20:30 -0800719 void setRematerializable(RegNumT NewRegNum, int32_t NewOffset) {
David Sehr4318a412015-11-11 15:01:55 -0800720 IsRematerializable = true;
721 setRegNum(NewRegNum);
722 setStackOffset(NewOffset);
723 setMustHaveReg();
724 }
725 bool isRematerializable() const { return IsRematerializable; }
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700726
Jim Stichnothc59288b2015-11-09 11:38:40 -0800727 void setRegClass(uint8_t RC) { RegisterClass = static_cast<RegClass>(RC); }
728 RegClass getRegClass() const { return RegisterClass; }
729
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700730 LiveRange &getLiveRange() { return Live; }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700731 const LiveRange &getLiveRange() const { return Live; }
732 void setLiveRange(const LiveRange &Range) { Live = Range; }
733 void resetLiveRange() { Live.reset(); }
Andrew Scull11c9a322015-08-28 14:24:14 -0700734 void addLiveRange(InstNumberT Start, InstNumberT End) {
Jim Stichnothf9df4522015-08-06 17:50:14 -0700735 assert(!getIgnoreLiveness());
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700736 Live.addSegment(Start, End);
Jim Stichnothc6ead202015-02-24 09:30:30 -0800737 }
Jim Stichnoth037fa1d2014-10-07 11:09:33 -0700738 void trimLiveRange(InstNumberT Start) { Live.trim(Start); }
739 void untrimLiveRange() { Live.untrim(); }
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700740 bool rangeEndsBefore(const Variable *Other) const {
741 return Live.endsBefore(Other->Live);
742 }
743 bool rangeOverlaps(const Variable *Other) const {
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700744 constexpr bool UseTrimmed = true;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700745 return Live.overlaps(Other->Live, UseTrimmed);
746 }
747 bool rangeOverlapsStart(const Variable *Other) const {
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700748 constexpr bool UseTrimmed = true;
Jim Stichnoth5ce0abb2014-10-15 10:16:54 -0700749 return Live.overlapsInst(Other->Live.getStart(), UseTrimmed);
750 }
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700751
Andrew Scull57e12682015-09-16 11:30:19 -0700752 /// Creates a temporary copy of the variable with a different type. Used
753 /// primarily for syntactic correctness of textual assembly emission. Note
754 /// that only basic information is copied, in particular not IsArgument,
755 /// IsImplicitArgument, IgnoreLiveness, RegNumTmp, Live, LoVar, HiVar,
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800756 /// VarsReal. If NewRegNum.hasValue(), then that register assignment is made
Jim Stichnoth5bff61c2015-10-28 09:26:00 -0700757 /// instead of copying the existing assignment.
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700758 const Variable *asType(const Cfg *Func, Type Ty, RegNumT NewRegNum) const;
Jim Stichnoth5bc2b1d2014-05-22 13:38:48 -0700759
Jim Stichnothb56c8f42014-09-26 09:28:46 -0700760 void emit(const Cfg *Func) const override;
Jim Stichnoth2e8bfbb2014-09-16 10:16:00 -0700761 using Operand::dump;
Jim Stichnothb56c8f42014-09-26 09:28:46 -0700762 void dump(const Cfg *Func, Ostream &Str) const override;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700763
Jan Voung28068ad2015-07-31 12:58:46 -0700764 /// Return reg num of base register, if different from stack/frame register.
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800765 virtual RegNumT getBaseRegNum() const { return RegNumT(); }
Jan Voung28068ad2015-07-31 12:58:46 -0700766
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700767 static bool classof(const Operand *Operand) {
Jim Stichnoth800dab22014-09-20 12:25:02 -0700768 OperandKind Kind = Operand->getKind();
Andrew Scull6ef79492015-09-09 15:50:42 -0700769 return Kind >= kVariable && Kind <= kVariable_Max;
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700770 }
771
Jim Stichnoth800dab22014-09-20 12:25:02 -0700772protected:
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700773 Variable(const Cfg *Func, OperandKind K, Type Ty, SizeT Index)
Jim Stichnothc59288b2015-11-09 11:38:40 -0800774 : Operand(K, Ty), Number(Index),
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700775 Name(VariableString::createWithoutString(Func)),
Jim Stichnothc59288b2015-11-09 11:38:40 -0800776 RegisterClass(static_cast<RegClass>(Ty)) {
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700777 Vars = VarsReal;
778 Vars[0] = this;
779 NumVars = 1;
780 }
Andrew Scull57e12682015-09-16 11:30:19 -0700781 /// Number is unique across all variables, and is used as a (bit)vector index
782 /// for liveness analysis.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700783 const SizeT Number;
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700784 VariableString Name;
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700785 bool IsArgument = false;
786 bool IsImplicitArgument = false;
Andrew Scull57e12682015-09-16 11:30:19 -0700787 /// IgnoreLiveness means that the variable should be ignored when constructing
788 /// and validating live ranges. This is usually reserved for the stack
Jim Stichnoth69660552015-09-18 06:41:02 -0700789 /// pointer and other physical registers specifically referenced by name.
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700790 bool IgnoreLiveness = false;
David Sehr4318a412015-11-11 15:01:55 -0800791 // If IsRematerializable, RegNum keeps track of which register (stack or frame
792 // pointer), and StackOffset is the known offset from that register.
793 bool IsRematerializable = false;
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700794 RegRequirement RegRequirement = RR_MayHaveRegister;
Jim Stichnothc59288b2015-11-09 11:38:40 -0800795 RegClass RegisterClass;
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800796 /// RegNum is the allocated register, (as long as RegNum.hasValue() is true).
797 RegNumT RegNum;
Andrew Scull9612d322015-07-06 14:53:25 -0700798 /// RegNumTmp is the tentative assignment during register allocation.
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800799 RegNumT RegNumTmp;
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700800 /// StackOffset is the canonical location on stack (only if
Reed Kotler5fa0a5f2016-02-15 20:01:24 -0800801 /// RegNum.hasNoValue() || IsArgument).
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700802 int32_t StackOffset = 0;
Jim Stichnothd97c7df2014-06-04 11:57:08 -0700803 LiveRange Live;
Andrew Scull57e12682015-09-16 11:30:19 -0700804 /// VarsReal (and Operand::Vars) are set up such that Vars[0] == this.
Jim Stichnothf7c9a142014-04-29 10:52:43 -0700805 Variable *VarsReal[1];
806};
807
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700808// Variable64On32 represents a 64-bit variable on a 32-bit architecture. In
809// this situation the variable must be split into a low and a high word.
810class Variable64On32 : public Variable {
811 Variable64On32() = delete;
812 Variable64On32(const Variable64On32 &) = delete;
813 Variable64On32 &operator=(const Variable64On32 &) = delete;
814
815public:
816 static Variable64On32 *create(Cfg *Func, Type Ty, SizeT Index) {
John Portoa83bfde2015-09-18 08:43:02 -0700817 return new (Func->allocate<Variable64On32>())
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700818 Variable64On32(Func, kVariable64On32, Ty, Index);
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700819 }
820
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700821 void setName(const Cfg *Func, const std::string &NewName) override {
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700822 Variable::setName(Func, NewName);
823 if (LoVar && HiVar) {
Jim Stichnotha91c3412016-04-05 15:31:43 -0700824 LoVar->setName(Func, getName() + "__lo");
825 HiVar->setName(Func, getName() + "__hi");
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700826 }
827 }
828
829 void setIsArg(bool Val = true) override {
830 Variable::setIsArg(Val);
831 if (LoVar && HiVar) {
832 LoVar->setIsArg(Val);
833 HiVar->setIsArg(Val);
834 }
835 }
836
837 Variable *getLo() const {
838 assert(LoVar != nullptr);
839 return LoVar;
840 }
841 Variable *getHi() const {
842 assert(HiVar != nullptr);
843 return HiVar;
844 }
845
846 void initHiLo(Cfg *Func) {
847 assert(LoVar == nullptr);
848 assert(HiVar == nullptr);
849 LoVar = Func->makeVariable(IceType_i32);
850 HiVar = Func->makeVariable(IceType_i32);
851 LoVar->setIsArg(getIsArg());
852 HiVar->setIsArg(getIsArg());
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700853 if (BuildDefs::dump()) {
Jim Stichnotha91c3412016-04-05 15:31:43 -0700854 LoVar->setName(Func, getName() + "__lo");
855 HiVar->setName(Func, getName() + "__hi");
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700856 }
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700857 }
858
859 static bool classof(const Operand *Operand) {
860 OperandKind Kind = Operand->getKind();
861 return Kind == kVariable64On32;
862 }
863
864protected:
Jim Stichnoth467ffe52016-03-29 15:01:06 -0700865 Variable64On32(const Cfg *Func, OperandKind K, Type Ty, SizeT Index)
866 : Variable(Func, K, Ty, Index) {
Andrew Scull6d47bcd2015-09-17 17:10:05 -0700867 assert(typeWidthInBytes(Ty) == 8);
868 }
869
870 Variable *LoVar = nullptr;
871 Variable *HiVar = nullptr;
872};
873
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700874enum MetadataKind {
Andrew Scull9612d322015-07-06 14:53:25 -0700875 VMK_Uses, /// Track only uses, not defs
876 VMK_SingleDefs, /// Track uses+defs, but only record single def
877 VMK_All /// Track uses+defs, including full def list
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700878};
Andrew Scull00741a02015-09-16 19:04:09 -0700879using InstDefList = CfgVector<const Inst *>;
Jim Stichnothad403532014-09-25 12:44:17 -0700880
Andrew Scull9612d322015-07-06 14:53:25 -0700881/// VariableTracking tracks the metadata for a single variable. It is
882/// only meant to be used internally by VariablesMetadata.
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700883class VariableTracking {
884public:
885 enum MultiDefState {
886 // TODO(stichnot): Consider using just a simple counter.
887 MDS_Unknown,
888 MDS_SingleDef,
Jim Stichnothad403532014-09-25 12:44:17 -0700889 MDS_MultiDefSingleBlock,
890 MDS_MultiDefMultiBlock
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700891 };
Jim Stichnothcc89c952016-03-31 11:55:23 -0700892 enum MultiBlockState {
893 MBS_Unknown, // Not yet initialized, so be conservative
894 MBS_NoUses, // Known to have no uses
895 MBS_SingleBlock, // All uses in are in a single block
896 MBS_MultiBlock // Several uses across several blocks
897 };
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700898 VariableTracking() = default;
Jim Stichnoth7e571362015-01-09 11:43:26 -0800899 VariableTracking(const VariableTracking &) = default;
Jim Stichnothcc89c952016-03-31 11:55:23 -0700900 VariableTracking &operator=(const VariableTracking &) = default;
901 VariableTracking(MultiBlockState MultiBlock) : MultiBlock(MultiBlock) {}
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700902 MultiDefState getMultiDef() const { return MultiDef; }
903 MultiBlockState getMultiBlock() const { return MultiBlock; }
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700904 const Inst *getFirstDefinitionSingleBlock() const;
Jim Stichnothad403532014-09-25 12:44:17 -0700905 const Inst *getSingleDefinition() const;
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700906 const Inst *getFirstDefinition() const;
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700907 const InstDefList &getLatterDefinitions() const { return Definitions; }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700908 CfgNode *getNode() const { return SingleUseNode; }
Andrew Scullaa6c1092015-09-03 17:50:30 -0700909 RegWeight getUseWeight() const { return UseWeight; }
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700910 void markUse(MetadataKind TrackingKind, const Inst *Instr, CfgNode *Node,
911 bool IsImplicit);
912 void markDef(MetadataKind TrackingKind, const Inst *Instr, CfgNode *Node);
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700913
914private:
Jim Stichnotheafb56c2015-06-22 10:35:22 -0700915 MultiDefState MultiDef = MDS_Unknown;
916 MultiBlockState MultiBlock = MBS_Unknown;
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700917 CfgNode *SingleUseNode = nullptr;
918 CfgNode *SingleDefNode = nullptr;
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700919 /// All definitions of the variable are collected in Definitions[] (except for
920 /// the earliest definition), in increasing order of instruction number.
Andrew Scull9612d322015-07-06 14:53:25 -0700921 InstDefList Definitions; /// Only used if Kind==VMK_All
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700922 const Inst *FirstOrSingleDefinition = nullptr;
Andrew Scullaa6c1092015-09-03 17:50:30 -0700923 RegWeight UseWeight;
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700924};
925
Andrew Scull11c9a322015-08-28 14:24:14 -0700926/// VariablesMetadata analyzes and summarizes the metadata for the complete set
927/// of Variables.
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700928class VariablesMetadata {
Jim Stichnothc6ead202015-02-24 09:30:30 -0800929 VariablesMetadata() = delete;
Jim Stichnoth7b451a92014-10-15 14:39:23 -0700930 VariablesMetadata(const VariablesMetadata &) = delete;
931 VariablesMetadata &operator=(const VariablesMetadata &) = delete;
932
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700933public:
Jim Stichnothc6ead202015-02-24 09:30:30 -0800934 explicit VariablesMetadata(const Cfg *Func) : Func(Func) {}
Andrew Scull57e12682015-09-16 11:30:19 -0700935 /// Initialize the state by traversing all instructions/variables in the CFG.
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700936 void init(MetadataKind TrackingKind);
Andrew Scull57e12682015-09-16 11:30:19 -0700937 /// Add a single node. This is called by init(), and can be called
Andrew Scull9612d322015-07-06 14:53:25 -0700938 /// incrementally from elsewhere, e.g. after edge-splitting.
Jim Stichnoth336f6c42014-10-30 15:01:31 -0700939 void addNode(CfgNode *Node);
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700940 MetadataKind getKind() const { return Kind; }
Andrew Scull57e12682015-09-16 11:30:19 -0700941 /// Returns whether the given Variable is tracked in this object. It should
Andrew Scull11c9a322015-08-28 14:24:14 -0700942 /// only return false if changes were made to the CFG after running init(), in
943 /// which case the state is stale and the results shouldn't be trusted (but it
944 /// may be OK e.g. for dumping).
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700945 bool isTracked(const Variable *Var) const {
946 return Var->getIndex() < Metadata.size();
947 }
Jim Stichnothad403532014-09-25 12:44:17 -0700948
Andrew Scull9612d322015-07-06 14:53:25 -0700949 /// Returns whether the given Variable has multiple definitions.
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700950 bool isMultiDef(const Variable *Var) const;
Andrew Scull57e12682015-09-16 11:30:19 -0700951 /// Returns the first definition instruction of the given Variable. This is
Andrew Scull11c9a322015-08-28 14:24:14 -0700952 /// only valid for variables whose definitions are all within the same block,
953 /// e.g. T after the lowered sequence "T=B; T+=C; A=T", for which
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700954 /// getFirstDefinitionSingleBlock(T) would return the "T=B" instruction. For
955 /// variables with definitions span multiple blocks, nullptr is returned.
956 const Inst *getFirstDefinitionSingleBlock(const Variable *Var) const;
Andrew Scull57e12682015-09-16 11:30:19 -0700957 /// Returns the definition instruction of the given Variable, when the
958 /// variable has exactly one definition. Otherwise, nullptr is returned.
Jim Stichnothad403532014-09-25 12:44:17 -0700959 const Inst *getSingleDefinition(const Variable *Var) const;
Jim Stichnoth48e3ae52015-10-01 13:33:35 -0700960 /// getFirstDefinition() and getLatterDefinitions() are used together to
961 /// return the complete set of instructions that define the given Variable,
962 /// regardless of whether the definitions are within the same block (in
963 /// contrast to getFirstDefinitionSingleBlock).
964 const Inst *getFirstDefinition(const Variable *Var) const;
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700965 const InstDefList &getLatterDefinitions(const Variable *Var) const;
Jim Stichnothad403532014-09-25 12:44:17 -0700966
Andrew Scull57e12682015-09-16 11:30:19 -0700967 /// Returns whether the given Variable is live across multiple blocks. Mainly,
968 /// this is used to partition Variables into single-block versus multi-block
969 /// sets for leveraging sparsity in liveness analysis, and for implementing
970 /// simple stack slot coalescing. As a special case, function arguments are
971 /// always considered multi-block because they are live coming into the entry
972 /// block.
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700973 bool isMultiBlock(const Variable *Var) const;
Jim Stichnothcc89c952016-03-31 11:55:23 -0700974 bool isSingleBlock(const Variable *Var) const;
Andrew Scull9612d322015-07-06 14:53:25 -0700975 /// Returns the node that the given Variable is used in, assuming
Andrew Scull57e12682015-09-16 11:30:19 -0700976 /// isMultiBlock() returns false. Otherwise, nullptr is returned.
Jim Stichnotha3f57b92015-07-30 12:46:04 -0700977 CfgNode *getLocalUseNode(const Variable *Var) const;
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700978
Andrew Scull11c9a322015-08-28 14:24:14 -0700979 /// Returns the total use weight computed as the sum of uses multiplied by a
980 /// loop nest depth factor for each use.
Andrew Scullaa6c1092015-09-03 17:50:30 -0700981 RegWeight getUseWeight(const Variable *Var) const;
Andrew Scull11c9a322015-08-28 14:24:14 -0700982
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700983private:
984 const Cfg *Func;
Jim Stichnoth877b04e2014-10-15 15:13:06 -0700985 MetadataKind Kind;
Andrew Scull00741a02015-09-16 19:04:09 -0700986 CfgVector<VariableTracking> Metadata;
Jim Stichnothad403532014-09-25 12:44:17 -0700987 const static InstDefList NoDefinitions;
Jim Stichnoth144cdce2014-09-22 16:02:59 -0700988};
989
Eric Holk80ee5b32016-05-06 14:28:04 -0700990/// BooleanVariable represents a variable that was the zero-extended result of a
991/// comparison. It maintains a pointer to its original i1 source so that the
992/// WASM frontend can avoid adding needless comparisons.
993class BooleanVariable : public Variable {
994 BooleanVariable() = delete;
995 BooleanVariable(const BooleanVariable &) = delete;
996 BooleanVariable &operator=(const BooleanVariable &) = delete;
997
998 BooleanVariable(const Cfg *Func, OperandKind K, Type Ty, SizeT Index)
999 : Variable(Func, K, Ty, Index) {}
1000
1001public:
1002 static BooleanVariable *create(Cfg *Func, Type Ty, SizeT Index) {
1003 return new (Func->allocate<BooleanVariable>())
1004 BooleanVariable(Func, kVariable, Ty, Index);
1005 }
1006
1007 virtual Variable *asBoolean() { return BoolSource; }
1008
1009 void setBoolSource(Variable *Src) { BoolSource = Src; }
1010
1011 static bool classof(const Operand *Operand) {
1012 return Operand->getKind() == kVariableBoolean;
1013 }
1014
1015private:
1016 Variable *BoolSource = nullptr;
1017};
1018
Jim Stichnothf7c9a142014-04-29 10:52:43 -07001019} // end of namespace Ice
1020
1021#endif // SUBZERO_SRC_ICEOPERAND_H