OpenVDB 14.0.0
Loading...
Searching...
No Matches
Value.h
Go to the documentation of this file.
1// Copyright Contributors to the OpenVDB Project
2// SPDX-License-Identifier: Apache-2.0
3
4/// @file codegen/Value.h
5///
6/// @authors Nick Avramoussis
7///
8/// @brief Intermediate representation of supported AX values
9///
10
11#ifndef OPENVDB_AX_CODEGEN_VALUE_HAS_BEEN_INCLUDED
12#define OPENVDB_AX_CODEGEN_VALUE_HAS_BEEN_INCLUDED
13
14#include "Types.h"
15#include "Utils.h"
16
17#include "../ast/AST.h"
18#include "../ast/Tokens.h"
19#include "../compiler/Logger.h"
20
21#include <openvdb/version.h>
22#include <openvdb/util/Assert.h>
23
24#include <llvm/IR/IRBuilder.h>
25#include <llvm/IR/LLVMContext.h>
26
27namespace openvdb {
29namespace OPENVDB_VERSION_NAME {
30
31namespace ax {
32namespace codegen {
33
34/// @brief Intermediate representation wrapper for supported value types in AX
35/// as immutable instances.
36///@details This class allows you to generate LLVM IR for common operations
37/// supported by the AX grammar whilst abstracting away a lot of the
38/// complexity of the underlying LLVM state. This class is not meant as a
39/// definitive representation of all possible LLVM IR instructions that can
40/// be emitted, more as a strict helper translation layer for some supported
41/// AX instructions to LLVM IR. More generally, this is intended to be used
42/// for all arithmetic operations and less so for program control flow
43/// (branches, loops, etc). Importantly, this class abstracts away the
44/// concept of ptr/loaded instructions. That is, users of this API usually do
45/// not need to worry about explicitly loading or querying the state of LLVM
46/// IR allocations when calling methods. Instances of Value types also ensure
47/// that the required underlying type information is retained, necessary from
48/// LLVM 15 onwards (due to the introduction of LLVM's opaque ptr changes).
49///
50/// The subset of possible types this class supports are
51/// - void types (for function returns)
52/// - AX scalar values (bool, ints, floats)
53/// - AX array values (element types of ints or floats)
54/// - AX string values
55///
56/// Note that a Value can have a variety of arithmetic type/precision states.
57/// The API of this class does not guaranteed compatibility between all
58/// states. Some failure cases may report a log message and return
59/// Value::Invalid() or generate invalid IR/result in undefined behaviour if
60/// the inputs are not correct. Refer to individual API methods for more
61/// details.
63{
64public:
65 /// @brief Create a Value with a provided underlying type
66 /// @warning This constructor assumes that the underlying type is correct.
67 /// This cannot be asserted from LLVM 15 onwards. This should be used
68 /// sparingly and currently only exists to support some holes in the
69 /// compute generator. This constructor should eventually be removed as
70 /// these get closed, in favour of the static create/alloc methods.
71 Value(llvm::Value* val, llvm::Type* utype)
72 : mVal(val)
73 , mUType(utype) {
74 OPENVDB_ASSERT((!mVal && !mUType) || bool(*this));
75 }
76 /// @brief Initialize from a constant value
77 explicit Value(llvm::Constant* costant)
78 : Value(static_cast<llvm::Value*>(costant), costant->getType()) {}
79
80 Value(const Value&) = default;
81 Value(Value&&) = default;
82 Value& operator=(const Value&) = default;
83 Value& operator=(Value&&) = default;
84
85 /// @brief Return an invalid Value. This is used to represent various fail
86 /// cases. Note that the operator bool(Value) will return false in for
87 /// Value::Invalid
88 static Value Invalid() { return Value(nullptr, nullptr); }
89
90 /// @brief Create an arithmetic literal
91 template <typename ValueType>
92 static Value Create(llvm::LLVMContext& C, const ValueType& value)
93 {
94 return Value(LLVMType<ValueType>::get(C, value),
96 }
97
98 /// @brief Create a value that represents a return value from a function.
99 /// Really only intended to be used by the function framework. If ret is
100 /// not provided, a void return is created.
101 static Value Return(llvm::IRBuilder<>& B, Value* ret = nullptr)
102 {
103 return ret ? Value(B.CreateRet(ret->GetValue()), B.getVoidTy()) :
104 Value(B.CreateRetVoid(), B.getVoidTy());
105 }
106
107 /// @brief Return true if the underlying type held by utype is supported
108 /// via the interface of this Value class
109 static bool Supports(llvm::Type* utype)
110 {
111 llvm::Type* strtype = LLVMType<codegen::String>::get(utype->getContext());
112 return utype->isVoidTy() ||
113 utype->isIntegerTy() ||
114 utype->isFloatingPointTy() ||
115 utype == strtype ||
116 (utype->isArrayTy() &&
117 (utype->getArrayElementType()->isIntegerTy() ||
118 utype->getArrayElementType()->isFloatingPointTy()));
119 }
120
121 /// @brief Emit IR inserting an allocation at the front of the BasicBlock
122 /// pointed to by the provided IRBuilder. The type is expected to be a
123 /// supported utype.
124 static Value Alloc(llvm::IRBuilder<>& B, llvm::Type* type, llvm::Value* size = nullptr)
125 {
127 // Create the allocation at the start of the function block
128 llvm::Function* parent = B.GetInsertBlock()->getParent();
129 OPENVDB_ASSERT(parent && !parent->empty());
130 auto IP = B.saveIP();
131 llvm::BasicBlock& block = parent->front();
132 if (block.empty()) B.SetInsertPoint(&block);
133 else B.SetInsertPoint(&(block.front()));
134 llvm::Value* result = B.CreateAlloca(type, size);
135
136 /// @note Strings need to be initialised correctly when they are
137 /// created. We alloc them at the start of the function but
138 /// strings in branches may not ever be set to anything. If
139 /// we don't init these correctly, the clearup frees will
140 /// try and free uninitialised memory
141 llvm::StructType* strtype = LLVMType<codegen::String>::get(B.getContext());
142 if (type == strtype) {
143 llvm::Value* cptr = B.CreateStructGEP(strtype, result, 0); // char**
144 llvm::Value* sso = B.CreateStructGEP(strtype, result, 1); // char[]*
145 llvm::Value* sso_load = B.CreateConstInBoundsGEP2_64(strtype->getTypeAtIndex(1), sso, 0, 0); // char[]
146 llvm::Value* len = B.CreateStructGEP(strtype, result, 2);
147 B.CreateStore(sso_load, cptr); // this->ptr = this->SSO;
148 B.CreateStore(B.getInt64(0), len);
149 }
150 B.restoreIP(IP);
151 return Value(result, type);
152 }
153
154 /// @brief Emit IR to create an array from a set of scalar values. Will
155 /// generate invalid IR if the values are not all scalar or are of
156 /// different precision. values cannot be empty.
157 static Value ScalarsToArray(llvm::IRBuilder<>& B, const std::vector<Value>& values)
158 {
159 OPENVDB_ASSERT(!values.empty());
160
161 llvm::Type* type = values.front().GetUnderlyingType();
162 llvm::Type* arrayType = llvm::ArrayType::get(type, values.size());
163 Value array = Value::Alloc(B, arrayType);
164
165 size_t idx = 0;
166 for (const Value& value : values)
167 {
168 OPENVDB_ASSERT(value);
169 OPENVDB_ASSERT(value.IsScalar());
170 OPENVDB_ASSERT(value.GetUnderlyingType() == type);
171 Value element = array.GetArrayElement(B, idx++);
172 B.CreateStore(value.GetValue(), element.GetValue());
173 }
174
175 return array;
176 }
177
178 /// @brief Create a new zero scalar Value using the underlying scalar
179 /// precision of this Value. Does not generate IR, however will return
180 /// an invalid constant if this Value is a string
181 Value Zero() const
182 {
184 }
185
186 /// @brief Create a new one scalar Value using the underlying scalar
187 /// precision of this Value. Does not generate IR, however will return
188 /// an invalid constant if this Value is a string
189 Value One() const
190 {
192 }
193
194 ///////////////////////////////////////////////////////////////////////////
195 ///////////////////////////////////////////////////////////////////////////
196
197 /// @brief Check if this Value contains an active underlying llvm
198 /// Value/Type. When asserts are enabled. This method strictly checks all
199 /// possible valid combination types of a Value.
200 operator bool() const;
201
202 /// @brief See bool operator
203 bool operator!() const { return !bool(*this); }
204
205 /// @brief Return true if this value represents a void type. This is
206 /// typically only possible for void function returns
207 /// @note Void types are only ever explicitly void, never pointers to void
208 bool IsVoid() const
209 {
210 OPENVDB_ASSERT(*this);
211 return mUType->isVoidTy();
212 }
213
214 /// @brief Return true if the underlying type is a bool type
215 /// @note A bool's underlying state can be either as a pointer or
216 /// loaded. This method returns true in both instances if the underlying
217 /// type is a bool.
218 bool IsBool() const
219 {
220 OPENVDB_ASSERT(*this);
221 return mUType->isIntegerTy(1);
222 }
223
224 /// @brief Return true if the underlying type is a scalar type (bool, int
225 /// or float).
226 /// @note A scalar's underlying state can be either as a pointer or
227 /// loaded. This method returns true in both instances if the underlying
228 /// type is a scalar.
229 bool IsScalar() const
230 {
231 OPENVDB_ASSERT(*this);
232 return (mUType->isIntegerTy() || mUType->isFloatingPointTy());
233 }
234
235 /// @brief Return true if the underlying type is an integer type
236 /// @note A integer's underlying state can be either as a pointer or
237 /// loaded. This method returns true in both instances if the underlying
238 /// type is a integer.
239 bool IsInteger() const
240 {
241 OPENVDB_ASSERT(*this);
242 return mUType->isIntegerTy();
243 }
244
245 /// @brief Return true if the underlying type is an floating point type
246 /// (float or double).
247 /// @note A float's underlying state can be either as a pointer or
248 /// loaded. This method returns true in both instances if the underlying
249 /// type is a float/double.
250 bool IsFloat() const
251 {
252 OPENVDB_ASSERT(*this);
253 return mUType->isFloatingPointTy();
254 }
255
256 /// @brief Return true if the underlying type is an array type
257 /// @note An array type's state is only ever a pointer to an array
258 /// allocation
259 bool IsArray() const
260 {
261 OPENVDB_ASSERT(*this);
262 return mUType->isArrayTy();
263 }
264
265 /// @brief Return true if the underlying type is an vector 2/3/4 type
266 /// @note An vector type's state is only ever a pointer to a vector
267 /// allocation
268 bool IsVector() const
269 {
270 OPENVDB_ASSERT(*this);
271 return mUType->isArrayTy() && !this->IsMatrix();
272 }
273
274 /// @brief Return true if the underlying type is an matrix 3/4 type
275 /// @note An matrix type's state is only ever a pointer to a matrix
276 /// allocation
277 bool IsMatrix() const
278 {
279 OPENVDB_ASSERT(*this);
280 return mUType->isArrayTy() &&
281 // @todo This is dumb, add type-metadata for this
282 (this->GetArrayNumElements() == 9 || this->GetArrayNumElements() == 16);
283 }
284
285 /// @brief Return true if the underlying type is a string type
286 /// @note An string type's state is only ever a pointer to a string
287 /// allocation
288 bool IsString() const
289 {
290 OPENVDB_ASSERT(*this);
291 return mUType == LLVMType<codegen::String>::get(mUType->getContext());
292 }
293
294 /// @brief Return true if this Value is a pointer type
295 bool IsPtr() const
296 {
297 OPENVDB_ASSERT(*this);
298 return mVal->getType()->isPointerTy();
299 }
300
301 /// @brief Return true if this Value is a constant
302 bool IsConstant() const
303 {
304 return bool(llvm::dyn_cast<llvm::Constant>(this->GetValue()));
305 }
306
307 /// @brief Return the number of elements in this array type
308 size_t GetArrayNumElements() const
309 {
310 OPENVDB_ASSERT(this->IsArray());
311 return mUType->getArrayNumElements();
312 }
313
314 ///////////////////////////////////////////////////////////////////////////
315 ///////////////////////////////////////////////////////////////////////////
316
317 // The following method generate IR and return new Value instances
318
319 /// @brief Emit IR to check whether this value is NaN. Only works on Float
320 /// types and will generate invalid IR if this Value is not a Float
321 /// instance.
322 Value IsNan(llvm::IRBuilder<>& B) const
323 {
324 OPENVDB_ASSERT(*this);
325 OPENVDB_ASSERT(this->IsFloat());
326 Value self = this->LoadIfPtr(B);
327 llvm::Value* result = B.CreateFCmpUNO(self.GetValue(), self.GetValue());
328 return Value(result, result->getType());
329 }
330
331 /// @brief Emit IR to load the current value. Not typically required to
332 /// call directly. Will generate invalid IR if this Value is not a Ptr.
333 /// @warning Should only ever be called for ptrs to scalar types
334 Value Load(llvm::IRBuilder<>& B) const
335 {
336 OPENVDB_ASSERT(*this);
337 OPENVDB_ASSERT(this->IsPtr());
338 OPENVDB_ASSERT(this->IsScalar()); // Should only be loading scalars
339 return Value(B.CreateLoad(mUType, mVal), mUType);
340 }
341
342 /// @brief Emit IR to load the current value if it is a ptr. Not typically
343 /// required to call directly.
344 /// @warning Should only ever be called for ptrs to scalar types
345 Value LoadIfPtr(llvm::IRBuilder<>& B) const
346 {
347 OPENVDB_ASSERT(*this);
348 OPENVDB_ASSERT(this->IsScalar()); // Should only be loading scalars
349 return this->IsPtr() ? this->Load(B) : *this;
350 }
351
352 /// @brief Emit IR to return a scalar at the provided index from this
353 /// array value. Will generate invalid IR if this Value is not an array
354 /// or if idx is not an integer.
355 Value GetArrayElement(llvm::IRBuilder<>& B, Value idx) const
356 {
357 OPENVDB_ASSERT(*this);
358 OPENVDB_ASSERT(this->IsArray());
360 idx = idx.LoadIfPtr(B);
361 if (this->IsPtr()) {
362 Value zero = idx.Zero(); // same int precision as idx
363 return Value(B.CreateInBoundsGEP(mUType, mVal, {zero.GetValue(), idx.GetValue()}), mUType->getArrayElementType());
364 }
365 else {
366 OPENVDB_ASSERT(this->IsConstant());
367 return Value(B.CreateInBoundsGEP(mUType, mVal, {idx.GetValue()}), mUType->getArrayElementType());
368 }
369 }
370
371 /// @brief Emit IR to return a scalar at the provided index from this
372 /// array value. Will generate invalid IR if this Value is not an array.
373 Value GetArrayElement(llvm::IRBuilder<>& B, uint64_t idx) const
374 {
375 OPENVDB_ASSERT(*this);
376 OPENVDB_ASSERT(this->IsArray());
377 OPENVDB_ASSERT(idx < this->GetArrayNumElements());
378 if (this->IsPtr()) {
379 return Value(B.CreateConstInBoundsGEP2_64(mUType, mVal, uint64_t(0), idx), mUType->getArrayElementType());
380 }
381 else {
382 OPENVDB_ASSERT(this->IsConstant());
383 return Value(B.CreateConstInBoundsGEP1_64(mUType, mVal, idx), mUType->getArrayElementType());
384 }
385 }
386
387 /// @brief Emit IR to extract scalar values from the elements in this
388 /// array and populate the provided vector with them. The scalars are
389 /// additionally loaded if load is true. Will generate invalid IR if this
390 /// is not an array
391 void ArrayToScalars(llvm::IRBuilder<>& B,
392 std::vector<Value>& elements,
393 const bool load = false) const
394 {
395 OPENVDB_ASSERT(*this);
396 OPENVDB_ASSERT(this->IsArray());
397
398 const size_t size = this->GetArrayNumElements();
399 elements.reserve(size);
400
401 for (size_t i = 0; i < size; ++i)
402 {
403 Value elem = this->GetArrayElement(B, i);
404 if (load) elem = elem.Load(B);
405 OPENVDB_ASSERT(elem);
406 elements.emplace_back(elem);
407 }
408
409 OPENVDB_ASSERT(!elements.empty());
410 }
411
412 /// @brief Emit IR to broadcast this scalar to a new array. Will generated
413 /// invalid IR if this is not a scalar or if size is zero.
414 /// @warning This fills the array with the current scalar value. It does
415 /// NOT do scalar->matrix promotion.
416 Value ScalarToArray(llvm::IRBuilder<>& B, size_t size) const
417 {
418 OPENVDB_ASSERT(*this);
419 OPENVDB_ASSERT_MESSAGE(this->IsScalar(), "value type is not a scalar type");
420 Value scalar = this->LoadIfPtr(B);
421
422 llvm::Type* type = llvm::ArrayType::get(scalar.GetUnderlyingType(), size);
423 Value array = Value::Alloc(B, type);
424 for (size_t i = 0; i < size; ++i) {
425 Value element = array.GetArrayElement(B, i);
426 B.CreateStore(scalar.GetValue(), element.GetValue());
427 }
428 return array;
429 }
430
431 /// @brief Emit IR to create a new 3x3 matrix from this scalar value,
432 /// adhering to scalar->matrix promotion rules. Will generate invalid IR
433 /// if this is not a scalar value.
434 Value ScalarToIdentMatrix3(llvm::IRBuilder<>& B) const
435 {
436 return this->ScalarToIdentMatrixN<3>(B);
437 }
438
439 /// @brief Emit IR to create a new 4x4 matrix from this scalar value,
440 /// adhering to scalar->matrix promotion rules. Will generate invalid IR
441 /// if this is not a scalar value.
442 Value ScalarToIdentMatrix4(llvm::IRBuilder<>& B) const
443 {
444 return this->ScalarToIdentMatrixN<4>(B);
445 }
446
447 /// @brief Emit IR to perform standard boolean comparison on this scalar
448 /// i.e. bool(scalar) or bool(scalar == 0). Returns a Value of type bool.
449 /// Will return Value::Invalid() if this is not a bool/int/float.
450 Value ScalarBoolComparison(llvm::IRBuilder<>& B) const;
451
452 /// @brief Emit IR to select a value based on this boolean scalar value.
453 /// Will generate invalid IR if this is not a boolean value, or if
454 /// trueval and falseval have different types.
455 Value Select(llvm::IRBuilder<>& B, const Value& trueval, const Value& falseval) const;
456
457 /// @brief Emit IR to cast this scalar or array to a new value of the
458 /// provided scalar precision. Returns a new value of the same class type
459 /// (scalar or array) but with a new precision. Will generate invalid IR
460 /// if the precision is not an integer or floating point precision type.
461 /// If this is not an array or scalar, no IR is emitted and
462 /// Value::Invalid() is returned. Additionally, if the provided precision
463 /// is the same as this scalar/array's underlying precision, no IR is
464 /// emitted and no new value is created.
465 Value CastToPrecision(llvm::IRBuilder<>& B, llvm::Type* precision) const;
466
467 ///////////////////////////////////////////////////////////////////////////
468 ///////////////////////////////////////////////////////////////////////////
469
470 // Unary IR emission
471
472 /// @brief Emit IR to create a unary not instruction on this scalar or
473 /// integer array (i.e. !value). If the value is not a int/float/integer
474 /// array, no IR is emitted, a warning is logged (if a logger is provided)
475 /// and Value::Invalid is returned.
476 Value Not(llvm::IRBuilder<>& B, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
477
478 /// @brief Emit IR to create a unary not instruction on this integer or
479 /// integer array (i.e. ~value). If the value is not a int/integer array,
480 /// no IR is emitted, a warning is logged (if a logger is provided) and
481 /// Value::Invalid is returned.
482 Value BitNot(llvm::IRBuilder<>& B, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
483
484 /// @brief Emit IR to create a unary not instruction on this scalar or
485 /// array (i.e. -value). If the value is not a int/float/array, no IR is
486 /// is emitted, a warning is logged (if a logger is provided) and
487 /// Value::Invalid is returned.
488 Value Negate(llvm::IRBuilder<>& B, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
489
490 /// @brief Emit IR to increment this scalar (i.e. value + 1). Will
491 /// return Value::Invalid() and report a message to a logger (if provided)
492 /// if this is not an integer (non-bool) or float scalar.
493 Value Increment(llvm::IRBuilder<>& B, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
494
495 /// @brief Emit IR to increment this scalar (i.e. value - 1). Will
496 /// return Value::Invalid() and report a message to a logger (if provided)
497 /// if this is not an integer (non-bool) or float scalar.
498 Value Decrement(llvm::IRBuilder<>& B, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
499
500 ///////////////////////////////////////////////////////////////////////////
501 ///////////////////////////////////////////////////////////////////////////
502
503 /// @brief Emit IR to perform a binary operation on this LHS value and a
504 /// provided RHS value. If the operation is not a valid binary operation,
505 /// Value::Invalid() is returned. Defer to the explicit binary methods on
506 /// this class for more details.
507 /// @note For all methods, performing type promotion/casting where necessary
508 /// or return Value::Invalid() on incompatible inputs and report a
509 /// message to the log, if provided.
510 Value Binary(llvm::IRBuilder<>& B,
511 Value rhs,
513 Logger* log = nullptr,
514 const ax::ast::Node* node = nullptr) const
515 {
516 OPENVDB_ASSERT(*this);
517 OPENVDB_ASSERT(rhs);
518 switch (op)
519 {
520 case ast::tokens::OperatorToken::PLUS : return this->Add(B, rhs, log, node);
521 case ast::tokens::OperatorToken::MINUS : return this->Subtract(B, rhs, log, node);
522 case ast::tokens::OperatorToken::MULTIPLY : return this->Multiply(B, rhs, log, node);
523 case ast::tokens::OperatorToken::DIVIDE : return this->Divide(B, rhs, log, node);
524 case ast::tokens::OperatorToken::MODULO : return this->Modulo(B, rhs, log, node);
525 case ast::tokens::OperatorToken::EQUALSEQUALS : return this->Equals(B, rhs, log, node);
526 case ast::tokens::OperatorToken::NOTEQUALS : return this->NotEquals(B, rhs, log, node);
527 case ast::tokens::OperatorToken::MORETHAN : return this->GreaterThan(B, rhs, log, node);
528 case ast::tokens::OperatorToken::MORETHANOREQUAL : return this->GreaterThanEquals(B, rhs, log, node);
529 case ast::tokens::OperatorToken::LESSTHAN : return this->LessThan(B, rhs, log, node);
530 case ast::tokens::OperatorToken::LESSTHANOREQUAL : return this->LessThanEquals(B, rhs, log, node);
531 case ast::tokens::OperatorToken::SHIFTLEFT : return this->ShiftLeft(B, rhs, log, node);
532 case ast::tokens::OperatorToken::SHIFTRIGHT : return this->ShiftRight(B, rhs, log, node);
533 case ast::tokens::OperatorToken::BITAND : return this->BitAnd(B, rhs, log, node);
534 case ast::tokens::OperatorToken::BITOR : return this->BitOr(B, rhs, log, node);
535 case ast::tokens::OperatorToken::BITXOR : return this->BitXor(B, rhs, log, node);
536 default: return Value::Invalid();
537 }
538 }
539
540 // Binary arithmetic IR emission.
541
542 /// @brief Emit IR to perform a && operation on two scalars. Assumes both
543 /// inputs are scalars (this checking is currently done in the
544 /// ComputeGenerator) and will cause undefined behaviour if they are not.
545 /// @warning This does not perform short circuiting. See:
546 /// ComputeGenerator::visit(const ast::BinaryOperator*)
547 Value And(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
548 {
549 OPENVDB_ASSERT(*this);
550 OPENVDB_ASSERT(rhs);
551 OPENVDB_ASSERT(this->IsScalar());
553 Value lhs = *this;
554 lhs = lhs.ScalarBoolComparison(B);
555 rhs = rhs.ScalarBoolComparison(B);
556 return this->TrivialBinary(B, rhs, ast::tokens::AND, log, node);
557 }
558
559 /// @brief Emit IR to perform a || operation on two scalars. Assumes both
560 /// inputs are scalars (this checking is currently done in the
561 /// ComputeGenerator) and will cause undefined behaviour if they are not.
562 /// @warning This does not perform short circuiting. See:
563 /// ComputeGenerator::visit(const ast::BinaryOperator*)
564 Value Or(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
565 {
566 OPENVDB_ASSERT(*this);
567 OPENVDB_ASSERT(rhs);
568 OPENVDB_ASSERT(this->IsScalar());
570 Value lhs = *this;
571 lhs = lhs.ScalarBoolComparison(B);
572 rhs = rhs.ScalarBoolComparison(B);
573 return this->TrivialBinary(B, rhs, ast::tokens::OR, log, node);
574 }
575
576 /// @brief Emit IR to perform a + operation on two values
577 Value Add(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
578
579 /// @brief Emit IR to perform a - operation on two values
580 Value Subtract(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
581
582 /// @brief Emit IR to perform a * operation on two values
583 Value Multiply(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
584
585 /// @brief Emit IR to perform a / operation on two values If the denominator is constant and
586 /// zero, returns Value::Invalid()
587 Value Divide(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
588
589 /// @brief Emit IR to perform a FLOORED % operation on two values
590 Value Modulo(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
591
592 /// @brief Emit IR to perform a TRUNCATED % operation on two values
593 Value TruncatedModulo(llvm::IRBuilder<>& B, Value rhs) const;
594
595 // Binary Relational IR emission
596
597 /// @brief Emit IR to perform a == operation on two values
598 Value Equals(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
599
600 /// @brief Emit IR to perform a != operation on two values
601 Value NotEquals(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
602
603 /// @brief Emit IR to perform a > operation on two values
604 Value GreaterThan(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
605 {
606 return this->Relational(B, rhs, ast::tokens::MORETHAN, log, node);
607 }
608
609 /// @brief Emit IR to perform a >= operation on two values
610 Value GreaterThanEquals(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
611 {
612 return this->Relational(B, rhs, ast::tokens::MORETHANOREQUAL, log, node);
613 }
614
615 /// @brief Emit IR to perform a < operation on two values
616 Value LessThan(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
617 {
618 return this->Relational(B, rhs, ast::tokens::LESSTHAN, log, node);
619 }
620
621 /// @brief Emit IR to perform a <= operation on two values
622 Value LessThanEquals(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
623 {
624 return this->Relational(B, rhs, ast::tokens::LESSTHANOREQUAL, log, node);
625 }
626
627 // Binary Bitwise IR emission
628
629 /// @brief Emit IR to perform a << operation. Both values must be integers
630 Value ShiftLeft(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
631 {
632 return this->Bitwise(B, rhs, ast::tokens::SHIFTLEFT, log, node);
633 }
634
635 /// @brief Emit IR to perform a >> operation. Both values must be integers
636 Value ShiftRight(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
637 {
638 return this->Bitwise(B, rhs, ast::tokens::SHIFTRIGHT, log, node);
639 }
640
641 /// @brief Emit IR to perform a & operation. Both values must be integers
642 Value BitAnd(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
643 {
644 return this->Bitwise(B, rhs, ast::tokens::BITAND, log, node);
645 }
646
647 /// @brief Emit IR to perform a | operation. Both values must be integers
648 Value BitOr(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
649 {
650 return this->Bitwise(B, rhs, ast::tokens::BITOR, log, node);
651 }
652
653 /// @brief Emit IR to perform a ^ operation. Both values must be integers
654 Value BitXor(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const
655 {
656 return this->Bitwise(B, rhs, ast::tokens::BITXOR, log, node);
657 }
658
659 ///////////////////////////////////////////////////////////////////////////
660 ///////////////////////////////////////////////////////////////////////////
661
662 /// @brief Emit IR to assign the provided rhs to this value.
663 Value Assign(llvm::IRBuilder<>& B, Value rhs, Logger* log = nullptr, const ax::ast::Node* node = nullptr) const;
664
665 ///////////////////////////////////////////////////////////////////////////
666 ///////////////////////////////////////////////////////////////////////////
667
668 /// @brief Dump this value/type to llvm::errs
669 void Print() const;
670
671 /// @brief Access the underlying llvm Value
672 llvm::Value* GetValue() const { return mVal; }
673
674 /// @brief Access the underlying llvm Type
675 llvm::Type* GetUnderlyingType() const { return mUType; }
676
677 /// @brief Access the underlying scalar type. This method assumes the
678 /// current value is a scalar or array
679 llvm::Type* GetUnderlyingScalarType() const
680 {
681 OPENVDB_ASSERT(*this);
682 OPENVDB_ASSERT(this->IsScalar() || this->IsArray());
683 return mUType->isArrayTy() ? mUType->getArrayElementType() : mUType;
684 }
685
686private:
687 template <size_t Dim>
688 Value ScalarToIdentMatrixN(llvm::IRBuilder<>& B) const
689 {
690 static_assert(Dim == 3 || Dim == 4);
691 OPENVDB_ASSERT(*this);
692 OPENVDB_ASSERT_MESSAGE(this->IsScalar(), "value type is not a scalar type");
693
694 Value scalar = this->LoadIfPtr(B);
695 llvm::Type* type = llvm::ArrayType::get(scalar.GetUnderlyingType(), Dim*Dim);
696 Value array = Value::Alloc(B, type);
697 Value zero = scalar.Zero();
698
699 for (size_t i = 0; i < Dim*Dim; ++i) {
700 const Value& m = ((i % (Dim+1) == 0) ? scalar : zero);
701 llvm::Value* element = array.GetArrayElement(B, i).GetValue();
702 B.CreateStore(m.GetValue(), element);
703 }
704
705 return array;
706 }
707
708 Value TrivialBinary(llvm::IRBuilder<>& B,
709 Value rhs,
710 const ast::tokens::OperatorToken& op,
711 Logger* log,
712 const ax::ast::Node* node) const;
713
714 Value Bitwise(llvm::IRBuilder<>& B,
715 Value rhs,
716 const ast::tokens::OperatorToken& op,
717 Logger* log,
718 const ax::ast::Node* node) const;
719
720 Value Relational(llvm::IRBuilder<>& B,
721 Value rhs,
722 const ast::tokens::OperatorToken& op,
723 Logger* log,
724 const ax::ast::Node* node) const;
725
726
727 static Value Reduce(llvm::IRBuilder<>& B,
728 const std::vector<Value>& bools,
729 const ast::tokens::OperatorToken& op)
730 {
731 OPENVDB_ASSERT(!bools.empty());
732 OPENVDB_ASSERT(op == ast::tokens::AND || op == ast::tokens::OR);
733 Value result = bools.front();
734 OPENVDB_ASSERT(result.IsBool());
735 for (size_t i = 1; i < bools.size(); ++i) {
736 result = result.TrivialBinary(B, bools[i], op, nullptr, nullptr);
737 }
738 return result;
739 }
740
741 Value ReduceBoolArray(llvm::IRBuilder<>& B, const ast::tokens::OperatorToken& op) const
742 {
743 OPENVDB_ASSERT(this->IsArray());
744 OPENVDB_ASSERT(this->GetUnderlyingScalarType() == LLVMType<bool>::get(B.getContext()));
745 std::vector<Value> elements;
746 this->ArrayToScalars(B, elements);
747 return Value::Reduce(B, elements, op);
748 }
749
750 static bool WImplicitScalarToMatrix(Logger* log, const ax::ast::Node* node)
751 {
752 if (!node) return true;
753 if (auto* child = node->child(0)) {
754 if (child->isType<ast::ArrayPack>()) {
755 if (log) log->error("unable to deduce implicit {...} type for binary op as value "
756 "may be a matrix or array. assign to a local mat variable", child);
757 return false;
758 }
759 }
760 if (log && !log->warning("implicit cast to matrix from scalar. resulting "
761 "cast will be equal to scalar <op> identity.", node->child(1))) return false;
762 return true;
763 }
764
765 static Value WUnsupportedOp(const ast::tokens::CoreType& type,
766 const ast::tokens::OperatorToken& op,
767 Logger* log,
768 const ax::ast::Node* node)
769 {
770 const std::string typestr = ast::tokens::typeStringFromToken(type);
771 return Value::WUnsupportedOp(typestr, op, log, node);
772 }
773
774 static Value WUnsupportedOp(const std::string& typestr,
775 const ast::tokens::OperatorToken& op,
776 Logger* log,
777 const ax::ast::Node* node)
778 {
779 if (log) {
780 const std::string opstr = ast::tokens::operatorNameFromToken(op);
781 log->error("unsupported " + typestr + " operation \"" + opstr + "\"", node);
782 }
783 return Value::Invalid();
784 }
785
786private:
787 llvm::Value* mVal {nullptr};
788 llvm::Type* mUType {nullptr};
789};
790
791} // namespace codegen
792} // namespace ax
793} // namespace OPENVDB_VERSION_NAME
794} // namespace openvdb
795
796#endif // OPENVDB_AX_CODEGEN_VALUE_HAS_BEEN_INCLUDED
797
Provides the definition for every abstract and concrete derived class which represent a particular ab...
#define OPENVDB_ASSERT_MESSAGE(X, MSG)
Definition Assert.h:42
#define OPENVDB_ASSERT(X)
Definition Assert.h:41
Logging system to collect errors and warnings throughout the different stages of parsing and compilat...
#define OPENVDB_AX_API
Definition Platform.h:307
Various function and operator tokens used throughout the AST and code generation.
Consolidated llvm types for most supported types.
Logger for collecting errors and warnings that occur during AX compilation.
Definition Logger.h:58
Intermediate representation wrapper for supported value types in AX as immutable instances.
Definition Value.h:63
Value GetArrayElement(llvm::IRBuilder<> &B, Value idx) const
Emit IR to return a scalar at the provided index from this array value. Will generate invalid IR if t...
Definition Value.h:355
Value BitNot(llvm::IRBuilder<> &B, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to create a unary not instruction on this integer or integer array (i.e. ~value)....
bool IsPtr() const
Return true if this Value is a pointer type.
Definition Value.h:295
Value Or(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a || operation on two scalars. Assumes both inputs are scalars (this checking is c...
Definition Value.h:564
size_t GetArrayNumElements() const
Return the number of elements in this array type.
Definition Value.h:308
Value BitAnd(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a & operation. Both values must be integers.
Definition Value.h:642
Value LessThanEquals(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a <= operation on two values.
Definition Value.h:622
static Value Alloc(llvm::IRBuilder<> &B, llvm::Type *type, llvm::Value *size=nullptr)
Emit IR inserting an allocation at the front of the BasicBlock pointed to by the provided IRBuilder....
Definition Value.h:124
Value ScalarToArray(llvm::IRBuilder<> &B, size_t size) const
Emit IR to broadcast this scalar to a new array. Will generated invalid IR if this is not a scalar or...
Definition Value.h:416
static Value Create(llvm::LLVMContext &C, const ValueType &value)
Create an arithmetic literal.
Definition Value.h:92
llvm::Type * GetUnderlyingScalarType() const
Access the underlying scalar type. This method assumes the current value is a scalar or array.
Definition Value.h:679
Value Assign(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to assign the provided rhs to this value.
Value ScalarToIdentMatrix4(llvm::IRBuilder<> &B) const
Emit IR to create a new 4x4 matrix from this scalar value, adhering to scalar->matrix promotion rules...
Definition Value.h:442
Value BitOr(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a | operation. Both values must be integers.
Definition Value.h:648
Value ShiftLeft(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a << operation. Both values must be integers.
Definition Value.h:630
void ArrayToScalars(llvm::IRBuilder<> &B, std::vector< Value > &elements, const bool load=false) const
Emit IR to extract scalar values from the elements in this array and populate the provided vector wit...
Definition Value.h:391
static Value ScalarsToArray(llvm::IRBuilder<> &B, const std::vector< Value > &values)
Emit IR to create an array from a set of scalar values. Will generate invalid IR if the values are no...
Definition Value.h:157
Value Load(llvm::IRBuilder<> &B) const
Emit IR to load the current value. Not typically required to call directly. Will generate invalid IR ...
Definition Value.h:334
Value IsNan(llvm::IRBuilder<> &B) const
Emit IR to check whether this value is NaN. Only works on Float types and will generate invalid IR if...
Definition Value.h:322
bool IsVoid() const
Return true if this value represents a void type. This is typically only possible for void function r...
Definition Value.h:208
Value ScalarBoolComparison(llvm::IRBuilder<> &B) const
Emit IR to perform standard boolean comparison on this scalar i.e. bool(scalar) or bool(scalar == 0)....
Value Modulo(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a FLOORED % operation on two values.
bool operator!() const
See bool operator.
Definition Value.h:203
Value Increment(llvm::IRBuilder<> &B, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to increment this scalar (i.e. value + 1). Will return Value::Invalid() and report a message ...
Value BitXor(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a ^ operation. Both values must be integers.
Definition Value.h:654
llvm::Value * GetValue() const
Access the underlying llvm Value.
Definition Value.h:672
bool IsMatrix() const
Return true if the underlying type is an matrix 3/4 type.
Definition Value.h:277
Value(const Value &)=default
Value(llvm::Constant *costant)
Initialize from a constant value.
Definition Value.h:77
Value & operator=(const Value &)=default
Value NotEquals(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a != operation on two values.
Value LessThan(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a < operation on two values.
Definition Value.h:616
bool IsVector() const
Return true if the underlying type is an vector 2/3/4 type.
Definition Value.h:268
bool IsString() const
Return true if the underlying type is a string type.
Definition Value.h:288
bool IsInteger() const
Return true if the underlying type is an integer type.
Definition Value.h:239
Value Divide(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a / operation on two values If the denominator is constant and zero,...
Value ScalarToIdentMatrix3(llvm::IRBuilder<> &B) const
Emit IR to create a new 3x3 matrix from this scalar value, adhering to scalar->matrix promotion rules...
Definition Value.h:434
bool IsConstant() const
Return true if this Value is a constant.
Definition Value.h:302
Value ShiftRight(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a >> operation. Both values must be integers.
Definition Value.h:636
static Value Return(llvm::IRBuilder<> &B, Value *ret=nullptr)
Create a value that represents a return value from a function. Really only intended to be used by the...
Definition Value.h:101
Value Not(llvm::IRBuilder<> &B, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to create a unary not instruction on this scalar or integer array (i.e. !value)....
Value Negate(llvm::IRBuilder<> &B, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to create a unary not instruction on this scalar or array (i.e. -value). If the value is not ...
Value One() const
Create a new one scalar Value using the underlying scalar precision of this Value....
Definition Value.h:189
Value & operator=(Value &&)=default
Value Multiply(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a * operation on two values.
Value Binary(llvm::IRBuilder<> &B, Value rhs, const ast::tokens::OperatorToken &op, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a binary operation on this LHS value and a provided RHS value. If the operation is...
Definition Value.h:510
Value LoadIfPtr(llvm::IRBuilder<> &B) const
Emit IR to load the current value if it is a ptr. Not typically required to call directly.
Definition Value.h:345
Value And(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a && operation on two scalars. Assumes both inputs are scalars (this checking is c...
Definition Value.h:547
Value Select(llvm::IRBuilder<> &B, const Value &trueval, const Value &falseval) const
Emit IR to select a value based on this boolean scalar value. Will generate invalid IR if this is not...
Value Equals(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a == operation on two values.
Value GreaterThanEquals(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a >= operation on two values.
Definition Value.h:610
void Print() const
Dump this value/type to llvm::errs.
llvm::Type * GetUnderlyingType() const
Access the underlying llvm Type.
Definition Value.h:675
Value Subtract(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a - operation on two values.
Value TruncatedModulo(llvm::IRBuilder<> &B, Value rhs) const
Emit IR to perform a TRUNCATED % operation on two values.
Value Decrement(llvm::IRBuilder<> &B, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to increment this scalar (i.e. value - 1). Will return Value::Invalid() and report a message ...
Value Zero() const
Create a new zero scalar Value using the underlying scalar precision of this Value....
Definition Value.h:181
static Value Invalid()
Return an invalid Value. This is used to represent various fail cases. Note that the operator bool(Va...
Definition Value.h:88
Value Add(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a + operation on two values.
bool IsArray() const
Return true if the underlying type is an array type.
Definition Value.h:259
bool IsFloat() const
Return true if the underlying type is an floating point type (float or double).
Definition Value.h:250
bool IsBool() const
Return true if the underlying type is a bool type.
Definition Value.h:218
Value CastToPrecision(llvm::IRBuilder<> &B, llvm::Type *precision) const
Emit IR to cast this scalar or array to a new value of the provided scalar precision....
Value(llvm::Value *val, llvm::Type *utype)
Create a Value with a provided underlying type.
Definition Value.h:71
Value GreaterThan(llvm::IRBuilder<> &B, Value rhs, Logger *log=nullptr, const ax::ast::Node *node=nullptr) const
Emit IR to perform a > operation on two values.
Definition Value.h:604
Value GetArrayElement(llvm::IRBuilder<> &B, uint64_t idx) const
Emit IR to return a scalar at the provided index from this array value. Will generate invalid IR if t...
Definition Value.h:373
bool IsScalar() const
Return true if the underlying type is a scalar type (bool, int or float).
Definition Value.h:229
static bool Supports(llvm::Type *utype)
Return true if the underlying type held by utype is supported via the interface of this Value class.
Definition Value.h:109
OperatorToken
Definition Tokens.h:151
@ BITOR
Definition Tokens.h:181
@ DIVIDE
Definition Tokens.h:158
@ LESSTHANOREQUAL
Definition Tokens.h:174
@ SHIFTRIGHT
Definition Tokens.h:179
@ MORETHANOREQUAL
Definition Tokens.h:173
@ EQUALSEQUALS
RELATIONAL.
Definition Tokens.h:169
@ BITXOR
Definition Tokens.h:182
@ BITAND
Definition Tokens.h:180
@ AND
LOGICAL.
Definition Tokens.h:163
@ PLUS
ARITHMETIC.
Definition Tokens.h:155
@ LESSTHAN
Definition Tokens.h:172
@ OR
Definition Tokens.h:164
@ MODULO
Definition Tokens.h:159
@ MORETHAN
Definition Tokens.h:171
@ NOTEQUALS
Definition Tokens.h:170
@ MULTIPLY
Definition Tokens.h:157
@ SHIFTLEFT
BITWISE.
Definition Tokens.h:178
@ MINUS
Definition Tokens.h:156
llvm::Constant * llvmConstant(const T t, llvm::Type *type)
Returns an llvm Constant holding a scalar value.
Definition Types.h:344
Definition Exceptions.h:13
Utility code generation methods for performing various llvm operations.
The base abstract node which determines the interface and required methods for all derived concrete n...
Definition AST.h:103
static llvm::Type * get(llvm::LLVMContext &C)
Return an LLVM type which represents T.
Definition Types.h:81
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition version.h.in:121
#define OPENVDB_USE_VERSION_NAMESPACE
Definition version.h.in:291