Intel® Implicit SPMD Program Compiler (Intel® ISPC)  1.13.0
expr.cpp
Go to the documentation of this file.
1 /*
2  Copyright (c) 2010-2020, Intel Corporation
3  All rights reserved.
4 
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are
7  met:
8 
9  * Redistributions of source code must retain the above copyright
10  notice, this list of conditions and the following disclaimer.
11 
12  * Redistributions in binary form must reproduce the above copyright
13  notice, this list of conditions and the following disclaimer in the
14  documentation and/or other materials provided with the distribution.
15 
16  * Neither the name of Intel Corporation nor the names of its
17  contributors may be used to endorse or promote products derived from
18  this software without specific prior written permission.
19 
20 
21  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
22  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
24  PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
25  OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33 
34 /** @file expr.cpp
35  @brief Implementations of expression classes
36 */
37 
38 #include "expr.h"
39 #include "ast.h"
40 #include "ctx.h"
41 #include "llvmutil.h"
42 #include "module.h"
43 #include "sym.h"
44 #include "type.h"
45 #include "util.h"
46 #ifndef _MSC_VER
47 #include <inttypes.h>
48 #endif
49 #ifndef PRId64
50 #define PRId64 "lld"
51 #endif
52 #ifndef PRIu64
53 #define PRIu64 "llu"
54 #endif
55 
56 #include <list>
57 #include <set>
58 #include <stdio.h>
59 
60 #include <llvm/ExecutionEngine/GenericValue.h>
61 #include <llvm/IR/CallingConv.h>
62 #include <llvm/IR/DerivedTypes.h>
63 #include <llvm/IR/Function.h>
64 #include <llvm/IR/InstIterator.h>
65 #include <llvm/IR/Instructions.h>
66 #include <llvm/IR/LLVMContext.h>
67 #include <llvm/IR/Module.h>
68 #include <llvm/IR/Type.h>
69 
70 /////////////////////////////////////////////////////////////////////////////////////
71 // Expr
72 
73 llvm::Value *Expr::GetLValue(FunctionEmitContext *ctx) const {
74  // Expressions that can't provide an lvalue can just return NULL
75  return NULL;
76 }
77 
78 const Type *Expr::GetLValueType() const {
79  // This also only needs to be overrided by Exprs that implement the
80  // GetLValue() method.
81  return NULL;
82 }
83 
84 std::pair<llvm::Constant *, bool> Expr::GetStorageConstant(const Type *type) const { return GetConstant(type); }
85 std::pair<llvm::Constant *, bool> Expr::GetConstant(const Type *type) const {
86  // The default is failure; just return NULL
87  return std::pair<llvm::Constant *, bool>(NULL, false);
88 }
89 
91  // Not all expressions can do this, so provide a generally-useful
92  // default implementation.
93  return NULL;
94 }
95 
96 #if 0
97 /** If a conversion from 'fromAtomicType' to 'toAtomicType' may cause lost
98  precision, issue a warning. Don't warn for conversions to bool and
99  conversions between signed and unsigned integers of the same size.
100  */
101 static void
102 lMaybeIssuePrecisionWarning(const AtomicType *toAtomicType,
103  const AtomicType *fromAtomicType,
104  SourcePos pos, const char *errorMsgBase) {
105  switch (toAtomicType->basicType) {
117  if ((int)toAtomicType->basicType < (int)fromAtomicType->basicType &&
118  toAtomicType->basicType != AtomicType::TYPE_BOOL &&
119  !(toAtomicType->basicType == AtomicType::TYPE_INT8 &&
120  fromAtomicType->basicType == AtomicType::TYPE_UINT8) &&
121  !(toAtomicType->basicType == AtomicType::TYPE_INT16 &&
122  fromAtomicType->basicType == AtomicType::TYPE_UINT16) &&
123  !(toAtomicType->basicType == AtomicType::TYPE_INT32 &&
124  fromAtomicType->basicType == AtomicType::TYPE_UINT32) &&
125  !(toAtomicType->basicType == AtomicType::TYPE_INT64 &&
126  fromAtomicType->basicType == AtomicType::TYPE_UINT64))
127  Warning(pos, "Conversion from type \"%s\" to type \"%s\" for %s"
128  " may lose information.",
129  fromAtomicType->GetString().c_str(), toAtomicType->GetString().c_str(),
130  errorMsgBase);
131  break;
132  default:
133  FATAL("logic error in lMaybeIssuePrecisionWarning()");
134  }
135 }
136 #endif
137 
138 ///////////////////////////////////////////////////////////////////////////
139 
140 static Expr *lArrayToPointer(Expr *expr) {
141  Assert(expr != NULL);
142  AssertPos(expr->pos, CastType<ArrayType>(expr->GetType()));
143 
144  Expr *zero = new ConstExpr(AtomicType::UniformInt32, 0, expr->pos);
145  Expr *index = new IndexExpr(expr, zero, expr->pos);
146  Expr *addr = new AddressOfExpr(index, expr->pos);
147  addr = TypeCheck(addr);
148  Assert(addr != NULL);
149  addr = Optimize(addr);
150  Assert(addr != NULL);
151  return addr;
152 }
153 
154 static bool lIsAllIntZeros(Expr *expr) {
155  const Type *type = expr->GetType();
156  if (type == NULL || type->IsIntType() == false)
157  return false;
158 
159  ConstExpr *ce = llvm::dyn_cast<ConstExpr>(expr);
160  if (ce == NULL)
161  return false;
162 
163  uint64_t vals[ISPC_MAX_NVEC];
164  int count = ce->GetValues(vals);
165  if (count == 1)
166  return (vals[0] == 0);
167  else {
168  for (int i = 0; i < count; ++i)
169  if (vals[i] != 0)
170  return false;
171  }
172  return true;
173 }
174 
175 static bool lDoTypeConv(const Type *fromType, const Type *toType, Expr **expr, bool failureOk, const char *errorMsgBase,
176  SourcePos pos) {
177  /* This function is way too long and complex. Is type conversion stuff
178  always this messy, or can this be cleaned up somehow? */
179  AssertPos(pos, failureOk || errorMsgBase != NULL);
180 
181  if (toType == NULL || fromType == NULL)
182  return false;
183 
184  // The types are equal; there's nothing to do
185  if (Type::Equal(toType, fromType))
186  return true;
187 
188  if (fromType->IsVoidType()) {
189  if (!failureOk)
190  Error(pos, "Can't convert from \"void\" to \"%s\" for %s.", toType->GetString().c_str(), errorMsgBase);
191  return false;
192  }
193 
194  if (toType->IsVoidType()) {
195  if (!failureOk)
196  Error(pos, "Can't convert type \"%s\" to \"void\" for %s.", fromType->GetString().c_str(), errorMsgBase);
197  return false;
198  }
199 
200  if (CastType<FunctionType>(fromType)) {
201  if (CastType<PointerType>(toType) != NULL) {
202  // Convert function type to pointer to function type
203  if (expr != NULL) {
204  Expr *aoe = new AddressOfExpr(*expr, (*expr)->pos);
205  if (lDoTypeConv(aoe->GetType(), toType, &aoe, failureOk, errorMsgBase, pos)) {
206  *expr = aoe;
207  return true;
208  }
209  } else
210  return lDoTypeConv(PointerType::GetUniform(fromType), toType, NULL, failureOk, errorMsgBase, pos);
211  } else {
212  if (!failureOk)
213  Error(pos, "Can't convert function type \"%s\" to \"%s\" for %s.", fromType->GetString().c_str(),
214  toType->GetString().c_str(), errorMsgBase);
215  return false;
216  }
217  }
218  if (CastType<FunctionType>(toType)) {
219  if (!failureOk)
220  Error(pos,
221  "Can't convert from type \"%s\" to function type \"%s\" "
222  "for %s.",
223  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
224  return false;
225  }
226 
227  if ((toType->GetSOAWidth() > 0 || fromType->GetSOAWidth() > 0) &&
228  Type::Equal(toType->GetAsUniformType(), fromType->GetAsUniformType()) &&
229  toType->GetSOAWidth() != fromType->GetSOAWidth()) {
230  if (!failureOk)
231  Error(pos,
232  "Can't convert between types \"%s\" and \"%s\" with "
233  "different SOA widths for %s.",
234  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
235  return false;
236  }
237 
238  const ArrayType *toArrayType = CastType<ArrayType>(toType);
239  const ArrayType *fromArrayType = CastType<ArrayType>(fromType);
240  const VectorType *toVectorType = CastType<VectorType>(toType);
241  const VectorType *fromVectorType = CastType<VectorType>(fromType);
242  const StructType *toStructType = CastType<StructType>(toType);
243  const StructType *fromStructType = CastType<StructType>(fromType);
244  const EnumType *toEnumType = CastType<EnumType>(toType);
245  const EnumType *fromEnumType = CastType<EnumType>(fromType);
246  const AtomicType *toAtomicType = CastType<AtomicType>(toType);
247  const AtomicType *fromAtomicType = CastType<AtomicType>(fromType);
248  const PointerType *fromPointerType = CastType<PointerType>(fromType);
249  const PointerType *toPointerType = CastType<PointerType>(toType);
250 
251  // Do this early, since for the case of a conversion like
252  // "float foo[10]" -> "float * uniform foo", we have what's seemingly
253  // a varying to uniform conversion (but not really)
254  if (fromArrayType != NULL && toPointerType != NULL) {
255  // can convert any array to a void pointer (both uniform and
256  // varying).
257  if (PointerType::IsVoidPointer(toPointerType))
258  goto typecast_ok;
259 
260  // array to pointer to array element type
261  const Type *eltType = fromArrayType->GetElementType();
262  if (toPointerType->GetBaseType()->IsConstType())
263  eltType = eltType->GetAsConstType();
264 
265  PointerType pt(eltType, toPointerType->GetVariability(), toPointerType->IsConstType());
266  if (Type::Equal(toPointerType, &pt))
267  goto typecast_ok;
268  else {
269  if (!failureOk)
270  Error(pos,
271  "Can't convert from incompatible array type \"%s\" "
272  "to pointer type \"%s\" for %s.",
273  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
274  return false;
275  }
276  }
277 
278  if (toType->IsUniformType() && fromType->IsVaryingType()) {
279  if (!failureOk)
280  Error(pos, "Can't convert from type \"%s\" to type \"%s\" for %s.", fromType->GetString().c_str(),
281  toType->GetString().c_str(), errorMsgBase);
282  return false;
283  }
284 
285  if (fromPointerType != NULL) {
286  if (CastType<AtomicType>(toType) != NULL && toType->IsBoolType())
287  // Allow implicit conversion of pointers to bools
288  goto typecast_ok;
289 
290  if (toArrayType != NULL && Type::Equal(fromType->GetBaseType(), toArrayType->GetElementType())) {
291  // Can convert pointers to arrays of the same type
292  goto typecast_ok;
293  }
294  if (toPointerType == NULL) {
295  if (!failureOk)
296  Error(pos,
297  "Can't convert between from pointer type "
298  "\"%s\" to non-pointer type \"%s\" for %s.",
299  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
300  return false;
301  } else if (fromPointerType->IsSlice() == true && toPointerType->IsSlice() == false) {
302  if (!failureOk)
303  Error(pos,
304  "Can't convert from pointer to SOA type "
305  "\"%s\" to pointer to non-SOA type \"%s\" for %s.",
306  fromPointerType->GetAsNonSlice()->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
307  return false;
308  } else if (PointerType::IsVoidPointer(toPointerType)) {
309  if (fromPointerType->GetBaseType()->IsConstType() && !(toPointerType->GetBaseType()->IsConstType())) {
310  if (!failureOk)
311  Error(pos, "Can't convert pointer to const \"%s\" to void pointer.",
312  fromPointerType->GetString().c_str());
313  return false;
314  }
315  // any pointer type can be converted to a void *
316  // ...almost. #731
317  goto typecast_ok;
318  } else if (PointerType::IsVoidPointer(fromPointerType) && expr != NULL &&
319  llvm::dyn_cast<NullPointerExpr>(*expr) != NULL) {
320  // and a NULL convert to any other pointer type
321  goto typecast_ok;
322  } else if (!Type::Equal(fromPointerType->GetBaseType(), toPointerType->GetBaseType()) &&
323  !Type::Equal(fromPointerType->GetBaseType()->GetAsConstType(), toPointerType->GetBaseType())) {
324  // for const * -> * conversion, print warning.
325  if (Type::EqualIgnoringConst(fromPointerType->GetBaseType(), toPointerType->GetBaseType())) {
326  if (!Type::Equal(fromPointerType->GetBaseType()->GetAsConstType(), toPointerType->GetBaseType())) {
327  Warning(pos,
328  "Converting from const pointer type \"%s\" to "
329  "pointer type \"%s\" for %s discards const qualifier.",
330  fromPointerType->GetString().c_str(), toPointerType->GetString().c_str(), errorMsgBase);
331  }
332  } else {
333  if (!failureOk) {
334  Error(pos,
335  "Can't convert from pointer type \"%s\" to "
336  "incompatible pointer type \"%s\" for %s.",
337  fromPointerType->GetString().c_str(), toPointerType->GetString().c_str(), errorMsgBase);
338  }
339  return false;
340  }
341  }
342 
343  if (toType->IsVaryingType() && fromType->IsUniformType())
344  goto typecast_ok;
345 
346  if (toPointerType->IsSlice() == true && fromPointerType->IsSlice() == false)
347  goto typecast_ok;
348 
349  // Otherwise there's nothing to do
350  return true;
351  }
352 
353  if (toPointerType != NULL && fromAtomicType != NULL && fromAtomicType->IsIntType() && expr != NULL &&
354  lIsAllIntZeros(*expr)) {
355  // We have a zero-valued integer expression, which can also be
356  // treated as a NULL pointer that can be converted to any other
357  // pointer type.
358  Expr *npe = new NullPointerExpr(pos);
359  if (lDoTypeConv(PointerType::Void, toType, &npe, failureOk, errorMsgBase, pos)) {
360  *expr = npe;
361  return true;
362  }
363  return false;
364  }
365 
366  // Need to check this early, since otherwise the [sic] "unbound"
367  // variability of SOA struct types causes things to get messy if that
368  // hasn't been detected...
369  if (toStructType && fromStructType && (toStructType->GetSOAWidth() != fromStructType->GetSOAWidth())) {
370  if (!failureOk)
371  Error(pos,
372  "Can't convert between incompatible struct types \"%s\" "
373  "and \"%s\" for %s.",
374  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
375  return false;
376  }
377 
378  // Convert from type T -> const T; just return a TypeCast expr, which
379  // can handle this
380  if (Type::EqualIgnoringConst(toType, fromType) && toType->IsConstType() == true && fromType->IsConstType() == false)
381  goto typecast_ok;
382 
383  if (CastType<ReferenceType>(fromType)) {
384  if (CastType<ReferenceType>(toType)) {
385  // Convert from a reference to a type to a const reference to a type;
386  // this is handled by TypeCastExpr
387  if (Type::Equal(toType->GetReferenceTarget(), fromType->GetReferenceTarget()->GetAsConstType()))
388  goto typecast_ok;
389 
390  const ArrayType *atFrom = CastType<ArrayType>(fromType->GetReferenceTarget());
391  const ArrayType *atTo = CastType<ArrayType>(toType->GetReferenceTarget());
392 
393  if (atFrom != NULL && atTo != NULL && Type::Equal(atFrom->GetElementType(), atTo->GetElementType())) {
394  goto typecast_ok;
395  } else {
396  if (!failureOk)
397  Error(pos,
398  "Can't convert between incompatible reference types \"%s\" "
399  "and \"%s\" for %s.",
400  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
401  return false;
402  }
403  } else {
404  // convert from a reference T -> T
405  if (expr != NULL) {
406  Expr *drExpr = new RefDerefExpr(*expr, pos);
407  if (lDoTypeConv(drExpr->GetType(), toType, &drExpr, failureOk, errorMsgBase, pos) == true) {
408  *expr = drExpr;
409  return true;
410  }
411  return false;
412  } else
413  return lDoTypeConv(fromType->GetReferenceTarget(), toType, NULL, failureOk, errorMsgBase, pos);
414  }
415  } else if (CastType<ReferenceType>(toType)) {
416  // T -> reference T
417  if (expr != NULL) {
418  Expr *rExpr = new ReferenceExpr(*expr, pos);
419  if (lDoTypeConv(rExpr->GetType(), toType, &rExpr, failureOk, errorMsgBase, pos) == true) {
420  *expr = rExpr;
421  return true;
422  }
423  return false;
424  } else {
425  ReferenceType rt(fromType);
426  return lDoTypeConv(&rt, toType, NULL, failureOk, errorMsgBase, pos);
427  }
428  } else if (Type::Equal(toType, fromType->GetAsNonConstType()))
429  // convert: const T -> T (as long as T isn't a reference)
430  goto typecast_ok;
431 
432  fromType = fromType->GetReferenceTarget();
433  toType = toType->GetReferenceTarget();
434  if (toArrayType && fromArrayType) {
435  if (Type::Equal(toArrayType->GetElementType(), fromArrayType->GetElementType())) {
436  // the case of different element counts should have returned
437  // successfully earlier, yes??
438  AssertPos(pos, toArrayType->GetElementCount() != fromArrayType->GetElementCount());
439  goto typecast_ok;
440  } else if (Type::Equal(toArrayType->GetElementType(), fromArrayType->GetElementType()->GetAsConstType())) {
441  // T[x] -> const T[x]
442  goto typecast_ok;
443  } else {
444  if (!failureOk)
445  Error(pos, "Array type \"%s\" can't be converted to type \"%s\" for %s.", fromType->GetString().c_str(),
446  toType->GetString().c_str(), errorMsgBase);
447  return false;
448  }
449  }
450 
451  if (toVectorType && fromVectorType) {
452  // converting e.g. int<n> -> float<n>
453  if (fromVectorType->GetElementCount() != toVectorType->GetElementCount()) {
454  if (!failureOk)
455  Error(pos,
456  "Can't convert between differently sized vector types "
457  "\"%s\" -> \"%s\" for %s.",
458  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
459  return false;
460  }
461  goto typecast_ok;
462  }
463 
464  if (toStructType && fromStructType) {
465  if (!Type::Equal(toStructType->GetAsUniformType()->GetAsConstType(),
466  fromStructType->GetAsUniformType()->GetAsConstType())) {
467  if (!failureOk)
468  Error(pos,
469  "Can't convert between different struct types "
470  "\"%s\" and \"%s\" for %s.",
471  fromStructType->GetString().c_str(), toStructType->GetString().c_str(), errorMsgBase);
472  return false;
473  }
474  goto typecast_ok;
475  }
476 
477  if (toEnumType != NULL && fromEnumType != NULL) {
478  // No implicit conversions between different enum types
479  if (!Type::EqualIgnoringConst(toEnumType->GetAsUniformType(), fromEnumType->GetAsUniformType())) {
480  if (!failureOk)
481  Error(pos,
482  "Can't convert between different enum types "
483  "\"%s\" and \"%s\" for %s",
484  fromEnumType->GetString().c_str(), toEnumType->GetString().c_str(), errorMsgBase);
485  return false;
486  }
487  goto typecast_ok;
488  }
489 
490  // enum -> atomic (integer, generally...) is always ok
491  if (fromEnumType != NULL) {
492  // Cannot convert to anything other than atomic
493  if (toAtomicType == NULL && toVectorType == NULL) {
494  if (!failureOk)
495  Error(pos,
496  "Type conversion from \"%s\" to \"%s\" for %s is not "
497  "possible.",
498  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
499  return false;
500  }
501  goto typecast_ok;
502  }
503 
504  // from here on out, the from type can only be atomic something or
505  // other...
506  if (fromAtomicType == NULL) {
507  if (!failureOk)
508  Error(pos,
509  "Type conversion from \"%s\" to \"%s\" for %s is not "
510  "possible.",
511  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
512  return false;
513  }
514 
515  // scalar -> short-vector conversions
516  if (toVectorType != NULL && (fromType->GetSOAWidth() == toType->GetSOAWidth()))
517  goto typecast_ok;
518 
519  // ok, it better be a scalar->scalar conversion of some sort by now
520  if (toAtomicType == NULL) {
521  if (!failureOk)
522  Error(pos,
523  "Type conversion from \"%s\" to \"%s\" for %s is "
524  "not possible",
525  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
526  return false;
527  }
528 
529  if (fromType->GetSOAWidth() != toType->GetSOAWidth()) {
530  if (!failureOk)
531  Error(pos,
532  "Can't convert between types \"%s\" and \"%s\" with "
533  "different SOA widths for %s.",
534  fromType->GetString().c_str(), toType->GetString().c_str(), errorMsgBase);
535  return false;
536  }
537 
538 typecast_ok:
539  if (expr != NULL)
540  *expr = new TypeCastExpr(toType, *expr, pos);
541  return true;
542 }
543 
544 bool CanConvertTypes(const Type *fromType, const Type *toType, const char *errorMsgBase, SourcePos pos) {
545  return lDoTypeConv(fromType, toType, NULL, errorMsgBase == NULL, errorMsgBase, pos);
546 }
547 
548 Expr *TypeConvertExpr(Expr *expr, const Type *toType, const char *errorMsgBase) {
549  if (expr == NULL)
550  return NULL;
551 
552 #if 0
553  Debug(expr->pos, "type convert %s -> %s.", expr->GetType()->GetString().c_str(),
554  toType->GetString().c_str());
555 #endif
556 
557  const Type *fromType = expr->GetType();
558  Expr *e = expr;
559  if (lDoTypeConv(fromType, toType, &e, false, errorMsgBase, expr->pos))
560  return e;
561  else
562  return NULL;
563 }
564 
565 bool PossiblyResolveFunctionOverloads(Expr *expr, const Type *type) {
566  FunctionSymbolExpr *fse = NULL;
567  const FunctionType *funcType = NULL;
568  if (CastType<PointerType>(type) != NULL && (funcType = CastType<FunctionType>(type->GetBaseType())) &&
569  (fse = llvm::dyn_cast<FunctionSymbolExpr>(expr)) != NULL) {
570  // We're initializing a function pointer with a function symbol,
571  // which in turn may represent an overloaded function. So we need
572  // to try to resolve the overload based on the type of the symbol
573  // we're initializing here.
574  std::vector<const Type *> paramTypes;
575  for (int i = 0; i < funcType->GetNumParameters(); ++i)
576  paramTypes.push_back(funcType->GetParameterType(i));
577 
578  if (fse->ResolveOverloads(expr->pos, paramTypes) == false)
579  return false;
580  }
581  return true;
582 }
583 
584 /** Utility routine that emits code to initialize a symbol given an
585  initializer expression.
586 
587  @param ptr Memory location of storage for the symbol's data
588  @param symName Name of symbol (used in error messages)
589  @param symType Type of variable being initialized
590  @param initExpr Expression for the initializer
591  @param ctx FunctionEmitContext to use for generating instructions
592  @param pos Source file position of the variable being initialized
593 */
594 void InitSymbol(llvm::Value *ptr, const Type *symType, Expr *initExpr, FunctionEmitContext *ctx, SourcePos pos) {
595  if (initExpr == NULL)
596  // leave it uninitialized
597  return;
598 
599  // See if we have a constant initializer a this point
600  std::pair<llvm::Constant *, bool> constValPair = initExpr->GetStorageConstant(symType);
601  llvm::Constant *constValue = constValPair.first;
602  if (constValue != NULL) {
603  // It'd be nice if we could just do a StoreInst(constValue, ptr)
604  // at this point, but unfortunately that doesn't generate great
605  // code (e.g. a bunch of scalar moves for a constant array.) So
606  // instead we'll make a constant static global that holds the
607  // constant value and emit a memcpy to put its value into the
608  // pointer we have.
609  llvm::Type *llvmType = symType->LLVMStorageType(g->ctx);
610  if (llvmType == NULL) {
611  AssertPos(pos, m->errorCount > 0);
612  return;
613  }
614 
615  if (Type::IsBasicType(symType))
616  ctx->StoreInst(constValue, ptr, symType);
617  else {
618  llvm::Value *constPtr =
619  new llvm::GlobalVariable(*m->module, llvmType, true /* const */, llvm::GlobalValue::InternalLinkage,
620  constValue, "const_initializer");
621  llvm::Value *size = g->target->SizeOf(llvmType, ctx->GetCurrentBasicBlock());
622  ctx->MemcpyInst(ptr, constPtr, size);
623  }
624 
625  return;
626  }
627 
628  // If the initializer is a straight up expression that isn't an
629  // ExprList, then we'll see if we can type convert it to the type of
630  // the variable.
631  if (llvm::dyn_cast<ExprList>(initExpr) == NULL) {
632  if (PossiblyResolveFunctionOverloads(initExpr, symType) == false)
633  return;
634  initExpr = TypeConvertExpr(initExpr, symType, "initializer");
635 
636  if (initExpr == NULL)
637  return;
638 
639  llvm::Value *initializerValue = initExpr->GetValue(ctx);
640  if (initializerValue != NULL)
641  // Bingo; store the value in the variable's storage
642  ctx->StoreInst(initializerValue, ptr, symType);
643  return;
644  }
645 
646  // Atomic types and enums can be initialized with { ... } initializer
647  // expressions if they have a single element (except for SOA types,
648  // which are handled below).
649  if (symType->IsSOAType() == false && Type::IsBasicType(symType)) {
650  ExprList *elist = llvm::dyn_cast<ExprList>(initExpr);
651  if (elist != NULL) {
652  if (elist->exprs.size() == 1) {
653  InitSymbol(ptr, symType, elist->exprs[0], ctx, pos);
654  return;
655  } else if (symType->IsVaryingType() == false) {
656  Error(initExpr->pos,
657  "Expression list initializers with "
658  "multiple values can't be used with type \"%s\".",
659  symType->GetString().c_str());
660  return;
661  }
662  } else
663  return;
664  }
665 
666  const ReferenceType *rt = CastType<ReferenceType>(symType);
667  if (rt) {
668  if (!Type::Equal(initExpr->GetType(), rt)) {
669  Error(initExpr->pos,
670  "Initializer for reference type \"%s\" must have same "
671  "reference type itself. \"%s\" is incompatible.",
672  rt->GetString().c_str(), initExpr->GetType()->GetString().c_str());
673  return;
674  }
675 
676  llvm::Value *initializerValue = initExpr->GetValue(ctx);
677  if (initializerValue)
678  ctx->StoreInst(initializerValue, ptr, initExpr->GetType());
679  return;
680  }
681 
682  // Handle initiailizers for SOA types as well as for structs, arrays,
683  // and vectors.
684  const CollectionType *collectionType = CastType<CollectionType>(symType);
685  if (collectionType != NULL || symType->IsSOAType() ||
686  (Type::IsBasicType(symType) && symType->IsVaryingType() == true)) {
687  // Make default value equivalent to number of elements for varying
688  int nElements = g->target->getVectorWidth();
689  if (collectionType)
690  nElements = collectionType->GetElementCount();
691  else if (symType->IsSOAType())
692  nElements = symType->GetSOAWidth();
693 
694  std::string name;
695  if (CastType<StructType>(symType) != NULL)
696  name = "struct";
697  else if (CastType<ArrayType>(symType) != NULL)
698  name = "array";
699  else if (CastType<VectorType>(symType) != NULL)
700  name = "vector";
701  else if (symType->IsSOAType() || (Type::IsBasicType(symType) && symType->IsVaryingType() == true))
702  name = symType->GetVariability().GetString();
703  else
704  FATAL("Unexpected CollectionType in InitSymbol()");
705 
706  // There are two cases for initializing these types; either a
707  // single initializer may be provided (float foo[3] = 0;), in which
708  // case all of the elements are initialized to the given value, or
709  // an initializer list may be provided (float foo[3] = { 1,2,3 }),
710  // in which case the elements are initialized with the
711  // corresponding values.
712  ExprList *exprList = llvm::dyn_cast<ExprList>(initExpr);
713  if (exprList != NULL) {
714  // The { ... } case; make sure we have the no more expressions
715  // in the ExprList as we have struct members
716  int nInits = exprList->exprs.size();
717  if (nInits > nElements) {
718  Error(initExpr->pos,
719  "Initializer for %s type \"%s\" requires "
720  "no more than %d values; %d provided.",
721  name.c_str(), symType->GetString().c_str(), nElements, nInits);
722  return;
723  } else if ((Type::IsBasicType(symType) && symType->IsVaryingType() == true) && (nInits < nElements)) {
724  Error(initExpr->pos,
725  "Initializer for %s type \"%s\" requires "
726  "%d values; %d provided.",
727  name.c_str(), symType->GetString().c_str(), nElements, nInits);
728  return;
729  }
730 
731  // Initialize each element with the corresponding value from
732  // the ExprList
733  for (int i = 0; i < nElements; ++i) {
734  // For SOA types and varying, the element type is the uniform variant
735  // of the underlying type
736  const Type *elementType =
737  collectionType ? collectionType->GetElementType(i) : symType->GetAsUniformType();
738 
739  llvm::Value *ep;
740  if (CastType<StructType>(symType) != NULL)
741  ep = ctx->AddElementOffset(ptr, i, NULL, "element");
742  else
743  ep = ctx->GetElementPtrInst(ptr, LLVMInt32(0), LLVMInt32(i), PointerType::GetUniform(elementType),
744  "gep");
745 
746  if (i < nInits)
747  InitSymbol(ep, elementType, exprList->exprs[i], ctx, pos);
748  else {
749  // If we don't have enough initializer values, initialize the
750  // rest as zero.
751  llvm::Type *llvmType = elementType->LLVMStorageType(g->ctx);
752  if (llvmType == NULL) {
753  AssertPos(pos, m->errorCount > 0);
754  return;
755  }
756 
757  llvm::Constant *zeroInit = llvm::Constant::getNullValue(llvmType);
758  ctx->StoreInst(zeroInit, ep, elementType);
759  }
760  }
761  } else if (collectionType) {
762  Error(initExpr->pos, "Can't assign type \"%s\" to \"%s\".", initExpr->GetType()->GetString().c_str(),
763  collectionType->GetString().c_str());
764  } else {
765  FATAL("CollectionType is NULL in InitSymbol()");
766  }
767  return;
768  }
769 
770  FATAL("Unexpected Type in InitSymbol()");
771 }
772 
773 ///////////////////////////////////////////////////////////////////////////
774 
775 /** Given an atomic or vector type, this returns a boolean type with the
776  same "shape". In other words, if the given type is a vector type of
777  three uniform ints, the returned type is a vector type of three uniform
778  bools. */
779 static const Type *lMatchingBoolType(const Type *type) {
780  bool uniformTest = type->IsUniformType();
781  const AtomicType *boolBase = uniformTest ? AtomicType::UniformBool : AtomicType::VaryingBool;
782  const VectorType *vt = CastType<VectorType>(type);
783  if (vt != NULL)
784  return new VectorType(boolBase, vt->GetElementCount());
785  else {
786  Assert(Type::IsBasicType(type) || type->IsReferenceType());
787  return boolBase;
788  }
789 }
790 
791 ///////////////////////////////////////////////////////////////////////////
792 // UnaryExpr
793 
794 static llvm::Constant *lLLVMConstantValue(const Type *type, llvm::LLVMContext *ctx, double value) {
795  const AtomicType *atomicType = CastType<AtomicType>(type);
796  const EnumType *enumType = CastType<EnumType>(type);
797  const VectorType *vectorType = CastType<VectorType>(type);
798  const PointerType *pointerType = CastType<PointerType>(type);
799 
800  // This function is only called with, and only works for atomic, enum,
801  // and vector types.
802  Assert(atomicType != NULL || enumType != NULL || vectorType != NULL || pointerType != NULL);
803 
804  if (atomicType != NULL || enumType != NULL) {
805  // If it's an atomic or enuemrator type, then figure out which of
806  // the llvmutil.h functions to call to get the corresponding
807  // constant and then call it...
808  bool isUniform = type->IsUniformType();
809  AtomicType::BasicType basicType = (enumType != NULL) ? AtomicType::TYPE_UINT32 : atomicType->basicType;
810 
811  switch (basicType) {
813  FATAL("can't get constant value for void type");
814  return NULL;
816  if (isUniform)
817  return (value != 0.) ? LLVMTrue : LLVMFalse;
818  else
819  return LLVMBoolVector(value != 0.);
820  case AtomicType::TYPE_INT8: {
821  int i = (int)value;
822  Assert((double)i == value);
823  return isUniform ? LLVMInt8(i) : LLVMInt8Vector(i);
824  }
825  case AtomicType::TYPE_UINT8: {
826  unsigned int i = (unsigned int)value;
827  return isUniform ? LLVMUInt8(i) : LLVMUInt8Vector(i);
828  }
829  case AtomicType::TYPE_INT16: {
830  int i = (int)value;
831  Assert((double)i == value);
832  return isUniform ? LLVMInt16(i) : LLVMInt16Vector(i);
833  }
835  unsigned int i = (unsigned int)value;
836  return isUniform ? LLVMUInt16(i) : LLVMUInt16Vector(i);
837  }
838  case AtomicType::TYPE_INT32: {
839  int i = (int)value;
840  Assert((double)i == value);
841  return isUniform ? LLVMInt32(i) : LLVMInt32Vector(i);
842  }
844  unsigned int i = (unsigned int)value;
845  return isUniform ? LLVMUInt32(i) : LLVMUInt32Vector(i);
846  }
848  return isUniform ? LLVMFloat((float)value) : LLVMFloatVector((float)value);
850  uint64_t i = (uint64_t)value;
851  Assert(value == (int64_t)i);
852  return isUniform ? LLVMUInt64(i) : LLVMUInt64Vector(i);
853  }
854  case AtomicType::TYPE_INT64: {
855  int64_t i = (int64_t)value;
856  Assert((double)i == value);
857  return isUniform ? LLVMInt64(i) : LLVMInt64Vector(i);
858  }
860  return isUniform ? LLVMDouble(value) : LLVMDoubleVector(value);
861  default:
862  FATAL("logic error in lLLVMConstantValue");
863  return NULL;
864  }
865  } else if (pointerType != NULL) {
866  Assert(value == 0);
867  if (pointerType->IsUniformType())
868  return llvm::Constant::getNullValue(LLVMTypes::VoidPointerType);
869  else
870  return llvm::Constant::getNullValue(LLVMTypes::VoidPointerVectorType);
871  } else {
872  // For vector types, first get the LLVM constant for the basetype with
873  // a recursive call to lLLVMConstantValue().
874  const Type *baseType = vectorType->GetBaseType();
875  llvm::Constant *constElement = lLLVMConstantValue(baseType, ctx, value);
876  llvm::Type *llvmVectorType = vectorType->LLVMType(ctx);
877 
878  // Now create a constant version of the corresponding LLVM type that we
879  // use to represent the VectorType.
880  // FIXME: this is a little ugly in that the fact that ispc represents
881  // uniform VectorTypes as LLVM VectorTypes and varying VectorTypes as
882  // LLVM ArrayTypes leaks into the code here; it feels like this detail
883  // should be better encapsulated?
884  if (baseType->IsUniformType()) {
885  llvm::VectorType *lvt = llvm::dyn_cast<llvm::VectorType>(llvmVectorType);
886  Assert(lvt != NULL);
887  std::vector<llvm::Constant *> vals;
888  for (unsigned int i = 0; i < lvt->getNumElements(); ++i)
889  vals.push_back(constElement);
890  return llvm::ConstantVector::get(vals);
891  } else {
892  llvm::ArrayType *lat = llvm::dyn_cast<llvm::ArrayType>(llvmVectorType);
893  Assert(lat != NULL);
894  std::vector<llvm::Constant *> vals;
895  for (unsigned int i = 0; i < lat->getNumElements(); ++i)
896  vals.push_back(constElement);
897  return llvm::ConstantArray::get(lat, vals);
898  }
899  }
900 }
901 
902 static llvm::Value *lMaskForSymbol(Symbol *baseSym, FunctionEmitContext *ctx) {
903  if (baseSym == NULL)
904  return ctx->GetFullMask();
905 
906  if (CastType<PointerType>(baseSym->type) != NULL || CastType<ReferenceType>(baseSym->type) != NULL)
907  // FIXME: for pointers, we really only want to do this for
908  // dereferencing the pointer, not for things like pointer
909  // arithmetic, when we may be able to use the internal mask,
910  // depending on context...
911  return ctx->GetFullMask();
912 
913  llvm::Value *mask = (baseSym->parentFunction == ctx->GetFunction() && baseSym->storageClass != SC_STATIC)
914  ? ctx->GetInternalMask()
915  : ctx->GetFullMask();
916  return mask;
917 }
918 
919 /** Store the result of an assignment to the given location.
920  */
921 static void lStoreAssignResult(llvm::Value *value, llvm::Value *ptr, const Type *valueType, const Type *ptrType,
922  FunctionEmitContext *ctx, Symbol *baseSym) {
923  Assert(baseSym == NULL || baseSym->varyingCFDepth <= ctx->VaryingCFDepth());
924  if (!g->opt.disableMaskedStoreToStore && !g->opt.disableMaskAllOnOptimizations && baseSym != NULL &&
925  baseSym->varyingCFDepth == ctx->VaryingCFDepth() && baseSym->storageClass != SC_STATIC &&
926  CastType<ReferenceType>(baseSym->type) == NULL && CastType<PointerType>(baseSym->type) == NULL) {
927  // If the variable is declared at the same varying control flow
928  // depth as where it's being assigned, then we don't need to do any
929  // masking but can just do the assignment as if all the lanes were
930  // known to be on. While this may lead to random/garbage values
931  // written into the lanes that are off, by definition they will
932  // never be accessed, since those lanes aren't executing, and won't
933  // be executing at this scope or any other one before the variable
934  // goes out of scope.
935  ctx->StoreInst(value, ptr, LLVMMaskAllOn, valueType, ptrType);
936  } else {
937  ctx->StoreInst(value, ptr, lMaskForSymbol(baseSym, ctx), valueType, ptrType);
938  }
939 }
940 
941 /** Utility routine to emit code to do a {pre,post}-{inc,dec}rement of the
942  given expresion.
943  */
944 static llvm::Value *lEmitPrePostIncDec(UnaryExpr::Op op, Expr *expr, SourcePos pos, FunctionEmitContext *ctx) {
945  const Type *type = expr->GetType();
946  if (type == NULL)
947  return NULL;
948 
949  // Get both the lvalue and the rvalue of the given expression
950  llvm::Value *lvalue = NULL, *rvalue = NULL;
951  const Type *lvalueType = NULL;
952  if (CastType<ReferenceType>(type) != NULL) {
953  lvalueType = type;
954  type = type->GetReferenceTarget();
955  lvalue = expr->GetValue(ctx);
956 
957  RefDerefExpr *deref = new RefDerefExpr(expr, expr->pos);
958  rvalue = deref->GetValue(ctx);
959  } else {
960  lvalue = expr->GetLValue(ctx);
961  lvalueType = expr->GetLValueType();
962  rvalue = expr->GetValue(ctx);
963  }
964 
965  if (lvalue == NULL) {
966  // If we can't get a lvalue, then we have an error here
967  const char *prepost = (op == UnaryExpr::PreInc || op == UnaryExpr::PreDec) ? "pre" : "post";
968  const char *incdec = (op == UnaryExpr::PreInc || op == UnaryExpr::PostInc) ? "increment" : "decrement";
969  Error(pos, "Can't %s-%s non-lvalues.", prepost, incdec);
970  return NULL;
971  }
972 
973  // Emit code to do the appropriate addition/subtraction to the
974  // expression's old value
975  ctx->SetDebugPos(pos);
976  llvm::Value *binop = NULL;
977  int delta = (op == UnaryExpr::PreInc || op == UnaryExpr::PostInc) ? 1 : -1;
978 
979  std::string opName = rvalue->getName().str();
980  if (op == UnaryExpr::PreInc || op == UnaryExpr::PostInc)
981  opName += "_plus1";
982  else
983  opName += "_minus1";
984 
985  if (CastType<PointerType>(type) != NULL) {
987  llvm::Constant *dval = lLLVMConstantValue(incType, g->ctx, delta);
988  binop = ctx->GetElementPtrInst(rvalue, dval, type, opName.c_str());
989  } else {
990  llvm::Constant *dval = lLLVMConstantValue(type, g->ctx, delta);
991  if (type->IsFloatType())
992  binop = ctx->BinaryOperator(llvm::Instruction::FAdd, rvalue, dval, opName.c_str());
993  else
994  binop = ctx->BinaryOperator(llvm::Instruction::Add, rvalue, dval, opName.c_str());
995  }
996 
997  // And store the result out to the lvalue
998  Symbol *baseSym = expr->GetBaseSymbol();
999  lStoreAssignResult(binop, lvalue, type, lvalueType, ctx, baseSym);
1000 
1001  // And then if it's a pre increment/decrement, return the final
1002  // computed result; otherwise return the previously-grabbed expression
1003  // value.
1004  return (op == UnaryExpr::PreInc || op == UnaryExpr::PreDec) ? binop : rvalue;
1005 }
1006 
1007 /** Utility routine to emit code to negate the given expression.
1008  */
1009 static llvm::Value *lEmitNegate(Expr *arg, SourcePos pos, FunctionEmitContext *ctx) {
1010  const Type *type = arg->GetType();
1011  llvm::Value *argVal = arg->GetValue(ctx);
1012  if (type == NULL || argVal == NULL)
1013  return NULL;
1014 
1015  // Negate by subtracting from zero...
1016  ctx->SetDebugPos(pos);
1017  if (type->IsFloatType()) {
1018  llvm::Value *zero = llvm::ConstantFP::getZeroValueForNegation(type->LLVMType(g->ctx));
1019  return ctx->BinaryOperator(llvm::Instruction::FSub, zero, argVal, LLVMGetName(argVal, "_negate"));
1020  } else {
1021  llvm::Value *zero = lLLVMConstantValue(type, g->ctx, 0.);
1022  AssertPos(pos, type->IsIntType());
1023  return ctx->BinaryOperator(llvm::Instruction::Sub, zero, argVal, LLVMGetName(argVal, "_negate"));
1024  }
1025 }
1026 
1027 UnaryExpr::UnaryExpr(Op o, Expr *e, SourcePos p) : Expr(p, UnaryExprID), op(o) { expr = e; }
1028 
1029 llvm::Value *UnaryExpr::GetValue(FunctionEmitContext *ctx) const {
1030  if (expr == NULL)
1031  return NULL;
1032 
1033  ctx->SetDebugPos(pos);
1034 
1035  switch (op) {
1036  case PreInc:
1037  case PreDec:
1038  case PostInc:
1039  case PostDec:
1040  return lEmitPrePostIncDec(op, expr, pos, ctx);
1041  case Negate:
1042  return lEmitNegate(expr, pos, ctx);
1043  case LogicalNot: {
1044  llvm::Value *argVal = expr->GetValue(ctx);
1045  return ctx->NotOperator(argVal, LLVMGetName(argVal, "_logicalnot"));
1046  }
1047  case BitNot: {
1048  llvm::Value *argVal = expr->GetValue(ctx);
1049  return ctx->NotOperator(argVal, LLVMGetName(argVal, "_bitnot"));
1050  }
1051  default:
1052  FATAL("logic error");
1053  return NULL;
1054  }
1055 }
1056 
1057 const Type *UnaryExpr::GetType() const {
1058  if (expr == NULL)
1059  return NULL;
1060 
1061  const Type *type = expr->GetType();
1062  if (type == NULL)
1063  return NULL;
1064 
1065  // For all unary expressions besides logical not, the returned type is
1066  // the same as the source type. Logical not always returns a bool
1067  // type, with the same shape as the input type.
1068  switch (op) {
1069  case PreInc:
1070  case PreDec:
1071  case PostInc:
1072  case PostDec:
1073  case Negate:
1074  case BitNot:
1075  return type;
1076  case LogicalNot:
1077  return lMatchingBoolType(type);
1078  default:
1079  FATAL("error");
1080  return NULL;
1081  }
1082 }
1083 
1084 template <typename T> static Expr *lOptimizeBitNot(ConstExpr *constExpr, const Type *type, SourcePos pos) {
1085  T v[ISPC_MAX_NVEC];
1086  int count = constExpr->GetValues(v);
1087  for (int i = 0; i < count; ++i)
1088  v[i] = ~v[i];
1089  return new ConstExpr(type, v, pos);
1090 }
1091 
1092 template <typename T> static Expr *lOptimizeNegate(ConstExpr *constExpr, const Type *type, SourcePos pos) {
1093  T v[ISPC_MAX_NVEC];
1094  int count = constExpr->GetValues(v);
1095  for (int i = 0; i < count; ++i)
1096  v[i] = -v[i];
1097  return new ConstExpr(type, v, pos);
1098 }
1099 
1101  ConstExpr *constExpr = llvm::dyn_cast<ConstExpr>(expr);
1102  // If the operand isn't a constant, then we can't do any optimization
1103  // here...
1104  if (constExpr == NULL)
1105  return this;
1106 
1107  const Type *type = constExpr->GetType();
1108  bool isEnumType = CastType<EnumType>(type) != NULL;
1109 
1110  switch (op) {
1111  case PreInc:
1112  case PreDec:
1113  case PostInc:
1114  case PostDec:
1115  // this shouldn't happen--it's illegal to modify a contant value..
1116  // An error will be issued elsewhere...
1117  return this;
1118  case Negate: {
1121  return lOptimizeNegate<int64_t>(constExpr, type, pos);
1124  return lOptimizeNegate<uint64_t>(constExpr, type, pos);
1127  return lOptimizeNegate<int32_t>(constExpr, type, pos);
1130  return lOptimizeNegate<uint32_t>(constExpr, type, pos);
1133  return lOptimizeNegate<int16_t>(constExpr, type, pos);
1136  return lOptimizeNegate<uint16_t>(constExpr, type, pos);
1139  return lOptimizeNegate<int8_t>(constExpr, type, pos);
1142  return lOptimizeNegate<uint8_t>(constExpr, type, pos);
1143  } else {
1144  // For all the other types, it's safe to stuff whatever we have
1145  // into a double, do the negate as a double, and then return a
1146  // ConstExpr with the same type as the original...
1147  double v[ISPC_MAX_NVEC];
1148  int count = constExpr->GetValues(v);
1149  for (int i = 0; i < count; ++i)
1150  v[i] = -v[i];
1151  return new ConstExpr(constExpr, v);
1152  }
1153  }
1154  case BitNot: {
1157  return lOptimizeBitNot<int8_t>(constExpr, type, pos);
1160  return lOptimizeBitNot<uint8_t>(constExpr, type, pos);
1163  return lOptimizeBitNot<int16_t>(constExpr, type, pos);
1166  return lOptimizeBitNot<uint16_t>(constExpr, type, pos);
1169  return lOptimizeBitNot<int32_t>(constExpr, type, pos);
1171  Type::EqualIgnoringConst(type, AtomicType::VaryingUInt32) || isEnumType == true) {
1172  return lOptimizeBitNot<uint32_t>(constExpr, type, pos);
1175  return lOptimizeBitNot<int64_t>(constExpr, type, pos);
1178  return lOptimizeBitNot<uint64_t>(constExpr, type, pos);
1179  } else
1180  FATAL("unexpected type in UnaryExpr::Optimize() / BitNot case");
1181  }
1182  case LogicalNot: {
1185  bool v[ISPC_MAX_NVEC];
1186  int count = constExpr->GetValues(v);
1187  for (int i = 0; i < count; ++i)
1188  v[i] = !v[i];
1189  return new ConstExpr(type, v, pos);
1190  }
1191  default:
1192  FATAL("unexpected op in UnaryExpr::Optimize()");
1193  return NULL;
1194  }
1195 }
1196 
1198  const Type *type;
1199  if (expr == NULL || (type = expr->GetType()) == NULL)
1200  // something went wrong in type checking...
1201  return NULL;
1202 
1203  if (type->IsSOAType()) {
1204  Error(pos, "Can't apply unary operator to SOA type \"%s\".", type->GetString().c_str());
1205  return NULL;
1206  }
1207 
1208  if (op == PreInc || op == PreDec || op == PostInc || op == PostDec) {
1209  if (type->IsConstType()) {
1210  Error(pos,
1211  "Can't assign to type \"%s\" on left-hand side of "
1212  "expression.",
1213  type->GetString().c_str());
1214  return NULL;
1215  }
1216 
1217  if (type->IsNumericType())
1218  return this;
1219 
1220  const PointerType *pt = CastType<PointerType>(type);
1221  if (pt == NULL) {
1222  Error(expr->pos,
1223  "Can only pre/post increment numeric and "
1224  "pointer types, not \"%s\".",
1225  type->GetString().c_str());
1226  return NULL;
1227  }
1228 
1229  if (PointerType::IsVoidPointer(type)) {
1230  Error(expr->pos, "Illegal to pre/post increment \"%s\" type.", type->GetString().c_str());
1231  return NULL;
1232  }
1233  if (CastType<UndefinedStructType>(pt->GetBaseType())) {
1234  Error(expr->pos,
1235  "Illegal to pre/post increment pointer to "
1236  "undefined struct type \"%s\".",
1237  type->GetString().c_str());
1238  return NULL;
1239  }
1240 
1241  return this;
1242  }
1243 
1244  // don't do this for pre/post increment/decrement
1245  if (CastType<ReferenceType>(type)) {
1246  expr = new RefDerefExpr(expr, pos);
1247  type = expr->GetType();
1248  }
1249 
1250  if (op == Negate) {
1251  if (!type->IsNumericType()) {
1252  Error(expr->pos, "Negate not allowed for non-numeric type \"%s\".", type->GetString().c_str());
1253  return NULL;
1254  }
1255  } else if (op == LogicalNot) {
1256  const Type *boolType = lMatchingBoolType(type);
1257  expr = TypeConvertExpr(expr, boolType, "logical not");
1258  if (expr == NULL)
1259  return NULL;
1260  } else if (op == BitNot) {
1261  if (!type->IsIntType()) {
1262  Error(expr->pos,
1263  "~ operator can only be used with integer types, "
1264  "not \"%s\".",
1265  type->GetString().c_str());
1266  return NULL;
1267  }
1268  }
1269  return this;
1270 }
1271 
1273  if (llvm::dyn_cast<ConstExpr>(expr) != NULL)
1274  return 0;
1275 
1277 }
1278 
1279 void UnaryExpr::Print() const {
1280  if (!expr || !GetType())
1281  return;
1282 
1283  printf("[ %s ] (", GetType()->GetString().c_str());
1284  if (op == PreInc)
1285  printf("++");
1286  if (op == PreDec)
1287  printf("--");
1288  if (op == Negate)
1289  printf("-");
1290  if (op == LogicalNot)
1291  printf("!");
1292  if (op == BitNot)
1293  printf("~");
1294  printf("(");
1295  expr->Print();
1296  printf(")");
1297  if (op == PostInc)
1298  printf("++");
1299  if (op == PostDec)
1300  printf("--");
1301  printf(")");
1302  pos.Print();
1303 }
1304 
1305 ///////////////////////////////////////////////////////////////////////////
1306 // BinaryExpr
1307 
1308 static const char *lOpString(BinaryExpr::Op op) {
1309  switch (op) {
1310  case BinaryExpr::Add:
1311  return "+";
1312  case BinaryExpr::Sub:
1313  return "-";
1314  case BinaryExpr::Mul:
1315  return "*";
1316  case BinaryExpr::Div:
1317  return "/";
1318  case BinaryExpr::Mod:
1319  return "%";
1320  case BinaryExpr::Shl:
1321  return "<<";
1322  case BinaryExpr::Shr:
1323  return ">>";
1324  case BinaryExpr::Lt:
1325  return "<";
1326  case BinaryExpr::Gt:
1327  return ">";
1328  case BinaryExpr::Le:
1329  return "<=";
1330  case BinaryExpr::Ge:
1331  return ">=";
1332  case BinaryExpr::Equal:
1333  return "==";
1334  case BinaryExpr::NotEqual:
1335  return "!=";
1336  case BinaryExpr::BitAnd:
1337  return "&";
1338  case BinaryExpr::BitXor:
1339  return "^";
1340  case BinaryExpr::BitOr:
1341  return "|";
1343  return "&&";
1344  case BinaryExpr::LogicalOr:
1345  return "||";
1346  case BinaryExpr::Comma:
1347  return ",";
1348  default:
1349  FATAL("unimplemented case in lOpString()");
1350  return "";
1351  }
1352 }
1353 
1354 /** Utility routine to emit the binary bitwise operator corresponding to
1355  the given BinaryExpr::Op.
1356 */
1357 static llvm::Value *lEmitBinaryBitOp(BinaryExpr::Op op, llvm::Value *arg0Val, llvm::Value *arg1Val, bool isUnsigned,
1358  FunctionEmitContext *ctx) {
1359  llvm::Instruction::BinaryOps inst;
1360  switch (op) {
1361  case BinaryExpr::Shl:
1362  inst = llvm::Instruction::Shl;
1363  break;
1364  case BinaryExpr::Shr:
1365  if (isUnsigned)
1366  inst = llvm::Instruction::LShr;
1367  else
1368  inst = llvm::Instruction::AShr;
1369  break;
1370  case BinaryExpr::BitAnd:
1371  inst = llvm::Instruction::And;
1372  break;
1373  case BinaryExpr::BitXor:
1374  inst = llvm::Instruction::Xor;
1375  break;
1376  case BinaryExpr::BitOr:
1377  inst = llvm::Instruction::Or;
1378  break;
1379  default:
1380  FATAL("logic error in lEmitBinaryBitOp()");
1381  return NULL;
1382  }
1383 
1384  return ctx->BinaryOperator(inst, arg0Val, arg1Val, "bitop");
1385 }
1386 
1387 static llvm::Value *lEmitBinaryPointerArith(BinaryExpr::Op op, llvm::Value *value0, llvm::Value *value1,
1388  const Type *type0, const Type *type1, FunctionEmitContext *ctx,
1389  SourcePos pos) {
1390  const PointerType *ptrType = CastType<PointerType>(type0);
1391  AssertPos(pos, ptrType != NULL);
1392  switch (op) {
1393  case BinaryExpr::Add:
1394  // ptr + integer
1395  return ctx->GetElementPtrInst(value0, value1, ptrType, "ptrmath");
1396  break;
1397  case BinaryExpr::Sub: {
1398  if (CastType<PointerType>(type1) != NULL) {
1399  AssertPos(pos, Type::EqualIgnoringConst(type0, type1));
1400 
1401  if (ptrType->IsSlice()) {
1402  llvm::Value *p0 = ctx->ExtractInst(value0, 0);
1403  llvm::Value *p1 = ctx->ExtractInst(value1, 0);
1404  const Type *majorType = ptrType->GetAsNonSlice();
1405  llvm::Value *majorDelta = lEmitBinaryPointerArith(op, p0, p1, majorType, majorType, ctx, pos);
1406 
1407  int soaWidth = ptrType->GetBaseType()->GetSOAWidth();
1408  AssertPos(pos, soaWidth > 0);
1409  llvm::Value *soaScale = LLVMIntAsType(soaWidth, majorDelta->getType());
1410 
1411  llvm::Value *majorScale =
1412  ctx->BinaryOperator(llvm::Instruction::Mul, majorDelta, soaScale, "major_soa_scaled");
1413 
1414  llvm::Value *m0 = ctx->ExtractInst(value0, 1);
1415  llvm::Value *m1 = ctx->ExtractInst(value1, 1);
1416  llvm::Value *minorDelta = ctx->BinaryOperator(llvm::Instruction::Sub, m0, m1, "minor_soa_delta");
1417 
1418  ctx->MatchIntegerTypes(&majorScale, &minorDelta);
1419  return ctx->BinaryOperator(llvm::Instruction::Add, majorScale, minorDelta, "soa_ptrdiff");
1420  }
1421 
1422  // ptr - ptr
1423  if (ptrType->IsUniformType()) {
1424  value0 = ctx->PtrToIntInst(value0);
1425  value1 = ctx->PtrToIntInst(value1);
1426  }
1427 
1428  // Compute the difference in bytes
1429  llvm::Value *delta = ctx->BinaryOperator(llvm::Instruction::Sub, value0, value1, "ptr_diff");
1430 
1431  // Now divide by the size of the type that the pointer
1432  // points to in order to return the difference in elements.
1433  llvm::Type *llvmElementType = ptrType->GetBaseType()->LLVMType(g->ctx);
1434  llvm::Value *size = g->target->SizeOf(llvmElementType, ctx->GetCurrentBasicBlock());
1435  if (ptrType->IsVaryingType())
1436  size = ctx->SmearUniform(size);
1437 
1438  if (g->target->is32Bit() == false && g->opt.force32BitAddressing == true) {
1439  // If we're doing 32-bit addressing math on a 64-bit
1440  // target, then trunc the delta down to a 32-bit value.
1441  // (Thus also matching what will be a 32-bit value
1442  // returned from SizeOf above.)
1443  if (ptrType->IsUniformType())
1444  delta = ctx->TruncInst(delta, LLVMTypes::Int32Type, "trunc_ptr_delta");
1445  else
1446  delta = ctx->TruncInst(delta, LLVMTypes::Int32VectorType, "trunc_ptr_delta");
1447  }
1448 
1449  // And now do the actual division
1450  return ctx->BinaryOperator(llvm::Instruction::SDiv, delta, size, "element_diff");
1451  } else {
1452  // ptr - integer
1453  llvm::Value *zero = lLLVMConstantValue(type1, g->ctx, 0.);
1454  llvm::Value *negOffset = ctx->BinaryOperator(llvm::Instruction::Sub, zero, value1, "negate");
1455  // Do a GEP as ptr + -integer
1456  return ctx->GetElementPtrInst(value0, negOffset, ptrType, "ptrmath");
1457  }
1458  }
1459  default:
1460  FATAL("Logic error in lEmitBinaryArith() for pointer type case");
1461  return NULL;
1462  }
1463 }
1464 
1465 /** Utility routine to emit binary arithmetic operator based on the given
1466  BinaryExpr::Op.
1467 */
1468 static llvm::Value *lEmitBinaryArith(BinaryExpr::Op op, llvm::Value *value0, llvm::Value *value1, const Type *type0,
1469  const Type *type1, FunctionEmitContext *ctx, SourcePos pos) {
1470  const PointerType *ptrType = CastType<PointerType>(type0);
1471 
1472  if (ptrType != NULL)
1473  return lEmitBinaryPointerArith(op, value0, value1, type0, type1, ctx, pos);
1474  else {
1475  AssertPos(pos, Type::EqualIgnoringConst(type0, type1));
1476 
1477  llvm::Instruction::BinaryOps inst;
1478  bool isFloatOp = type0->IsFloatType();
1479  bool isUnsignedOp = type0->IsUnsignedType();
1480 
1481  const char *opName = NULL;
1482  switch (op) {
1483  case BinaryExpr::Add:
1484  opName = "add";
1485  inst = isFloatOp ? llvm::Instruction::FAdd : llvm::Instruction::Add;
1486  break;
1487  case BinaryExpr::Sub:
1488  opName = "sub";
1489  inst = isFloatOp ? llvm::Instruction::FSub : llvm::Instruction::Sub;
1490  break;
1491  case BinaryExpr::Mul:
1492  opName = "mul";
1493  inst = isFloatOp ? llvm::Instruction::FMul : llvm::Instruction::Mul;
1494  break;
1495  case BinaryExpr::Div:
1496  opName = "div";
1497  if (type0->IsVaryingType() && !isFloatOp)
1498  PerformanceWarning(pos, "Division with varying integer types is "
1499  "very inefficient.");
1500  inst = isFloatOp ? llvm::Instruction::FDiv
1501  : (isUnsignedOp ? llvm::Instruction::UDiv : llvm::Instruction::SDiv);
1502  break;
1503  case BinaryExpr::Mod:
1504  opName = "mod";
1505  if (type0->IsVaryingType() && !isFloatOp)
1506  PerformanceWarning(pos, "Modulus operator with varying types is "
1507  "very inefficient.");
1508  inst = isFloatOp ? llvm::Instruction::FRem
1509  : (isUnsignedOp ? llvm::Instruction::URem : llvm::Instruction::SRem);
1510  break;
1511  default:
1512  FATAL("Invalid op type passed to lEmitBinaryArith()");
1513  return NULL;
1514  }
1515 
1516  return ctx->BinaryOperator(inst, value0, value1, LLVMGetName(opName, value0, value1));
1517  }
1518 }
1519 
1520 /** Utility routine to emit a binary comparison operator based on the given
1521  BinaryExpr::Op.
1522  */
1523 static llvm::Value *lEmitBinaryCmp(BinaryExpr::Op op, llvm::Value *e0Val, llvm::Value *e1Val, const Type *type,
1524  FunctionEmitContext *ctx, SourcePos pos) {
1525  bool isFloatOp = type->IsFloatType();
1526  bool isUnsignedOp = type->IsUnsignedType();
1527 
1528  llvm::CmpInst::Predicate pred;
1529  const char *opName = NULL;
1530  switch (op) {
1531  case BinaryExpr::Lt:
1532  opName = "less";
1533  pred = isFloatOp ? llvm::CmpInst::FCMP_OLT : (isUnsignedOp ? llvm::CmpInst::ICMP_ULT : llvm::CmpInst::ICMP_SLT);
1534  break;
1535  case BinaryExpr::Gt:
1536  opName = "greater";
1537  pred = isFloatOp ? llvm::CmpInst::FCMP_OGT : (isUnsignedOp ? llvm::CmpInst::ICMP_UGT : llvm::CmpInst::ICMP_SGT);
1538  break;
1539  case BinaryExpr::Le:
1540  opName = "lessequal";
1541  pred = isFloatOp ? llvm::CmpInst::FCMP_OLE : (isUnsignedOp ? llvm::CmpInst::ICMP_ULE : llvm::CmpInst::ICMP_SLE);
1542  break;
1543  case BinaryExpr::Ge:
1544  opName = "greaterequal";
1545  pred = isFloatOp ? llvm::CmpInst::FCMP_OGE : (isUnsignedOp ? llvm::CmpInst::ICMP_UGE : llvm::CmpInst::ICMP_SGE);
1546  break;
1547  case BinaryExpr::Equal:
1548  opName = "equal";
1549  pred = isFloatOp ? llvm::CmpInst::FCMP_OEQ : llvm::CmpInst::ICMP_EQ;
1550  break;
1551  case BinaryExpr::NotEqual:
1552  opName = "notequal";
1553  pred = isFloatOp ? llvm::CmpInst::FCMP_UNE : llvm::CmpInst::ICMP_NE;
1554  break;
1555  default:
1556  FATAL("error in lEmitBinaryCmp()");
1557  return NULL;
1558  }
1559 
1560  llvm::Value *cmp = ctx->CmpInst(isFloatOp ? llvm::Instruction::FCmp : llvm::Instruction::ICmp, pred, e0Val, e1Val,
1561  LLVMGetName(opName, e0Val, e1Val));
1562  // This is a little ugly: CmpInst returns i1 values, but we use vectors
1563  // of i32s for varying bool values; type convert the result here if
1564  // needed.
1565  if (type->IsVaryingType())
1566  cmp = ctx->I1VecToBoolVec(cmp);
1567 
1568  return cmp;
1569 }
1570 
1572  arg0 = a;
1573  arg1 = b;
1574 }
1575 
1577  if ((a0 == NULL) || (a1 == NULL)) {
1578  return NULL;
1579  }
1580  Expr *arg0 = a0;
1581  Expr *arg1 = a1;
1582  const Type *type0 = arg0->GetType();
1583  const Type *type1 = arg1->GetType();
1584 
1585  // If either operand is a reference, dereference it before we move
1586  // forward
1587  if (CastType<ReferenceType>(type0) != NULL) {
1588  arg0 = new RefDerefExpr(arg0, arg0->pos);
1589  type0 = arg0->GetType();
1590  }
1591  if (CastType<ReferenceType>(type1) != NULL) {
1592  arg1 = new RefDerefExpr(arg1, arg1->pos);
1593  type1 = arg1->GetType();
1594  }
1595  if ((type0 == NULL) || (type1 == NULL)) {
1596  return NULL;
1597  }
1598  if (CastType<StructType>(type0) != NULL || CastType<StructType>(type1) != NULL) {
1599  std::string opName = std::string("operator") + lOpString(bop);
1600  std::vector<Symbol *> funs;
1601  m->symbolTable->LookupFunction(opName.c_str(), &funs);
1602  if (funs.size() == 0) {
1603  Error(sp, "operator %s(%s, %s) is not defined.", opName.c_str(), (type0->GetString()).c_str(),
1604  (type1->GetString()).c_str());
1605  return NULL;
1606  }
1607  Expr *func = new FunctionSymbolExpr(opName.c_str(), funs, sp);
1608  ExprList *args = new ExprList(sp);
1609  args->exprs.push_back(arg0);
1610  args->exprs.push_back(arg1);
1611  Expr *opCallExpr = new FunctionCallExpr(func, args, sp);
1612  return opCallExpr;
1613  }
1614  return NULL;
1615 }
1616 
1618  Expr *op = lCreateBinaryOperatorCall(o, a, b, p);
1619  if (op != NULL) {
1620  return op;
1621  }
1622  op = new BinaryExpr(o, a, b, p);
1623  return op;
1624 }
1625 
1626 /** Emit code for a && or || logical operator. In particular, the code
1627  here handles "short-circuit" evaluation, where the second expression
1628  isn't evaluated if the value of the first one determines the value of
1629  the result.
1630 */
1632 
1633  const Type *type0 = arg0->GetType(), *type1 = arg1->GetType();
1634  if (type0 == NULL || type1 == NULL) {
1635  AssertPos(pos, m->errorCount > 0);
1636  return NULL;
1637  }
1638 
1639  // There is overhead (branches, etc.), to short-circuiting, so if the
1640  // right side of the expression is a) relatively simple, and b) can be
1641  // safely executed with an all-off execution mask, then we just
1642  // evaluate both sides and then the logical operator in that case.
1643  // FIXME: not sure what we should do about vector types here...
1644  bool shortCircuit =
1646  CastType<VectorType>(type0) != NULL || CastType<VectorType>(type1) != NULL);
1647  if (shortCircuit == false) {
1648  // If one of the operands is uniform but the other is varying,
1649  // promote the uniform one to varying
1650  if (type0->IsUniformType() && type1->IsVaryingType()) {
1652  AssertPos(pos, arg0 != NULL);
1653  }
1654  if (type1->IsUniformType() && type0->IsVaryingType()) {
1656  AssertPos(pos, arg1 != NULL);
1657  }
1658 
1659  llvm::Value *value0 = arg0->GetValue(ctx);
1660  llvm::Value *value1 = arg1->GetValue(ctx);
1661  if (value0 == NULL || value1 == NULL) {
1662  AssertPos(pos, m->errorCount > 0);
1663  return NULL;
1664  }
1665 
1666  if (op == BinaryExpr::LogicalAnd)
1667  return ctx->BinaryOperator(llvm::Instruction::And, value0, value1, "logical_and");
1668  else {
1669  AssertPos(pos, op == BinaryExpr::LogicalOr);
1670  return ctx->BinaryOperator(llvm::Instruction::Or, value0, value1, "logical_or");
1671  }
1672  }
1673 
1674  // Allocate temporary storage for the return value
1675  const Type *retType = Type::MoreGeneralType(type0, type1, pos, lOpString(op));
1676  if (retType == NULL) {
1677  AssertPos(pos, m->errorCount > 0);
1678  return NULL;
1679  }
1680  llvm::Value *retPtr = ctx->AllocaInst(retType, "logical_op_mem");
1681  llvm::BasicBlock *bbSkipEvalValue1 = ctx->CreateBasicBlock("skip_eval_1");
1682  llvm::BasicBlock *bbEvalValue1 = ctx->CreateBasicBlock("eval_1");
1683  llvm::BasicBlock *bbLogicalDone = ctx->CreateBasicBlock("logical_op_done");
1684 
1685  // Evaluate the first operand
1686  llvm::Value *value0 = arg0->GetValue(ctx);
1687  if (value0 == NULL) {
1688  AssertPos(pos, m->errorCount > 0);
1689  return NULL;
1690  }
1691 
1692  if (type0->IsUniformType()) {
1693  // Check to see if the value of the first operand is true or false
1694  llvm::Value *value0True = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, value0, LLVMTrue);
1695 
1696  if (op == BinaryExpr::LogicalOr) {
1697  // For ||, if value0 is true, then we skip evaluating value1
1698  // entirely.
1699  ctx->BranchInst(bbSkipEvalValue1, bbEvalValue1, value0True);
1700 
1701  // If value0 is true, the complete result is true (either
1702  // uniform or varying)
1703  ctx->SetCurrentBasicBlock(bbSkipEvalValue1);
1704  llvm::Value *trueValue = retType->IsUniformType() ? LLVMTrue : LLVMMaskAllOn;
1705  ctx->StoreInst(trueValue, retPtr, retType);
1706  ctx->BranchInst(bbLogicalDone);
1707  } else {
1708  AssertPos(pos, op == BinaryExpr::LogicalAnd);
1709 
1710  // Conversely, for &&, if value0 is false, we skip evaluating
1711  // value1.
1712  ctx->BranchInst(bbEvalValue1, bbSkipEvalValue1, value0True);
1713 
1714  // In this case, the complete result is false (again, either a
1715  // uniform or varying false).
1716  ctx->SetCurrentBasicBlock(bbSkipEvalValue1);
1717  llvm::Value *falseValue = retType->IsUniformType() ? LLVMFalse : LLVMMaskAllOff;
1718  ctx->StoreInst(falseValue, retPtr, retType);
1719  ctx->BranchInst(bbLogicalDone);
1720  }
1721 
1722  // Both || and && are in the same situation if the first operand's
1723  // value didn't resolve the final result: they need to evaluate the
1724  // value of the second operand, which in turn gives the value for
1725  // the full expression.
1726  ctx->SetCurrentBasicBlock(bbEvalValue1);
1727  if (type1->IsUniformType() && retType->IsVaryingType()) {
1728  arg1 = TypeConvertExpr(arg1, AtomicType::VaryingBool, "logical op");
1729  AssertPos(pos, arg1 != NULL);
1730  }
1731 
1732  llvm::Value *value1 = arg1->GetValue(ctx);
1733  if (value1 == NULL) {
1734  AssertPos(pos, m->errorCount > 0);
1735  return NULL;
1736  }
1737  ctx->StoreInst(value1, retPtr, arg1->GetType());
1738  ctx->BranchInst(bbLogicalDone);
1739 
1740  // In all cases, we end up at the bbLogicalDone basic block;
1741  // loading the value stored in retPtr in turn gives the overall
1742  // result.
1743  ctx->SetCurrentBasicBlock(bbLogicalDone);
1744  return ctx->LoadInst(retPtr, retType);
1745  } else {
1746  // Otherwise, the first operand is varying... Save the current
1747  // value of the mask so that we can restore it at the end.
1748  llvm::Value *oldMask = ctx->GetInternalMask();
1749  llvm::Value *oldFullMask = ctx->GetFullMask();
1750 
1751  // Convert the second operand to be varying as well, so that we can
1752  // perform logical vector ops with its value.
1753  if (type1->IsUniformType()) {
1754  arg1 = TypeConvertExpr(arg1, AtomicType::VaryingBool, "logical op");
1755  AssertPos(pos, arg1 != NULL);
1756  type1 = arg1->GetType();
1757  }
1758 
1759  if (op == BinaryExpr::LogicalOr) {
1760  // See if value0 is true for all currently executing
1761  // lanes--i.e. if (value0 & mask) == mask. If so, we don't
1762  // need to evaluate the second operand of the expression.
1763  llvm::Value *value0AndMask = ctx->BinaryOperator(llvm::Instruction::And, value0, oldFullMask, "op&mask");
1764  llvm::Value *equalsMask = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, value0AndMask,
1765  oldFullMask, "value0&mask==mask");
1766  equalsMask = ctx->I1VecToBoolVec(equalsMask);
1767  llvm::Value *allMatch = ctx->All(equalsMask);
1768  ctx->BranchInst(bbSkipEvalValue1, bbEvalValue1, allMatch);
1769 
1770  // value0 is true for all running lanes, so it can be used for
1771  // the final result
1772  ctx->SetCurrentBasicBlock(bbSkipEvalValue1);
1773  ctx->StoreInst(value0, retPtr, arg0->GetType());
1774  ctx->BranchInst(bbLogicalDone);
1775 
1776  // Otherwise, we need to valuate arg1. However, first we need
1777  // to set the execution mask to be (oldMask & ~a); in other
1778  // words, only execute the instances where value0 is false.
1779  // For the instances where value0 was true, we need to inhibit
1780  // execution.
1781  ctx->SetCurrentBasicBlock(bbEvalValue1);
1782  ctx->SetInternalMaskAndNot(oldMask, value0);
1783 
1784  llvm::Value *value1 = arg1->GetValue(ctx);
1785  if (value1 == NULL) {
1786  AssertPos(pos, m->errorCount > 0);
1787  return NULL;
1788  }
1789 
1790  // We need to compute the result carefully, since vector
1791  // elements that were computed when the corresponding lane was
1792  // disabled have undefined values:
1793  // result = (value0 & old_mask) | (value1 & current_mask)
1794  llvm::Value *value1AndMask =
1795  ctx->BinaryOperator(llvm::Instruction::And, value1, ctx->GetInternalMask(), "op&mask");
1796  llvm::Value *result = ctx->BinaryOperator(llvm::Instruction::Or, value0AndMask, value1AndMask, "or_result");
1797  ctx->StoreInst(result, retPtr, retType);
1798  ctx->BranchInst(bbLogicalDone);
1799  } else {
1800  AssertPos(pos, op == BinaryExpr::LogicalAnd);
1801 
1802  // If value0 is false for all currently running lanes, the
1803  // overall result must be false: this corresponds to checking
1804  // if (mask & ~value0) == mask.
1805  llvm::Value *notValue0 = ctx->NotOperator(value0, "not_value0");
1806  llvm::Value *notValue0AndMask =
1807  ctx->BinaryOperator(llvm::Instruction::And, notValue0, oldFullMask, "not_value0&mask");
1808  llvm::Value *equalsMask = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_EQ, notValue0AndMask,
1809  oldFullMask, "not_value0&mask==mask");
1810  equalsMask = ctx->I1VecToBoolVec(equalsMask);
1811  llvm::Value *allMatch = ctx->All(equalsMask);
1812  ctx->BranchInst(bbSkipEvalValue1, bbEvalValue1, allMatch);
1813 
1814  // value0 was false for all running lanes, so use its value as
1815  // the overall result.
1816  ctx->SetCurrentBasicBlock(bbSkipEvalValue1);
1817  ctx->StoreInst(value0, retPtr, arg0->GetType());
1818  ctx->BranchInst(bbLogicalDone);
1819 
1820  // Otherwise we need to evaluate value1, but again with the
1821  // mask set to only be on for the lanes where value0 was true.
1822  // For the lanes where value0 was false, execution needs to be
1823  // disabled: mask = (mask & value0).
1824  ctx->SetCurrentBasicBlock(bbEvalValue1);
1825  ctx->SetInternalMaskAnd(oldMask, value0);
1826 
1827  llvm::Value *value1 = arg1->GetValue(ctx);
1828  if (value1 == NULL) {
1829  AssertPos(pos, m->errorCount > 0);
1830  return NULL;
1831  }
1832 
1833  // And as in the || case, we compute the overall result by
1834  // masking off the valid lanes before we AND them together:
1835  // result = (value0 & old_mask) & (value1 & current_mask)
1836  llvm::Value *value0AndMask = ctx->BinaryOperator(llvm::Instruction::And, value0, oldFullMask, "op&mask");
1837  llvm::Value *value1AndMask =
1838  ctx->BinaryOperator(llvm::Instruction::And, value1, ctx->GetInternalMask(), "value1&mask");
1839  llvm::Value *result =
1840  ctx->BinaryOperator(llvm::Instruction::And, value0AndMask, value1AndMask, "or_result");
1841  ctx->StoreInst(result, retPtr, retType);
1842  ctx->BranchInst(bbLogicalDone);
1843  }
1844 
1845  // And finally we always end up in bbLogicalDone, where we restore
1846  // the old mask and return the computed result
1847  ctx->SetCurrentBasicBlock(bbLogicalDone);
1848  ctx->SetInternalMask(oldMask);
1849  return ctx->LoadInst(retPtr, retType);
1850  }
1851 }
1852 
1853 /* Returns true if shifting right by the given amount will lead to
1854  inefficient code. (Assumes x86 target. May also warn inaccurately if
1855  later optimization simplify the shift amount more than we are able to
1856  see at this point.) */
1857 static bool lIsDifficultShiftAmount(Expr *expr) {
1858  // Uniform shifts (of uniform values) are no problem.
1859  if (expr->GetType()->IsVaryingType() == false)
1860  return false;
1861 
1862  ConstExpr *ce = llvm::dyn_cast<ConstExpr>(expr);
1863  if (ce) {
1864  // If the shift is by a constant amount, *and* it's the same amount
1865  // in all vector lanes, we're in good shape.
1866  uint32_t amount[ISPC_MAX_NVEC];
1867  int count = ce->GetValues(amount);
1868  for (int i = 1; i < count; ++i)
1869  if (amount[i] != amount[0])
1870  return true;
1871  return false;
1872  }
1873 
1874  TypeCastExpr *tce = llvm::dyn_cast<TypeCastExpr>(expr);
1875  if (tce && tce->expr) {
1876  // Finally, if the shift amount is given by a uniform value that's
1877  // been smeared out into a varying, we have the same shift for all
1878  // lanes and are also in good shape.
1879  return (tce->expr->GetType()->IsUniformType() == false);
1880  }
1881 
1882  return true;
1883 }
1884 
1885 llvm::Value *BinaryExpr::GetValue(FunctionEmitContext *ctx) const {
1886  if (!arg0 || !arg1) {
1887  AssertPos(pos, m->errorCount > 0);
1888  return NULL;
1889  }
1890 
1891  // Handle these specially, since we want to short-circuit their evaluation...
1892  if (op == LogicalAnd || op == LogicalOr)
1893  return lEmitLogicalOp(op, arg0, arg1, ctx, pos);
1894 
1895  llvm::Value *value0 = arg0->GetValue(ctx);
1896  llvm::Value *value1 = arg1->GetValue(ctx);
1897  if (value0 == NULL || value1 == NULL) {
1898  AssertPos(pos, m->errorCount > 0);
1899  return NULL;
1900  }
1901 
1902  ctx->SetDebugPos(pos);
1903 
1904  switch (op) {
1905  case Add:
1906  case Sub:
1907  case Mul:
1908  case Div:
1909  case Mod:
1910  return lEmitBinaryArith(op, value0, value1, arg0->GetType(), arg1->GetType(), ctx, pos);
1911  case Lt:
1912  case Gt:
1913  case Le:
1914  case Ge:
1915  case Equal:
1916  case NotEqual:
1917  return lEmitBinaryCmp(op, value0, value1, arg0->GetType(), ctx, pos);
1918  case Shl:
1919  case Shr:
1920  case BitAnd:
1921  case BitXor:
1922  case BitOr: {
1923  if (op == Shr && lIsDifficultShiftAmount(arg1))
1924  PerformanceWarning(pos, "Shift right is inefficient for "
1925  "varying shift amounts.");
1926  return lEmitBinaryBitOp(op, value0, value1, arg0->GetType()->IsUnsignedType(), ctx);
1927  }
1928  case Comma:
1929  return value1;
1930  default:
1931  FATAL("logic error");
1932  return NULL;
1933  }
1934 }
1935 
1936 const Type *BinaryExpr::GetType() const {
1937  if (arg0 == NULL || arg1 == NULL)
1938  return NULL;
1939 
1940  const Type *type0 = arg0->GetType(), *type1 = arg1->GetType();
1941  if (type0 == NULL || type1 == NULL)
1942  return NULL;
1943 
1944  // If this hits, it means that our TypeCheck() method hasn't been
1945  // called before GetType() was called; adding two pointers is illegal
1946  // and will fail type checking and (int + ptr) should be canonicalized
1947  // into (ptr + int) by type checking.
1948  if (op == Add)
1949  AssertPos(pos, CastType<PointerType>(type1) == NULL);
1950 
1951  if (op == Comma)
1952  return arg1->GetType();
1953 
1954  if (CastType<PointerType>(type0) != NULL) {
1955  if (op == Add)
1956  // ptr + int -> ptr
1957  return type0;
1958  else if (op == Sub) {
1959  if (CastType<PointerType>(type1) != NULL) {
1960  // ptr - ptr -> ~ptrdiff_t
1961  const Type *diffType = (g->target->is32Bit() || g->opt.force32BitAddressing) ? AtomicType::UniformInt32
1963  if (type0->IsVaryingType() || type1->IsVaryingType())
1964  diffType = diffType->GetAsVaryingType();
1965  return diffType;
1966  } else
1967  // ptr - int -> ptr
1968  return type0;
1969  }
1970 
1971  // otherwise fall through for these...
1972  AssertPos(pos, op == Lt || op == Gt || op == Le || op == Ge || op == Equal || op == NotEqual);
1973  }
1974 
1975  const Type *exprType = Type::MoreGeneralType(type0, type1, pos, lOpString(op));
1976  // I don't think that MoreGeneralType should be able to fail after the
1977  // checks done in BinaryExpr::TypeCheck().
1978  AssertPos(pos, exprType != NULL);
1979 
1980  switch (op) {
1981  case Add:
1982  case Sub:
1983  case Mul:
1984  case Div:
1985  case Mod:
1986  return exprType;
1987  case Lt:
1988  case Gt:
1989  case Le:
1990  case Ge:
1991  case Equal:
1992  case NotEqual:
1993  case LogicalAnd:
1994  case LogicalOr:
1995  return lMatchingBoolType(exprType);
1996  case Shl:
1997  case Shr:
1998  return type1->IsVaryingType() ? type0->GetAsVaryingType() : type0;
1999  case BitAnd:
2000  case BitXor:
2001  case BitOr:
2002  return exprType;
2003  case Comma:
2004  // handled above, so fall through here just in case
2005  default:
2006  FATAL("logic error in BinaryExpr::GetType()");
2007  return NULL;
2008  }
2009 }
2010 
2011 #define FOLD_OP(O, E) \
2012  case O: \
2013  for (int i = 0; i < count; ++i) \
2014  result[i] = (v0[i] E v1[i]); \
2015  break
2016 
2017 #define FOLD_OP_REF(O, E, TRef) \
2018  case O: \
2019  for (int i = 0; i < count; ++i) { \
2020  result[i] = (v0[i] E v1[i]); \
2021  TRef r = (TRef)v0[i] E(TRef) v1[i]; \
2022  if (result[i] != r) \
2023  Warning(pos, "Binary expression with type \"%s\" can't represent value.", \
2024  carg0->GetType()->GetString().c_str()); \
2025  } \
2026  break
2027 
2028 /** Constant fold the binary integer operations that aren't also applicable
2029  to floating-point types.
2030 */
2031 template <typename T, typename TRef>
2032 static ConstExpr *lConstFoldBinaryIntOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0, SourcePos pos) {
2033  T result[ISPC_MAX_NVEC];
2034  int count = carg0->Count();
2035 
2036  switch (op) {
2037  FOLD_OP_REF(BinaryExpr::Mod, %, TRef);
2038  FOLD_OP_REF(BinaryExpr::Shl, <<, TRef);
2039  FOLD_OP_REF(BinaryExpr::Shr, >>, TRef);
2040  FOLD_OP_REF(BinaryExpr::BitAnd, &, TRef);
2041  FOLD_OP_REF(BinaryExpr::BitXor, ^, TRef);
2042  FOLD_OP_REF(BinaryExpr::BitOr, |, TRef);
2043  default:
2044  return NULL;
2045  }
2046 
2047  return new ConstExpr(carg0->GetType(), result, carg0->pos);
2048 }
2049 
2050 /** Constant fold the binary logical ops.
2051  */
2052 template <typename T>
2053 static ConstExpr *lConstFoldBinaryLogicalOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0) {
2054  bool result[ISPC_MAX_NVEC];
2055  int count = carg0->Count();
2056 
2057  switch (op) {
2058  FOLD_OP(BinaryExpr::Lt, <);
2059  FOLD_OP(BinaryExpr::Gt, >);
2060  FOLD_OP(BinaryExpr::Le, <=);
2061  FOLD_OP(BinaryExpr::Ge, >=);
2066  default:
2067  return NULL;
2068  }
2069 
2071  return new ConstExpr(rType, result, carg0->pos);
2072 }
2073 
2074 /** Constant fold binary arithmetic ops.
2075  */
2076 template <typename T, typename TRef>
2077 static ConstExpr *lConstFoldBinaryArithOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0,
2078  SourcePos pos) {
2079  T result[ISPC_MAX_NVEC];
2080  int count = carg0->Count();
2081 
2082  switch (op) {
2083  FOLD_OP_REF(BinaryExpr::Add, +, TRef);
2084  FOLD_OP_REF(BinaryExpr::Sub, -, TRef);
2085  FOLD_OP_REF(BinaryExpr::Mul, *, TRef);
2086  case BinaryExpr::Div:
2087  for (int i = 0; i < count; ++i) {
2088  if (v1[i] == 0) {
2089  Error(pos, "Division by zero encountered in expression.");
2090  result[i] = 0;
2091  } else
2092  result[i] = (v0[i] / v1[i]);
2093  }
2094  break;
2095  default:
2096  return NULL;
2097  }
2098 
2099  return new ConstExpr(carg0->GetType(), result, carg0->pos);
2100 }
2101 
2102 /** Constant fold the various boolean binary ops.
2103  */
2104 static ConstExpr *lConstFoldBoolBinaryOp(BinaryExpr::Op op, const bool *v0, const bool *v1, ConstExpr *carg0) {
2105  bool result[ISPC_MAX_NVEC];
2106  int count = carg0->Count();
2107 
2108  switch (op) {
2112  FOLD_OP(BinaryExpr::Lt, <);
2113  FOLD_OP(BinaryExpr::Gt, >);
2114  FOLD_OP(BinaryExpr::Le, <=);
2115  FOLD_OP(BinaryExpr::Ge, >=);
2120  default:
2121  return NULL;
2122  }
2123 
2124  return new ConstExpr(carg0->GetType(), result, carg0->pos);
2125 }
2126 
2127 template <typename T>
2128 static Expr *lConstFoldBinaryFPOp(ConstExpr *constArg0, ConstExpr *constArg1, BinaryExpr::Op op, BinaryExpr *origExpr,
2129  SourcePos pos) {
2130  T v0[ISPC_MAX_NVEC], v1[ISPC_MAX_NVEC];
2131  constArg0->GetValues(v0);
2132  constArg1->GetValues(v1);
2133  ConstExpr *ret;
2134  if ((ret = lConstFoldBinaryArithOp<T, T>(op, v0, v1, constArg0, pos)) != NULL)
2135  return ret;
2136  else if ((ret = lConstFoldBinaryLogicalOp(op, v0, v1, constArg0)) != NULL)
2137  return ret;
2138  else
2139  return origExpr;
2140 }
2141 
2142 template <typename T, typename TRef>
2143 static Expr *lConstFoldBinaryIntOp(ConstExpr *constArg0, ConstExpr *constArg1, BinaryExpr::Op op, BinaryExpr *origExpr,
2144  SourcePos pos) {
2145  T v0[ISPC_MAX_NVEC], v1[ISPC_MAX_NVEC];
2146  constArg0->GetValues(v0);
2147  constArg1->GetValues(v1);
2148  ConstExpr *ret;
2149  if ((ret = lConstFoldBinaryArithOp<T, TRef>(op, v0, v1, constArg0, pos)) != NULL)
2150  return ret;
2151  else if ((ret = lConstFoldBinaryIntOp<T, TRef>(op, v0, v1, constArg0, pos)) != NULL)
2152  return ret;
2153  else if ((ret = lConstFoldBinaryLogicalOp(op, v0, v1, constArg0)) != NULL)
2154  return ret;
2155  else
2156  return origExpr;
2157 }
2158 
2159 /* Returns true if the given arguments (which are assumed to be the
2160  operands of a divide) represent a divide that can be performed by one of
2161  the __fast_idiv functions.
2162  */
2163 static bool lCanImproveVectorDivide(Expr *arg0, Expr *arg1, int *divisor) {
2164  const Type *type = arg0->GetType();
2165  if (!type)
2166  return false;
2167 
2168  // The value being divided must be an int8/16/32.
2175  return false;
2176 
2177  // The divisor must be the same compile-time constant value for all of
2178  // the vector lanes.
2179  ConstExpr *ce = llvm::dyn_cast<ConstExpr>(arg1);
2180  if (!ce)
2181  return false;
2182  int64_t div[ISPC_MAX_NVEC];
2183  int count = ce->GetValues(div);
2184  for (int i = 1; i < count; ++i)
2185  if (div[i] != div[0])
2186  return false;
2187  *divisor = div[0];
2188 
2189  // And finally, the divisor must be >= 2 and <128 (for 8-bit divides),
2190  // and <256 otherwise.
2191  if (*divisor < 2)
2192  return false;
2195  return *divisor < 128;
2196  else
2197  return *divisor < 256;
2198 }
2199 
2201  if (arg0 == NULL || arg1 == NULL)
2202  return NULL;
2203 
2204  ConstExpr *constArg0 = llvm::dyn_cast<ConstExpr>(arg0);
2205  ConstExpr *constArg1 = llvm::dyn_cast<ConstExpr>(arg1);
2206 
2207  if (g->opt.fastMath) {
2208  // optimizations related to division by floats..
2209 
2210  // transform x / const -> x * (1/const)
2211  if (op == Div && constArg1 != NULL) {
2212  const Type *type1 = constArg1->GetType();
2215  float inv[ISPC_MAX_NVEC];
2216  int count = constArg1->GetValues(inv);
2217  for (int i = 0; i < count; ++i)
2218  inv[i] = 1.f / inv[i];
2219  Expr *einv = new ConstExpr(type1, inv, constArg1->pos);
2220  Expr *e = new BinaryExpr(Mul, arg0, einv, pos);
2221  e = ::TypeCheck(e);
2222  if (e == NULL)
2223  return NULL;
2224  return ::Optimize(e);
2225  }
2226  }
2227 
2228  // transform x / y -> x * rcp(y)
2229  if (op == Div) {
2230  const Type *type1 = arg1->GetType();
2233  // Get the symbol for the appropriate builtin
2234  std::vector<Symbol *> rcpFuns;
2235  m->symbolTable->LookupFunction("rcp", &rcpFuns);
2236  if (rcpFuns.size() > 0) {
2237  Expr *rcpSymExpr = new FunctionSymbolExpr("rcp", rcpFuns, pos);
2238  ExprList *args = new ExprList(arg1, arg1->pos);
2239  Expr *rcpCall = new FunctionCallExpr(rcpSymExpr, args, arg1->pos);
2240  rcpCall = ::TypeCheck(rcpCall);
2241  if (rcpCall == NULL)
2242  return NULL;
2243  rcpCall = ::Optimize(rcpCall);
2244  if (rcpCall == NULL)
2245  return NULL;
2246 
2247  Expr *ret = new BinaryExpr(Mul, arg0, rcpCall, pos);
2248  ret = ::TypeCheck(ret);
2249  if (ret == NULL)
2250  return NULL;
2251  return ::Optimize(ret);
2252  } else
2253  Warning(pos, "rcp() not found from stdlib. Can't apply "
2254  "fast-math rcp optimization.");
2255  }
2256  }
2257  }
2258 
2259  int divisor;
2260  if (op == Div && lCanImproveVectorDivide(arg0, arg1, &divisor)) {
2261  Debug(pos, "Improving vector divide by constant %d", divisor);
2262 
2263  std::vector<Symbol *> idivFuns;
2264  m->symbolTable->LookupFunction("__fast_idiv", &idivFuns);
2265  if (idivFuns.size() == 0) {
2266  Warning(pos, "Couldn't find __fast_idiv to optimize integer divide. "
2267  "Are you compiling with --nostdlib?");
2268  return this;
2269  }
2270 
2271  Expr *idivSymExpr = new FunctionSymbolExpr("__fast_idiv", idivFuns, pos);
2272  ExprList *args = new ExprList(arg0, pos);
2273  args->exprs.push_back(new ConstExpr(AtomicType::UniformInt32, divisor, arg1->pos));
2274  Expr *idivCall = new FunctionCallExpr(idivSymExpr, args, pos);
2275 
2276  idivCall = ::TypeCheck(idivCall);
2277  if (idivCall == NULL)
2278  return NULL;
2279 
2281  idivCall = new TypeCastExpr(GetType(), idivCall, pos);
2282  return ::Optimize(idivCall);
2283  }
2284 
2285  // From here on out, we're just doing constant folding, so if both args
2286  // aren't constants then we're done...
2287  if (constArg0 == NULL || constArg1 == NULL)
2288  return this;
2289 
2291  const Type *type = arg0->GetType()->GetAsNonConstType();
2293  return lConstFoldBinaryFPOp<float>(constArg0, constArg1, op, this, pos);
2295  return lConstFoldBinaryFPOp<double>(constArg0, constArg1, op, this, pos);
2297  return lConstFoldBinaryIntOp<int8_t, int64_t>(constArg0, constArg1, op, this, pos);
2299  return lConstFoldBinaryIntOp<uint8_t, uint64_t>(constArg0, constArg1, op, this, pos);
2301  return lConstFoldBinaryIntOp<int16_t, int64_t>(constArg0, constArg1, op, this, pos);
2303  return lConstFoldBinaryIntOp<uint16_t, uint64_t>(constArg0, constArg1, op, this, pos);
2305  return lConstFoldBinaryIntOp<int32_t, int64_t>(constArg0, constArg1, op, this, pos);
2307  return lConstFoldBinaryIntOp<uint32_t, uint64_t>(constArg0, constArg1, op, this, pos);
2309  return lConstFoldBinaryIntOp<int64_t, int64_t>(constArg0, constArg1, op, this, pos);
2311  return lConstFoldBinaryIntOp<uint64_t, uint64_t>(constArg0, constArg1, op, this, pos);
2313  bool v0[ISPC_MAX_NVEC], v1[ISPC_MAX_NVEC];
2314  constArg0->GetValues(v0);
2315  constArg1->GetValues(v1);
2316  ConstExpr *ret;
2317  if ((ret = lConstFoldBoolBinaryOp(op, v0, v1, constArg0)) != NULL)
2318  return ret;
2319  else if ((ret = lConstFoldBinaryLogicalOp(op, v0, v1, constArg0)) != NULL)
2320  return ret;
2321  else
2322  return this;
2323  } else
2324  return this;
2325 }
2326 
2328  if (arg0 == NULL || arg1 == NULL)
2329  return NULL;
2330 
2331  const Type *type0 = arg0->GetType(), *type1 = arg1->GetType();
2332  if (type0 == NULL || type1 == NULL)
2333  return NULL;
2334 
2335  // If either operand is a reference, dereference it before we move
2336  // forward
2337  if (CastType<ReferenceType>(type0) != NULL) {
2338  arg0 = new RefDerefExpr(arg0, arg0->pos);
2339  type0 = arg0->GetType();
2340  AssertPos(pos, type0 != NULL);
2341  }
2342  if (CastType<ReferenceType>(type1) != NULL) {
2343  arg1 = new RefDerefExpr(arg1, arg1->pos);
2344  type1 = arg1->GetType();
2345  AssertPos(pos, type1 != NULL);
2346  }
2347 
2348  // Convert arrays to pointers to their first elements
2349  if (CastType<ArrayType>(type0) != NULL) {
2351  type0 = arg0->GetType();
2352  }
2353  if (CastType<ArrayType>(type1) != NULL) {
2355  type1 = arg1->GetType();
2356  }
2357 
2358  // Prohibit binary operators with SOA types
2359  if (type0->GetSOAWidth() > 0) {
2360  Error(arg0->pos,
2361  "Illegal to use binary operator %s with SOA type "
2362  "\"%s\".",
2363  lOpString(op), type0->GetString().c_str());
2364  return NULL;
2365  }
2366  if (type1->GetSOAWidth() > 0) {
2367  Error(arg1->pos,
2368  "Illegal to use binary operator %s with SOA type "
2369  "\"%s\".",
2370  lOpString(op), type1->GetString().c_str());
2371  return NULL;
2372  }
2373 
2374  const PointerType *pt0 = CastType<PointerType>(type0);
2375  const PointerType *pt1 = CastType<PointerType>(type1);
2376  if (pt0 != NULL && pt1 != NULL && op == Sub) {
2377  // Pointer subtraction
2378  if (PointerType::IsVoidPointer(type0)) {
2379  Error(pos,
2380  "Illegal to perform pointer arithmetic "
2381  "on \"%s\" type.",
2382  type0->GetString().c_str());
2383  return NULL;
2384  }
2385  if (PointerType::IsVoidPointer(type1)) {
2386  Error(pos,
2387  "Illegal to perform pointer arithmetic "
2388  "on \"%s\" type.",
2389  type1->GetString().c_str());
2390  return NULL;
2391  }
2392  if (CastType<UndefinedStructType>(pt0->GetBaseType())) {
2393  Error(pos,
2394  "Illegal to perform pointer arithmetic "
2395  "on undefined struct type \"%s\".",
2396  pt0->GetString().c_str());
2397  return NULL;
2398  }
2399  if (CastType<UndefinedStructType>(pt1->GetBaseType())) {
2400  Error(pos,
2401  "Illegal to perform pointer arithmetic "
2402  "on undefined struct type \"%s\".",
2403  pt1->GetString().c_str());
2404  return NULL;
2405  }
2406 
2407  const Type *t = Type::MoreGeneralType(type0, type1, pos, "-");
2408  if (t == NULL)
2409  return NULL;
2410 
2411  arg0 = TypeConvertExpr(arg0, t, "pointer subtraction");
2412  arg1 = TypeConvertExpr(arg1, t, "pointer subtraction");
2413  if (arg0 == NULL || arg1 == NULL)
2414  return NULL;
2415 
2416  return this;
2417  } else if (((pt0 != NULL || pt1 != NULL) && op == Add) || (pt0 != NULL && op == Sub)) {
2418  // Handle ptr + int, int + ptr, ptr - int
2419  if (pt0 != NULL && pt1 != NULL) {
2420  Error(pos, "Illegal to add two pointer types \"%s\" and \"%s\".", pt0->GetString().c_str(),
2421  pt1->GetString().c_str());
2422  return NULL;
2423  } else if (pt1 != NULL) {
2424  // put in canonical order with the pointer as the first operand
2425  // for GetValue()
2426  std::swap(arg0, arg1);
2427  std::swap(type0, type1);
2428  std::swap(pt0, pt1);
2429  }
2430 
2431  AssertPos(pos, pt0 != NULL);
2432 
2433  if (PointerType::IsVoidPointer(pt0)) {
2434  Error(pos,
2435  "Illegal to perform pointer arithmetic "
2436  "on \"%s\" type.",
2437  pt0->GetString().c_str());
2438  return NULL;
2439  }
2440  if (CastType<UndefinedStructType>(pt0->GetBaseType())) {
2441  Error(pos,
2442  "Illegal to perform pointer arithmetic "
2443  "on undefined struct type \"%s\".",
2444  pt0->GetString().c_str());
2445  return NULL;
2446  }
2447 
2449  if (pt0->IsVaryingType())
2450  offsetType = offsetType->GetAsVaryingType();
2451  if (type1->IsVaryingType()) {
2452  arg0 = TypeConvertExpr(arg0, type0->GetAsVaryingType(), "pointer addition");
2453  offsetType = offsetType->GetAsVaryingType();
2454  AssertPos(pos, arg0 != NULL);
2455  }
2456 
2457  arg1 = TypeConvertExpr(arg1, offsetType, lOpString(op));
2458  if (arg1 == NULL)
2459  return NULL;
2460 
2461  return this;
2462  }
2463 
2464  switch (op) {
2465  case Shl:
2466  case Shr:
2467  case BitAnd:
2468  case BitXor:
2469  case BitOr: {
2470  // Must have integer or bool-typed operands for these bit-related
2471  // ops; don't do any implicit conversions from floats here...
2472  if (!type0->IsIntType() && !type0->IsBoolType()) {
2473  Error(arg0->pos,
2474  "First operand to binary operator \"%s\" must be "
2475  "an integer or bool.",
2476  lOpString(op));
2477  return NULL;
2478  }
2479  if (!type1->IsIntType() && !type1->IsBoolType()) {
2480  Error(arg1->pos,
2481  "Second operand to binary operator \"%s\" must be "
2482  "an integer or bool.",
2483  lOpString(op));
2484  return NULL;
2485  }
2486 
2487  if (op == Shl || op == Shr) {
2488  bool isVarying = (type0->IsVaryingType() || type1->IsVaryingType());
2489  if (isVarying) {
2490  arg0 = TypeConvertExpr(arg0, type0->GetAsVaryingType(), "shift operator");
2491  if (arg0 == NULL)
2492  return NULL;
2493  type0 = arg0->GetType();
2494  }
2495  arg1 = TypeConvertExpr(arg1, type0, "shift operator");
2496  if (arg1 == NULL)
2497  return NULL;
2498  } else {
2499  const Type *promotedType = Type::MoreGeneralType(type0, type1, arg0->pos, "binary bit op");
2500  if (promotedType == NULL)
2501  return NULL;
2502 
2503  arg0 = TypeConvertExpr(arg0, promotedType, "binary bit op");
2504  arg1 = TypeConvertExpr(arg1, promotedType, "binary bit op");
2505  if (arg0 == NULL || arg1 == NULL)
2506  return NULL;
2507  }
2508  return this;
2509  }
2510  case Add:
2511  case Sub:
2512  case Mul:
2513  case Div:
2514  case Mod: {
2515  // Must be numeric type for these. (And mod is special--can't be float)
2516  if (!type0->IsNumericType() || (op == Mod && type0->IsFloatType())) {
2517  Error(arg0->pos,
2518  "First operand to binary operator \"%s\" is of "
2519  "invalid type \"%s\".",
2520  lOpString(op), type0->GetString().c_str());
2521  return NULL;
2522  }
2523  if (!type1->IsNumericType() || (op == Mod && type1->IsFloatType())) {
2524  Error(arg1->pos,
2525  "First operand to binary operator \"%s\" is of "
2526  "invalid type \"%s\".",
2527  lOpString(op), type1->GetString().c_str());
2528  return NULL;
2529  }
2530 
2531  const Type *promotedType = Type::MoreGeneralType(type0, type1, Union(arg0->pos, arg1->pos), lOpString(op));
2532  if (promotedType == NULL)
2533  return NULL;
2534 
2535  arg0 = TypeConvertExpr(arg0, promotedType, lOpString(op));
2536  arg1 = TypeConvertExpr(arg1, promotedType, lOpString(op));
2537  if (arg0 == NULL || arg1 == NULL)
2538  return NULL;
2539  return this;
2540  }
2541  case Lt:
2542  case Gt:
2543  case Le:
2544  case Ge:
2545  case Equal:
2546  case NotEqual: {
2547  const PointerType *pt0 = CastType<PointerType>(type0);
2548  const PointerType *pt1 = CastType<PointerType>(type1);
2549 
2550  // Convert '0' in expressions where the other expression is a
2551  // pointer type to a NULL pointer.
2552  if (pt0 != NULL && lIsAllIntZeros(arg1)) {
2553  arg1 = new NullPointerExpr(pos);
2554  type1 = arg1->GetType();
2555  pt1 = CastType<PointerType>(type1);
2556  } else if (pt1 != NULL && lIsAllIntZeros(arg0)) {
2557  arg0 = new NullPointerExpr(pos);
2558  type0 = arg1->GetType();
2559  pt0 = CastType<PointerType>(type0);
2560  }
2561 
2562  if (pt0 == NULL && pt1 == NULL) {
2563  if (!type0->IsBoolType() && !type0->IsNumericType()) {
2564  Error(arg0->pos,
2565  "First operand to operator \"%s\" is of "
2566  "non-comparable type \"%s\".",
2567  lOpString(op), type0->GetString().c_str());
2568  return NULL;
2569  }
2570  if (!type1->IsBoolType() && !type1->IsNumericType()) {
2571  Error(arg1->pos,
2572  "Second operand to operator \"%s\" is of "
2573  "non-comparable type \"%s\".",
2574  lOpString(op), type1->GetString().c_str());
2575  return NULL;
2576  }
2577  }
2578 
2579  const Type *promotedType = Type::MoreGeneralType(type0, type1, arg0->pos, lOpString(op));
2580  if (promotedType == NULL)
2581  return NULL;
2582 
2583  arg0 = TypeConvertExpr(arg0, promotedType, lOpString(op));
2584  arg1 = TypeConvertExpr(arg1, promotedType, lOpString(op));
2585  if (arg0 == NULL || arg1 == NULL)
2586  return NULL;
2587  return this;
2588  }
2589  case LogicalAnd:
2590  case LogicalOr: {
2591  // For now, we just type convert to boolean types, of the same
2592  // variability as the original types. (When generating code, it's
2593  // useful to have preserved the uniform/varying distinction.)
2596 
2597  const Type *destType0 = NULL, *destType1 = NULL;
2598  const VectorType *vtype0 = CastType<VectorType>(type0);
2599  const VectorType *vtype1 = CastType<VectorType>(type1);
2600  if (vtype0 && vtype1) {
2601  int sz0 = vtype0->GetElementCount(), sz1 = vtype1->GetElementCount();
2602  if (sz0 != sz1) {
2603  Error(pos,
2604  "Can't do logical operation \"%s\" between vector types of "
2605  "different sizes (%d vs. %d).",
2606  lOpString(op), sz0, sz1);
2607  return NULL;
2608  }
2609  destType0 = new VectorType(boolType0, sz0);
2610  destType1 = new VectorType(boolType1, sz1);
2611  } else if (vtype0 != NULL) {
2612  destType0 = new VectorType(boolType0, vtype0->GetElementCount());
2613  destType1 = new VectorType(boolType1, vtype0->GetElementCount());
2614  } else if (vtype1 != NULL) {
2615  destType0 = new VectorType(boolType0, vtype1->GetElementCount());
2616  destType1 = new VectorType(boolType1, vtype1->GetElementCount());
2617  } else {
2618  destType0 = boolType0;
2619  destType1 = boolType1;
2620  }
2621 
2622  arg0 = TypeConvertExpr(arg0, destType0, lOpString(op));
2623  arg1 = TypeConvertExpr(arg1, destType1, lOpString(op));
2624  if (arg0 == NULL || arg1 == NULL)
2625  return NULL;
2626  return this;
2627  }
2628  case Comma:
2629  return this;
2630  default:
2631  FATAL("logic error");
2632  return NULL;
2633  }
2634 }
2635 
2637  const Type *t = GetType();
2638  if (CastType<PointerType>(t) != NULL) {
2639  // Are we doing something like (basePtr + offset)[...] = ...
2640  return t;
2641  } else {
2642  return NULL;
2643  }
2644 }
2645 
2647  if (llvm::dyn_cast<ConstExpr>(arg0) != NULL && llvm::dyn_cast<ConstExpr>(arg1) != NULL)
2648  return 0;
2649 
2651 }
2652 
2653 void BinaryExpr::Print() const {
2654  if (!arg0 || !arg1 || !GetType())
2655  return;
2656 
2657  printf("[ %s ] (", GetType()->GetString().c_str());
2658  arg0->Print();
2659  printf(" %s ", lOpString(op));
2660  arg1->Print();
2661  printf(")");
2662  pos.Print();
2663 }
2664 
2665 static std::pair<llvm::Constant *, bool> lGetBinaryExprStorageConstant(const Type *type, const BinaryExpr *bExpr,
2666  bool isStorageType) {
2667 
2668  const BinaryExpr::Op op = bExpr->op;
2669  Expr *arg0 = bExpr->arg0;
2670  Expr *arg1 = bExpr->arg1;
2671 
2672  // Are we doing something like (basePtr + offset)[...] = ... for a Global
2673  // Variable
2674  if (!bExpr->GetLValueType())
2675  return std::pair<llvm::Constant *, bool>(NULL, false);
2676 
2677  // We are limiting cases to just addition and subtraction involving
2678  // pointer addresses
2679  // Case 1 : first argument is a pointer address.
2680  // In this case as long as the second argument is a constant value, we are fine
2681  // Case 2 : second argument is a pointer address.
2682  // In this case, it has to be an addition with first argument as
2683  // a constant value.
2684  if (!((op == BinaryExpr::Op::Add) || (op == BinaryExpr::Op::Sub)))
2685  return std::pair<llvm::Constant *, bool>(NULL, false);
2686  if (op == BinaryExpr::Op::Sub) {
2687  // Ignore cases where subtrahend is a PointerType
2688  // Eg. b - 5 is valid but 5 - b is not.
2689  if (CastType<PointerType>(arg1->GetType()))
2690  return std::pair<llvm::Constant *, bool>(NULL, false);
2691  }
2692 
2693  // 'isNotValidForMultiTargetGlobal' is required to let the caller know
2694  // that the llvm::constant value returned cannot be used in case of
2695  // multi-target compilation for initialization of globals. This is due
2696  // to different constant values for different targets, i.e. computation
2697  // involving sizeof() of varying types.
2698  // Since converting expr to constant can be a recursive process, we need
2699  // to ensure that if the flag is set by any expr in the chain, it's
2700  // reflected in the final return value.
2701  bool isNotValidForMultiTargetGlobal = false;
2702  if (const PointerType *pt0 = CastType<PointerType>(arg0->GetType())) {
2703  std::pair<llvm::Constant *, bool> c1Pair;
2704  if (isStorageType)
2705  c1Pair = arg0->GetStorageConstant(pt0);
2706  else
2707  c1Pair = arg0->GetConstant(pt0);
2708  llvm::Constant *c1 = c1Pair.first;
2709  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || c1Pair.second;
2710  ConstExpr *cExpr = llvm::dyn_cast<ConstExpr>(arg1);
2711  if ((cExpr == NULL) || (c1 == NULL))
2712  return std::pair<llvm::Constant *, bool>(NULL, false);
2713  std::pair<llvm::Constant *, bool> c2Pair;
2714  if (isStorageType)
2715  c2Pair = cExpr->GetStorageConstant(cExpr->GetType());
2716  else
2717  c2Pair = cExpr->GetConstant(cExpr->GetType());
2718  llvm::Constant *c2 = c2Pair.first;
2719  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || c2Pair.second;
2720  if (op == BinaryExpr::Op::Sub)
2721  c2 = llvm::ConstantExpr::getNeg(c2);
2722  llvm::Constant *c = llvm::ConstantExpr::getGetElementPtr(PTYPE(c1), c1, c2);
2723  return std::pair<llvm::Constant *, bool>(c, isNotValidForMultiTargetGlobal);
2724  } else if (const PointerType *pt1 = CastType<PointerType>(arg1->GetType())) {
2725  std::pair<llvm::Constant *, bool> c1Pair;
2726  if (isStorageType)
2727  c1Pair = arg1->GetStorageConstant(pt1);
2728  else
2729  c1Pair = arg1->GetConstant(pt1);
2730  llvm::Constant *c1 = c1Pair.first;
2731  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || c1Pair.second;
2732  ConstExpr *cExpr = llvm::dyn_cast<ConstExpr>(arg0);
2733  if ((cExpr == NULL) || (c1 == NULL))
2734  return std::pair<llvm::Constant *, bool>(NULL, false);
2735  std::pair<llvm::Constant *, bool> c2Pair;
2736  if (isStorageType)
2737  c2Pair = cExpr->GetStorageConstant(cExpr->GetType());
2738  else
2739  c2Pair = cExpr->GetConstant(cExpr->GetType());
2740  llvm::Constant *c2 = c2Pair.first;
2741  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || c2Pair.second;
2742  llvm::Constant *c = llvm::ConstantExpr::getGetElementPtr(PTYPE(c1), c1, c2);
2743  return std::pair<llvm::Constant *, bool>(c, isNotValidForMultiTargetGlobal);
2744  }
2745 
2746  return std::pair<llvm::Constant *, bool>(NULL, false);
2747 }
2748 
2749 std::pair<llvm::Constant *, bool> BinaryExpr::GetStorageConstant(const Type *type) const {
2750  return lGetBinaryExprStorageConstant(type, this, true);
2751 }
2752 
2753 std::pair<llvm::Constant *, bool> BinaryExpr::GetConstant(const Type *type) const {
2754 
2755  return lGetBinaryExprStorageConstant(type, this, false);
2756 }
2757 ///////////////////////////////////////////////////////////////////////////
2758 // AssignExpr
2759 
2760 static const char *lOpString(AssignExpr::Op op) {
2761  switch (op) {
2762  case AssignExpr::Assign:
2763  return "assignment operator";
2764  case AssignExpr::MulAssign:
2765  return "*=";
2766  case AssignExpr::DivAssign:
2767  return "/=";
2768  case AssignExpr::ModAssign:
2769  return "%%=";
2770  case AssignExpr::AddAssign:
2771  return "+=";
2772  case AssignExpr::SubAssign:
2773  return "-=";
2774  case AssignExpr::ShlAssign:
2775  return "<<=";
2776  case AssignExpr::ShrAssign:
2777  return ">>=";
2778  case AssignExpr::AndAssign:
2779  return "&=";
2780  case AssignExpr::XorAssign:
2781  return "^=";
2782  case AssignExpr::OrAssign:
2783  return "|=";
2784  default:
2785  FATAL("Missing op in lOpstring");
2786  return "";
2787  }
2788 }
2789 
2790 /** Emit code to do an "assignment + operation" operator, e.g. "+=".
2791  */
2792 static llvm::Value *lEmitOpAssign(AssignExpr::Op op, Expr *arg0, Expr *arg1, const Type *type, Symbol *baseSym,
2793  SourcePos pos, FunctionEmitContext *ctx) {
2794  llvm::Value *lv = arg0->GetLValue(ctx);
2795  if (!lv) {
2796  // FIXME: I think this test is unnecessary and that this case
2797  // should be caught during typechecking
2798  Error(pos, "Can't assign to left-hand side of expression.");
2799  return NULL;
2800  }
2801  const Type *lvalueType = arg0->GetLValueType();
2802  const Type *resultType = arg0->GetType();
2803  if (lvalueType == NULL || resultType == NULL)
2804  return NULL;
2805 
2806  // Get the value on the right-hand side of the assignment+operation
2807  // operator and load the current value on the left-hand side.
2808  llvm::Value *rvalue = arg1->GetValue(ctx);
2809  llvm::Value *mask = lMaskForSymbol(baseSym, ctx);
2810  ctx->SetDebugPos(arg0->pos);
2811  llvm::Value *oldLHS = ctx->LoadInst(lv, mask, lvalueType);
2812  ctx->SetDebugPos(pos);
2813 
2814  // Map the operator to the corresponding BinaryExpr::Op operator
2815  BinaryExpr::Op basicop;
2816  switch (op) {
2817  case AssignExpr::MulAssign:
2818  basicop = BinaryExpr::Mul;
2819  break;
2820  case AssignExpr::DivAssign:
2821  basicop = BinaryExpr::Div;
2822  break;
2823  case AssignExpr::ModAssign:
2824  basicop = BinaryExpr::Mod;
2825  break;
2826  case AssignExpr::AddAssign:
2827  basicop = BinaryExpr::Add;
2828  break;
2829  case AssignExpr::SubAssign:
2830  basicop = BinaryExpr::Sub;
2831  break;
2832  case AssignExpr::ShlAssign:
2833  basicop = BinaryExpr::Shl;
2834  break;
2835  case AssignExpr::ShrAssign:
2836  basicop = BinaryExpr::Shr;
2837  break;
2838  case AssignExpr::AndAssign:
2839  basicop = BinaryExpr::BitAnd;
2840  break;
2841  case AssignExpr::XorAssign:
2842  basicop = BinaryExpr::BitXor;
2843  break;
2844  case AssignExpr::OrAssign:
2845  basicop = BinaryExpr::BitOr;
2846  break;
2847  default:
2848  FATAL("logic error in lEmitOpAssign()");
2849  return NULL;
2850  }
2851 
2852  // Emit the code to compute the new value
2853  llvm::Value *newValue = NULL;
2854  switch (op) {
2855  case AssignExpr::MulAssign:
2856  case AssignExpr::DivAssign:
2857  case AssignExpr::ModAssign:
2858  case AssignExpr::AddAssign:
2859  case AssignExpr::SubAssign:
2860  newValue = lEmitBinaryArith(basicop, oldLHS, rvalue, type, arg1->GetType(), ctx, pos);
2861  break;
2862  case AssignExpr::ShlAssign:
2863  case AssignExpr::ShrAssign:
2864  case AssignExpr::AndAssign:
2865  case AssignExpr::XorAssign:
2866  case AssignExpr::OrAssign:
2867  newValue = lEmitBinaryBitOp(basicop, oldLHS, rvalue, arg0->GetType()->IsUnsignedType(), ctx);
2868  break;
2869  default:
2870  FATAL("logic error in lEmitOpAssign");
2871  return NULL;
2872  }
2873 
2874  // And store the result back to the lvalue.
2875  ctx->SetDebugPos(arg0->pos);
2876  lStoreAssignResult(newValue, lv, resultType, lvalueType, ctx, baseSym);
2877 
2878  return newValue;
2879 }
2880 
2882  lvalue = a;
2883  rvalue = b;
2884 }
2885 
2886 llvm::Value *AssignExpr::GetValue(FunctionEmitContext *ctx) const {
2887  const Type *type = NULL;
2888  if (lvalue == NULL || rvalue == NULL || (type = GetType()) == NULL)
2889  return NULL;
2890  ctx->SetDebugPos(pos);
2891 
2892  Symbol *baseSym = lvalue->GetBaseSymbol();
2893 
2894  switch (op) {
2895  case Assign: {
2896  llvm::Value *ptr = lvalue->GetLValue(ctx);
2897  if (ptr == NULL) {
2898  Error(lvalue->pos, "Left hand side of assignment expression can't "
2899  "be assigned to.");
2900  return NULL;
2901  }
2902  const Type *ptrType = lvalue->GetLValueType();
2903  const Type *valueType = rvalue->GetType();
2904  if (ptrType == NULL || valueType == NULL) {
2905  AssertPos(pos, m->errorCount > 0);
2906  return NULL;
2907  }
2908 
2909  llvm::Value *value = rvalue->GetValue(ctx);
2910  if (value == NULL) {
2911  AssertPos(pos, m->errorCount > 0);
2912  return NULL;
2913  }
2914 
2915  ctx->SetDebugPos(lvalue->pos);
2916 
2917  lStoreAssignResult(value, ptr, valueType, ptrType, ctx, baseSym);
2918 
2919  return value;
2920  }
2921  case MulAssign:
2922  case DivAssign:
2923  case ModAssign:
2924  case AddAssign:
2925  case SubAssign:
2926  case ShlAssign:
2927  case ShrAssign:
2928  case AndAssign:
2929  case XorAssign:
2930  case OrAssign: {
2931  // This should be caught during type checking
2932  AssertPos(pos, !CastType<ArrayType>(type) && !CastType<StructType>(type));
2933  return lEmitOpAssign(op, lvalue, rvalue, type, baseSym, pos, ctx);
2934  }
2935  default:
2936  FATAL("logic error in AssignExpr::GetValue()");
2937  return NULL;
2938  }
2939 }
2940 
2942  if (lvalue == NULL || rvalue == NULL)
2943  return NULL;
2944  return this;
2945 }
2946 
2947 const Type *AssignExpr::GetType() const { return lvalue ? lvalue->GetType() : NULL; }
2948 
2949 /** Recursively checks a structure type to see if it (or any struct type
2950  that it holds) has a const-qualified member. */
2951 static bool lCheckForConstStructMember(SourcePos pos, const StructType *structType, const StructType *initialType) {
2952  for (int i = 0; i < structType->GetElementCount(); ++i) {
2953  const Type *t = structType->GetElementType(i);
2954  if (t->IsConstType()) {
2955  if (structType == initialType)
2956  Error(pos,
2957  "Illegal to assign to type \"%s\" due to element "
2958  "\"%s\" with type \"%s\".",
2959  structType->GetString().c_str(), structType->GetElementName(i).c_str(), t->GetString().c_str());
2960  else
2961  Error(pos,
2962  "Illegal to assign to type \"%s\" in type \"%s\" "
2963  "due to element \"%s\" with type \"%s\".",
2964  structType->GetString().c_str(), initialType->GetString().c_str(),
2965  structType->GetElementName(i).c_str(), t->GetString().c_str());
2966  return true;
2967  }
2968 
2969  const StructType *st = CastType<StructType>(t);
2970  if (st != NULL && lCheckForConstStructMember(pos, st, initialType))
2971  return true;
2972  }
2973  return false;
2974 }
2975 
2977  if (lvalue == NULL || rvalue == NULL)
2978  return NULL;
2979 
2980  bool lvalueIsReference = CastType<ReferenceType>(lvalue->GetType()) != NULL;
2981  if (lvalueIsReference)
2982  lvalue = new RefDerefExpr(lvalue, lvalue->pos);
2983 
2985  Error(pos, "Unable to find overloaded function for function "
2986  "pointer assignment.");
2987  return NULL;
2988  }
2989 
2990  const Type *lhsType = lvalue->GetType();
2991  if (lhsType == NULL) {
2992  AssertPos(pos, m->errorCount > 0);
2993  return NULL;
2994  }
2995 
2996  if (lhsType->IsConstType()) {
2997  Error(lvalue->pos,
2998  "Can't assign to type \"%s\" on left-hand side of "
2999  "expression.",
3000  lhsType->GetString().c_str());
3001  return NULL;
3002  }
3003 
3004  if (CastType<PointerType>(lhsType) != NULL) {
3005  if (op == AddAssign || op == SubAssign) {
3006  if (PointerType::IsVoidPointer(lhsType)) {
3007  Error(pos,
3008  "Illegal to perform pointer arithmetic on \"%s\" "
3009  "type.",
3010  lhsType->GetString().c_str());
3011  return NULL;
3012  }
3013 
3015  if (lhsType->IsVaryingType())
3016  deltaType = deltaType->GetAsVaryingType();
3017  rvalue = TypeConvertExpr(rvalue, deltaType, lOpString(op));
3018  } else if (op == Assign)
3019  rvalue = TypeConvertExpr(rvalue, lhsType, "assignment");
3020  else {
3021  Error(lvalue->pos, "Assignment operator \"%s\" is illegal with pointer types.", lOpString(op));
3022  return NULL;
3023  }
3024  } else if (CastType<ArrayType>(lhsType) != NULL) {
3025  Error(lvalue->pos, "Illegal to assign to array type \"%s\".", lhsType->GetString().c_str());
3026  return NULL;
3027  } else
3028  rvalue = TypeConvertExpr(rvalue, lhsType, lOpString(op));
3029 
3030  if (rvalue == NULL)
3031  return NULL;
3032 
3033  if (lhsType->IsFloatType() == true &&
3034  (op == ShlAssign || op == ShrAssign || op == AndAssign || op == XorAssign || op == OrAssign)) {
3035  Error(pos,
3036  "Illegal to use %s operator with floating-point "
3037  "operands.",
3038  lOpString(op));
3039  return NULL;
3040  }
3041 
3042  const StructType *st = CastType<StructType>(lhsType);
3043  if (st != NULL) {
3044  // Make sure we're not assigning to a struct that has a constant member
3045  if (lCheckForConstStructMember(pos, st, st))
3046  return NULL;
3047 
3048  if (op != Assign) {
3049  Error(lvalue->pos,
3050  "Assignment operator \"%s\" is illegal with struct "
3051  "type \"%s\".",
3052  lOpString(op), st->GetString().c_str());
3053  return NULL;
3054  }
3055  }
3056  return this;
3057 }
3058 
3060  if (op == Assign)
3061  return COST_ASSIGN;
3062  if (op == DivAssign || op == ModAssign)
3064  else
3066 }
3067 
3068 void AssignExpr::Print() const {
3069  if (!lvalue || !rvalue || !GetType())
3070  return;
3071 
3072  printf("[%s] assign (", GetType()->GetString().c_str());
3073  lvalue->Print();
3074  printf(" %s ", lOpString(op));
3075  rvalue->Print();
3076  printf(")");
3077  pos.Print();
3078 }
3079 
3080 ///////////////////////////////////////////////////////////////////////////
3081 // SelectExpr
3082 
3084  test = t;
3085  expr1 = e1;
3086  expr2 = e2;
3087 }
3088 
3089 /** Emit code to select between two varying values based on a varying test
3090  value.
3091  */
3092 static llvm::Value *lEmitVaryingSelect(FunctionEmitContext *ctx, llvm::Value *test, llvm::Value *expr1,
3093  llvm::Value *expr2, const Type *type) {
3094 
3095  llvm::Value *resultPtr = ctx->AllocaInst(type, "selectexpr_tmp");
3096  Assert(resultPtr != NULL);
3097  // Don't need to worry about masking here
3098  ctx->StoreInst(expr2, resultPtr, type);
3099  // Use masking to conditionally store the expr1 values
3100  Assert(resultPtr->getType() == PointerType::GetUniform(type)->LLVMStorageType(g->ctx));
3101  ctx->StoreInst(expr1, resultPtr, test, type, PointerType::GetUniform(type));
3102  return ctx->LoadInst(resultPtr, type, "selectexpr_final");
3103 }
3104 
3105 static void lEmitSelectExprCode(FunctionEmitContext *ctx, llvm::Value *testVal, llvm::Value *oldMask,
3106  llvm::Value *fullMask, Expr *expr, llvm::Value *exprPtr) {
3107  llvm::BasicBlock *bbEval = ctx->CreateBasicBlock("select_eval_expr");
3108  llvm::BasicBlock *bbDone = ctx->CreateBasicBlock("select_done");
3109 
3110  // Check to see if the test was true for any of the currently executing
3111  // program instances.
3112  llvm::Value *testAndFullMask = ctx->BinaryOperator(llvm::Instruction::And, testVal, fullMask, "test&mask");
3113  llvm::Value *anyOn = ctx->Any(testAndFullMask);
3114  ctx->BranchInst(bbEval, bbDone, anyOn);
3115 
3116  ctx->SetCurrentBasicBlock(bbEval);
3117  llvm::Value *testAndMask = ctx->BinaryOperator(llvm::Instruction::And, testVal, oldMask, "test&mask");
3118  ctx->SetInternalMask(testAndMask);
3119  llvm::Value *exprVal = expr->GetValue(ctx);
3120  ctx->StoreInst(exprVal, exprPtr, expr->GetType());
3121  ctx->BranchInst(bbDone);
3122 
3123  ctx->SetCurrentBasicBlock(bbDone);
3124 }
3125 
3126 llvm::Value *SelectExpr::GetValue(FunctionEmitContext *ctx) const {
3127  if (!expr1 || !expr2 || !test)
3128  return NULL;
3129 
3130  ctx->SetDebugPos(pos);
3131 
3132  const Type *testType = test->GetType()->GetAsNonConstType();
3133  // This should be taken care of during typechecking
3136 
3137  const Type *type = expr1->GetType();
3138 
3139  if (Type::Equal(testType, AtomicType::UniformBool)) {
3140  // Simple case of a single uniform bool test expression; we just
3141  // want one of the two expressions. In this case, we can be
3142  // careful to evaluate just the one of the expressions that we need
3143  // the value of so that if the other one has side-effects or
3144  // accesses invalid memory, it doesn't execute.
3145  llvm::Value *testVal = test->GetValue(ctx);
3146  llvm::BasicBlock *testTrue = ctx->CreateBasicBlock("select_true");
3147  llvm::BasicBlock *testFalse = ctx->CreateBasicBlock("select_false");
3148  llvm::BasicBlock *testDone = ctx->CreateBasicBlock("select_done");
3149  ctx->BranchInst(testTrue, testFalse, testVal);
3150 
3151  ctx->SetCurrentBasicBlock(testTrue);
3152  llvm::Value *expr1Val = expr1->GetValue(ctx);
3153  // Note that truePred won't be necessarily equal to testTrue, in
3154  // case the expr1->GetValue() call changes the current basic block.
3155  llvm::BasicBlock *truePred = ctx->GetCurrentBasicBlock();
3156  ctx->BranchInst(testDone);
3157 
3158  ctx->SetCurrentBasicBlock(testFalse);
3159  llvm::Value *expr2Val = expr2->GetValue(ctx);
3160  // See comment above truePred for why we can't just assume we're in
3161  // the testFalse basic block here.
3162  llvm::BasicBlock *falsePred = ctx->GetCurrentBasicBlock();
3163  ctx->BranchInst(testDone);
3164 
3165  ctx->SetCurrentBasicBlock(testDone);
3166  llvm::PHINode *ret = ctx->PhiNode(expr1Val->getType(), 2, "select");
3167  ret->addIncoming(expr1Val, truePred);
3168  ret->addIncoming(expr2Val, falsePred);
3169  return ret;
3170  } else if (CastType<VectorType>(testType) == NULL) {
3171  // the test is a varying bool type
3172  llvm::Value *testVal = test->GetValue(ctx);
3173  AssertPos(pos, testVal->getType() == LLVMTypes::MaskType);
3174  llvm::Value *oldMask = ctx->GetInternalMask();
3175  llvm::Value *fullMask = ctx->GetFullMask();
3176 
3177  // We don't want to incur the overhead for short-circuit evaluation
3178  // for expressions that are both computationally simple and safe to
3179  // run with an "all off" mask.
3180  bool shortCircuit1 =
3182  bool shortCircuit2 =
3184 
3185  Debug(expr1->pos, "%sshort circuiting evaluation for select expr", shortCircuit1 ? "" : "Not ");
3186  Debug(expr2->pos, "%sshort circuiting evaluation for select expr", shortCircuit2 ? "" : "Not ");
3187 
3188  // Temporary storage to store the values computed for each
3189  // expression, if any. (These stay as uninitialized memory if we
3190  // short circuit around the corresponding expression.)
3191  llvm::Value *expr1Ptr = ctx->AllocaInst(expr1->GetType());
3192  llvm::Value *expr2Ptr = ctx->AllocaInst(expr1->GetType());
3193 
3194  if (shortCircuit1)
3195  lEmitSelectExprCode(ctx, testVal, oldMask, fullMask, expr1, expr1Ptr);
3196  else {
3197  ctx->SetInternalMaskAnd(oldMask, testVal);
3198  llvm::Value *expr1Val = expr1->GetValue(ctx);
3199  ctx->StoreInst(expr1Val, expr1Ptr, expr1->GetType());
3200  }
3201 
3202  if (shortCircuit2) {
3203  llvm::Value *notTest = ctx->NotOperator(testVal);
3204  lEmitSelectExprCode(ctx, notTest, oldMask, fullMask, expr2, expr2Ptr);
3205  } else {
3206  ctx->SetInternalMaskAndNot(oldMask, testVal);
3207  llvm::Value *expr2Val = expr2->GetValue(ctx);
3208  ctx->StoreInst(expr2Val, expr2Ptr, expr2->GetType());
3209  }
3210 
3211  ctx->SetInternalMask(oldMask);
3212  llvm::Value *expr1Val = ctx->LoadInst(expr1Ptr, expr1->GetType());
3213  llvm::Value *expr2Val = ctx->LoadInst(expr2Ptr, expr2->GetType());
3214  return lEmitVaryingSelect(ctx, testVal, expr1Val, expr2Val, type);
3215  } else {
3216  // FIXME? Short-circuiting doesn't work in the case of
3217  // vector-valued test expressions. (We could also just prohibit
3218  // these and place the issue in the user's hands...)
3219  llvm::Value *testVal = test->GetValue(ctx);
3220  llvm::Value *expr1Val = expr1->GetValue(ctx);
3221  llvm::Value *expr2Val = expr2->GetValue(ctx);
3222 
3223  ctx->SetDebugPos(pos);
3224  const VectorType *vt = CastType<VectorType>(type);
3225  // Things that typechecking should have caught
3226  AssertPos(pos, vt != NULL);
3227  AssertPos(pos, CastType<VectorType>(testType) != NULL &&
3228  (CastType<VectorType>(testType)->GetElementCount() == vt->GetElementCount()));
3229 
3230  // Do an element-wise select
3231  llvm::Value *result = llvm::UndefValue::get(type->LLVMType(g->ctx));
3232  for (int i = 0; i < vt->GetElementCount(); ++i) {
3233  llvm::Value *ti = ctx->ExtractInst(testVal, i);
3234  llvm::Value *e1i = ctx->ExtractInst(expr1Val, i);
3235  llvm::Value *e2i = ctx->ExtractInst(expr2Val, i);
3236  llvm::Value *sel = NULL;
3237  if (testType->IsUniformType())
3238  sel = ctx->SelectInst(ti, e1i, e2i);
3239  else
3240  sel = lEmitVaryingSelect(ctx, ti, e1i, e2i, vt->GetElementType());
3241  result = ctx->InsertInst(result, sel, i);
3242  }
3243  return result;
3244  }
3245 }
3246 
3247 const Type *SelectExpr::GetType() const {
3248  if (!test || !expr1 || !expr2)
3249  return NULL;
3250 
3251  const Type *testType = test->GetType();
3252  const Type *expr1Type = expr1->GetType();
3253  const Type *expr2Type = expr2->GetType();
3254 
3255  if (!testType || !expr1Type || !expr2Type)
3256  return NULL;
3257 
3258  bool becomesVarying = (testType->IsVaryingType() || expr1Type->IsVaryingType() || expr2Type->IsVaryingType());
3259  // if expr1 and expr2 have different vector sizes, typechecking should fail...
3260  int testVecSize = CastType<VectorType>(testType) != NULL ? CastType<VectorType>(testType)->GetElementCount() : 0;
3261  int expr1VecSize = CastType<VectorType>(expr1Type) != NULL ? CastType<VectorType>(expr1Type)->GetElementCount() : 0;
3262  AssertPos(pos, !(testVecSize != 0 && expr1VecSize != 0 && testVecSize != expr1VecSize));
3263 
3264  int vectorSize = std::max(testVecSize, expr1VecSize);
3265  return Type::MoreGeneralType(expr1Type, expr2Type, Union(expr1->pos, expr2->pos), "select expression",
3266  becomesVarying, vectorSize);
3267 }
3268 
3269 template <typename T>
3270 Expr *lConstFoldSelect(const bool bv[], ConstExpr *constExpr1, ConstExpr *constExpr2, const Type *exprType,
3271  SourcePos pos) {
3272  T v1[ISPC_MAX_NVEC], v2[ISPC_MAX_NVEC];
3273  T result[ISPC_MAX_NVEC];
3274  int count = constExpr1->GetValues(v1);
3275  constExpr2->GetValues(v2);
3276  for (int i = 0; i < count; ++i)
3277  result[i] = bv[i] ? v1[i] : v2[i];
3278  return new ConstExpr(exprType, result, pos);
3279 }
3280 
3282  if (test == NULL || expr1 == NULL || expr2 == NULL)
3283  return NULL;
3284 
3285  ConstExpr *constTest = llvm::dyn_cast<ConstExpr>(test);
3286  if (constTest == NULL)
3287  return this;
3288 
3289  // The test is a constant; see if we can resolve to one of the
3290  // expressions..
3291  bool bv[ISPC_MAX_NVEC];
3292  int count = constTest->GetValues(bv);
3293  if (count == 1)
3294  // Uniform test value; return the corresponding expression
3295  return (bv[0] == true) ? expr1 : expr2;
3296  else {
3297  // Varying test: see if all of the values are the same; if so, then
3298  // return the corresponding expression
3299  bool first = bv[0];
3300  bool mismatch = false;
3301  for (int i = 0; i < count; ++i)
3302  if (bv[i] != first) {
3303  mismatch = true;
3304  break;
3305  }
3306  if (mismatch == false)
3307  return (bv[0] == true) ? expr1 : expr2;
3308 
3309  // Last chance: see if the two expressions are constants; if so,
3310  // then we can do an element-wise selection based on the constant
3311  // condition..
3312  ConstExpr *constExpr1 = llvm::dyn_cast<ConstExpr>(expr1);
3313  ConstExpr *constExpr2 = llvm::dyn_cast<ConstExpr>(expr2);
3314  if (constExpr1 == NULL || constExpr2 == NULL)
3315  return this;
3316 
3317  AssertPos(pos, Type::Equal(constExpr1->GetType(), constExpr2->GetType()));
3318  const Type *exprType = constExpr1->GetType()->GetAsNonConstType();
3319  AssertPos(pos, exprType->IsVaryingType());
3320 
3321  if (Type::Equal(exprType, AtomicType::VaryingInt8)) {
3322  return lConstFoldSelect<int8_t>(bv, constExpr1, constExpr2, exprType, pos);
3323  } else if (Type::Equal(exprType, AtomicType::VaryingUInt8)) {
3324  return lConstFoldSelect<uint8_t>(bv, constExpr1, constExpr2, exprType, pos);
3325  } else if (Type::Equal(exprType, AtomicType::VaryingInt16)) {
3326  return lConstFoldSelect<int16_t>(bv, constExpr1, constExpr2, exprType, pos);
3327  } else if (Type::Equal(exprType, AtomicType::VaryingUInt16)) {
3328  return lConstFoldSelect<uint16_t>(bv, constExpr1, constExpr2, exprType, pos);
3329  } else if (Type::Equal(exprType, AtomicType::VaryingInt32)) {
3330  return lConstFoldSelect<int32_t>(bv, constExpr1, constExpr2, exprType, pos);
3331  } else if (Type::Equal(exprType, AtomicType::VaryingUInt32)) {
3332  return lConstFoldSelect<uint32_t>(bv, constExpr1, constExpr2, exprType, pos);
3333  } else if (Type::Equal(exprType, AtomicType::VaryingInt64)) {
3334  return lConstFoldSelect<int64_t>(bv, constExpr1, constExpr2, exprType, pos);
3335  } else if (Type::Equal(exprType, AtomicType::VaryingUInt64)) {
3336  return lConstFoldSelect<uint64_t>(bv, constExpr1, constExpr2, exprType, pos);
3337  } else if (Type::Equal(exprType, AtomicType::VaryingFloat)) {
3338  return lConstFoldSelect<float>(bv, constExpr1, constExpr2, exprType, pos);
3339  } else if (Type::Equal(exprType, AtomicType::VaryingDouble)) {
3340  return lConstFoldSelect<bool>(bv, constExpr1, constExpr2, exprType, pos);
3341  } else if (Type::Equal(exprType, AtomicType::VaryingBool)) {
3342  return lConstFoldSelect<double>(bv, constExpr1, constExpr2, exprType, pos);
3343  }
3344 
3345  return this;
3346  }
3347 }
3348 
3350  if (test == NULL || expr1 == NULL || expr2 == NULL)
3351  return NULL;
3352 
3353  const Type *type1 = expr1->GetType(), *type2 = expr2->GetType();
3354  if (!type1 || !type2)
3355  return NULL;
3356 
3357  if (const ArrayType *at1 = CastType<ArrayType>(type1)) {
3358  expr1 = TypeConvertExpr(expr1, PointerType::GetUniform(at1->GetBaseType()), "select");
3359  if (expr1 == NULL)
3360  return NULL;
3361  type1 = expr1->GetType();
3362  }
3363  if (const ArrayType *at2 = CastType<ArrayType>(type2)) {
3364  expr2 = TypeConvertExpr(expr2, PointerType::GetUniform(at2->GetBaseType()), "select");
3365  if (expr2 == NULL)
3366  return NULL;
3367  type2 = expr2->GetType();
3368  }
3369 
3370  const Type *testType = test->GetType();
3371  if (testType == NULL)
3372  return NULL;
3373  test = TypeConvertExpr(test, lMatchingBoolType(testType), "select");
3374  if (test == NULL)
3375  return NULL;
3376  testType = test->GetType();
3377 
3378  int testVecSize = CastType<VectorType>(testType) ? CastType<VectorType>(testType)->GetElementCount() : 0;
3379  const Type *promotedType = Type::MoreGeneralType(type1, type2, Union(expr1->pos, expr2->pos), "select expression",
3380  testType->IsVaryingType(), testVecSize);
3381 
3382  // If the promoted type is a ReferenceType, the expression type will be
3383  // the reference target type since SelectExpr is always a rvalue.
3384  if (CastType<ReferenceType>(promotedType) != NULL)
3385  promotedType = promotedType->GetReferenceTarget();
3386 
3387  if (promotedType == NULL)
3388  return NULL;
3389 
3390  expr1 = TypeConvertExpr(expr1, promotedType, "select");
3391  expr2 = TypeConvertExpr(expr2, promotedType, "select");
3392  if (expr1 == NULL || expr2 == NULL)
3393  return NULL;
3394 
3395  return this;
3396 }
3397 
3398 int SelectExpr::EstimateCost() const { return COST_SELECT; }
3399 
3400 void SelectExpr::Print() const {
3401  if (!test || !expr1 || !expr2 || !GetType())
3402  return;
3403 
3404  printf("[%s] (", GetType()->GetString().c_str());
3405  test->Print();
3406  printf(" ? ");
3407  expr1->Print();
3408  printf(" : ");
3409  expr2->Print();
3410  printf(")");
3411  pos.Print();
3412 }
3413 
3414 ///////////////////////////////////////////////////////////////////////////
3415 // FunctionCallExpr
3416 
3418  : Expr(p, FunctionCallExprID), isLaunch(il) {
3419  func = f;
3420  args = a;
3421  if (lce != NULL) {
3422  launchCountExpr[0] = lce[0];
3423  launchCountExpr[1] = lce[1];
3424  launchCountExpr[2] = lce[2];
3425  } else
3426  launchCountExpr[0] = launchCountExpr[1] = launchCountExpr[2] = NULL;
3427 }
3428 
3430  if (func == NULL)
3431  return NULL;
3432 
3433  const Type *type = func->GetType();
3434  if (type == NULL)
3435  return NULL;
3436 
3437  const FunctionType *ftype = CastType<FunctionType>(type);
3438  if (ftype == NULL) {
3439  // Not a regular function symbol--is it a function pointer?
3440  if (CastType<PointerType>(type) != NULL)
3441  ftype = CastType<FunctionType>(type->GetBaseType());
3442  }
3443  return ftype;
3444 }
3445 
3447  if (func == NULL || args == NULL)
3448  return NULL;
3449 
3450  ctx->SetDebugPos(pos);
3451 
3452  llvm::Value *callee = func->GetValue(ctx);
3453 
3454  if (callee == NULL) {
3455  AssertPos(pos, m->errorCount > 0);
3456  return NULL;
3457  }
3458 
3459  const FunctionType *ft = lGetFunctionType(func);
3460  AssertPos(pos, ft != NULL);
3461  bool isVoidFunc = ft->GetReturnType()->IsVoidType();
3462 
3463  // Automatically convert function call args to references if needed.
3464  // FIXME: this should move to the TypeCheck() method... (but the
3465  // GetLValue call below needs a FunctionEmitContext, which is
3466  // problematic...)
3467  std::vector<Expr *> callargs = args->exprs;
3468 
3469  // Specifically, this can happen if there's an error earlier during
3470  // overload resolution.
3471  if ((int)callargs.size() > ft->GetNumParameters()) {
3472  AssertPos(pos, m->errorCount > 0);
3473  return NULL;
3474  }
3475 
3476  for (unsigned int i = 0; i < callargs.size(); ++i) {
3477  Expr *argExpr = callargs[i];
3478  if (argExpr == NULL)
3479  continue;
3480 
3481  const Type *paramType = ft->GetParameterType(i);
3482 
3483  const Type *argLValueType = argExpr->GetLValueType();
3484  if (argLValueType != NULL && CastType<PointerType>(argLValueType) != NULL && argLValueType->IsVaryingType() &&
3485  CastType<ReferenceType>(paramType) != NULL) {
3486  Error(argExpr->pos,
3487  "Illegal to pass a \"varying\" lvalue to a "
3488  "reference parameter of type \"%s\".",
3489  paramType->GetString().c_str());
3490  return NULL;
3491  }
3492 
3493  // Do whatever type conversion is needed
3494  argExpr = TypeConvertExpr(argExpr, paramType, "function call argument");
3495  if (argExpr == NULL)
3496  return NULL;
3497  callargs[i] = argExpr;
3498  }
3499 
3500  // Fill in any default argument values needed.
3501  // FIXME: should we do this during type checking?
3502  for (int i = callargs.size(); i < ft->GetNumParameters(); ++i) {
3503  Expr *paramDefault = ft->GetParameterDefault(i);
3504  const Type *paramType = ft->GetParameterType(i);
3505  // FIXME: this type conv should happen when we create the function
3506  // type!
3507  Expr *d = TypeConvertExpr(paramDefault, paramType, "function call default argument");
3508  if (d == NULL)
3509  return NULL;
3510  callargs.push_back(d);
3511  }
3512 
3513  // Now evaluate the values of all of the parameters being passed.
3514  std::vector<llvm::Value *> argVals;
3515  for (unsigned int i = 0; i < callargs.size(); ++i) {
3516  Expr *argExpr = callargs[i];
3517  if (argExpr == NULL)
3518  // give up; we hit an error earlier
3519  return NULL;
3520 
3521  llvm::Value *argValue = argExpr->GetValue(ctx);
3522  if (argValue == NULL)
3523  // something went wrong in evaluating the argument's
3524  // expression, so give up on this
3525  return NULL;
3526 
3527  argVals.push_back(argValue);
3528  }
3529 
3530  llvm::Value *retVal = NULL;
3531  ctx->SetDebugPos(pos);
3532  if (ft->isTask) {
3533  AssertPos(pos, launchCountExpr[0] != NULL);
3534  llvm::Value *launchCount[3] = {launchCountExpr[0]->GetValue(ctx), launchCountExpr[1]->GetValue(ctx),
3535  launchCountExpr[2]->GetValue(ctx)};
3536 
3537  if (launchCount[0] != NULL)
3538  ctx->LaunchInst(callee, argVals, launchCount);
3539  } else
3540  retVal = ctx->CallInst(callee, ft, argVals, isVoidFunc ? "" : "calltmp");
3541 
3542  if (isVoidFunc)
3543  return NULL;
3544  else
3545  return retVal;
3546 }
3547 
3549  if (GetLValueType() != NULL) {
3550  return GetValue(ctx);
3551  } else {
3552  // Only be a valid LValue type if the function
3553  // returns a pointer or reference.
3554  return NULL;
3555  }
3556 }
3557 
3558 bool FullResolveOverloads(Expr *func, ExprList *args, std::vector<const Type *> *argTypes,
3559  std::vector<bool> *argCouldBeNULL, std::vector<bool> *argIsConstant) {
3560  for (unsigned int i = 0; i < args->exprs.size(); ++i) {
3561  Expr *expr = args->exprs[i];
3562  if (expr == NULL)
3563  return false;
3564  const Type *t = expr->GetType();
3565  if (t == NULL)
3566  return false;
3567  argTypes->push_back(t);
3568  argCouldBeNULL->push_back(lIsAllIntZeros(expr) || llvm::dyn_cast<NullPointerExpr>(expr));
3569  argIsConstant->push_back(llvm::dyn_cast<ConstExpr>(expr) || llvm::dyn_cast<NullPointerExpr>(expr));
3570  }
3571  return true;
3572 }
3573 
3575  std::vector<const Type *> argTypes;
3576  std::vector<bool> argCouldBeNULL, argIsConstant;
3577  if (FullResolveOverloads(func, args, &argTypes, &argCouldBeNULL, &argIsConstant) == true) {
3578  FunctionSymbolExpr *fse = llvm::dyn_cast<FunctionSymbolExpr>(func);
3579  if (fse != NULL) {
3580  fse->ResolveOverloads(args->pos, argTypes, &argCouldBeNULL, &argIsConstant);
3581  }
3582  }
3583  const FunctionType *ftype = lGetFunctionType(func);
3584  return ftype ? ftype->GetReturnType() : NULL;
3585 }
3586 
3588  const FunctionType *ftype = lGetFunctionType(func);
3589  if (ftype && (ftype->GetReturnType()->IsPointerType() || ftype->GetReturnType()->IsReferenceType())) {
3590  return ftype->GetReturnType();
3591  } else {
3592  // Only be a valid LValue type if the function
3593  // returns a pointer or reference.
3594  return NULL;
3595  }
3596 }
3597 
3599  if (func == NULL || args == NULL)
3600  return NULL;
3601  return this;
3602 }
3603 
3605  if (func == NULL || args == NULL)
3606  return NULL;
3607 
3608  std::vector<const Type *> argTypes;
3609  std::vector<bool> argCouldBeNULL, argIsConstant;
3610 
3611  if (FullResolveOverloads(func, args, &argTypes, &argCouldBeNULL, &argIsConstant) == false) {
3612  return NULL;
3613  }
3614 
3615  FunctionSymbolExpr *fse = llvm::dyn_cast<FunctionSymbolExpr>(func);
3616  if (fse != NULL) {
3617  // Regular function call
3618  if (fse->ResolveOverloads(args->pos, argTypes, &argCouldBeNULL, &argIsConstant) == false)
3619  return NULL;
3620 
3621  func = ::TypeCheck(fse);
3622  if (func == NULL)
3623  return NULL;
3624 
3625  const FunctionType *ft = CastType<FunctionType>(func->GetType());
3626  if (ft == NULL) {
3627  const PointerType *pt = CastType<PointerType>(func->GetType());
3628  ft = (pt == NULL) ? NULL : CastType<FunctionType>(pt->GetBaseType());
3629  }
3630 
3631  if (ft == NULL) {
3632  Error(pos, "Valid function name must be used for function call.");
3633  return NULL;
3634  }
3635 
3636  if (ft->isTask) {
3637  if (!isLaunch)
3638  Error(pos, "\"launch\" expression needed to call function "
3639  "with \"task\" qualifier.");
3640  for (int k = 0; k < 3; k++) {
3641  if (!launchCountExpr[k])
3642  return NULL;
3643 
3645  if (launchCountExpr[k] == NULL)
3646  return NULL;
3647  }
3648  } else {
3649  if (isLaunch) {
3650  Error(pos, "\"launch\" expression illegal with non-\"task\"-"
3651  "qualified function.");
3652  return NULL;
3653  }
3654  AssertPos(pos, launchCountExpr[0] == NULL);
3655  }
3656  } else {
3657  // Call through a function pointer
3658  const Type *fptrType = func->GetType();
3659  if (fptrType == NULL)
3660  return NULL;
3661 
3662  // Make sure we do in fact have a function to call
3663  const FunctionType *funcType;
3664  if (CastType<PointerType>(fptrType) == NULL ||
3665  (funcType = CastType<FunctionType>(fptrType->GetBaseType())) == NULL) {
3666  Error(func->pos, "Must provide function name or function pointer for "
3667  "function call expression.");
3668  return NULL;
3669  }
3670 
3671  // Make sure we don't have too many arguments for the function
3672  if ((int)argTypes.size() > funcType->GetNumParameters()) {
3673  Error(args->pos,
3674  "Too many parameter values provided in "
3675  "function call (%d provided, %d expected).",
3676  (int)argTypes.size(), funcType->GetNumParameters());
3677  return NULL;
3678  }
3679  // It's ok to have too few arguments, as long as the function's
3680  // default parameter values have started by the time we run out
3681  // of arguments
3682  if ((int)argTypes.size() < funcType->GetNumParameters() &&
3683  funcType->GetParameterDefault(argTypes.size()) == NULL) {
3684  Error(args->pos,
3685  "Too few parameter values provided in "
3686  "function call (%d provided, %d expected).",
3687  (int)argTypes.size(), funcType->GetNumParameters());
3688  return NULL;
3689  }
3690 
3691  // Now make sure they can all type convert to the corresponding
3692  // parameter types..
3693  for (int i = 0; i < (int)argTypes.size(); ++i) {
3694  if (i < funcType->GetNumParameters()) {
3695  // make sure it can type convert
3696  const Type *paramType = funcType->GetParameterType(i);
3697  if (CanConvertTypes(argTypes[i], paramType) == false &&
3698  !(argCouldBeNULL[i] == true && CastType<PointerType>(paramType) != NULL)) {
3699  Error(args->exprs[i]->pos,
3700  "Can't convert argument of "
3701  "type \"%s\" to type \"%s\" for function call "
3702  "argument.",
3703  argTypes[i]->GetString().c_str(), paramType->GetString().c_str());
3704  return NULL;
3705  }
3706  } else
3707  // Otherwise the parameter default saves us. It should
3708  // be there for sure, given the check right above the
3709  // for loop.
3710  AssertPos(pos, funcType->GetParameterDefault(i) != NULL);
3711  }
3712 
3713  if (fptrType->IsVaryingType()) {
3714  const Type *retType = funcType->GetReturnType();
3715  if (retType->IsVoidType() == false && retType->IsUniformType()) {
3716  Error(pos,
3717  "Illegal to call a varying function pointer that "
3718  "points to a function with a uniform return type \"%s\".",
3719  funcType->GetReturnType()->GetString().c_str());
3720  return NULL;
3721  }
3722  }
3723  }
3724 
3725  if (func == NULL || args == NULL)
3726  return NULL;
3727  return this;
3728 }
3729 
3731  if (isLaunch)
3732  return COST_TASK_LAUNCH;
3733 
3734  const Type *type = func->GetType();
3735  if (type == NULL)
3736  return 0;
3737 
3738  const PointerType *pt = CastType<PointerType>(type);
3739  if (pt != NULL)
3740  type = type->GetBaseType();
3741 
3742  const FunctionType *ftype = CastType<FunctionType>(type);
3743  if (ftype != NULL && ftype->costOverride > -1)
3744  return ftype->costOverride;
3745 
3746  if (pt != NULL)
3748  else
3749  return COST_FUNCALL;
3750 }
3751 
3753  if (!func || !args || !GetType())
3754  return;
3755 
3756  printf("[%s] funcall %s ", GetType()->GetString().c_str(), isLaunch ? "launch" : "");
3757  func->Print();
3758  printf(" args (");
3759  args->Print();
3760  printf(")");
3761  pos.Print();
3762 }
3763 
3764 ///////////////////////////////////////////////////////////////////////////
3765 // ExprList
3766 
3767 llvm::Value *ExprList::GetValue(FunctionEmitContext *ctx) const {
3768  FATAL("ExprList::GetValue() should never be called");
3769  return NULL;
3770 }
3771 
3772 const Type *ExprList::GetType() const {
3773  FATAL("ExprList::GetType() should never be called");
3774  return NULL;
3775 }
3776 
3777 ExprList *ExprList::Optimize() { return this; }
3778 
3779 ExprList *ExprList::TypeCheck() { return this; }
3780 
3781 static std::pair<llvm::Constant *, bool> lGetExprListConstant(const Type *type, const ExprList *eList,
3782  bool isStorageType) {
3783  std::vector<Expr *> exprs = eList->exprs;
3784  SourcePos pos = eList->pos;
3785  bool isVaryingInit = false;
3786  bool isNotValidForMultiTargetGlobal = false;
3787  if (exprs.size() == 1 && (CastType<AtomicType>(type) != NULL || CastType<EnumType>(type) != NULL ||
3788  CastType<PointerType>(type) != NULL)) {
3789  if (isStorageType)
3790  return exprs[0]->GetStorageConstant(type);
3791  else
3792  return exprs[0]->GetConstant(type);
3793  }
3794 
3795  const CollectionType *collectionType = CastType<CollectionType>(type);
3796  if (collectionType == NULL) {
3797  if (type->IsVaryingType() == true) {
3798  isVaryingInit = true;
3799  } else
3800  return std::pair<llvm::Constant *, bool>(NULL, false);
3801  }
3802 
3803  std::string name;
3804  if (CastType<StructType>(type) != NULL)
3805  name = "struct";
3806  else if (CastType<ArrayType>(type) != NULL)
3807  name = "array";
3808  else if (CastType<VectorType>(type) != NULL)
3809  name = "vector";
3810  else if (isVaryingInit == true)
3811  name = "varying";
3812  else
3813  FATAL("Unexpected CollectionType in lGetExprListConstant");
3814 
3815  int elementCount = (isVaryingInit == true) ? g->target->getVectorWidth() : collectionType->GetElementCount();
3816  if ((int)exprs.size() > elementCount) {
3817  const Type *errType = (isVaryingInit == true) ? type : collectionType;
3818  Error(pos,
3819  "Initializer list for %s \"%s\" must have no more than %d "
3820  "elements (has %d).",
3821  name.c_str(), errType->GetString().c_str(), elementCount, (int)exprs.size());
3822  return std::pair<llvm::Constant *, bool>(NULL, false);
3823  } else if ((isVaryingInit == true) && ((int)exprs.size() < elementCount)) {
3824  Error(pos,
3825  "Initializer list for %s \"%s\" must have %d "
3826  "elements (has %d).",
3827  name.c_str(), type->GetString().c_str(), elementCount, (int)exprs.size());
3828  return std::pair<llvm::Constant *, bool>(NULL, false);
3829  }
3830 
3831  std::vector<llvm::Constant *> cv;
3832  for (unsigned int i = 0; i < exprs.size(); ++i) {
3833  if (exprs[i] == NULL)
3834  return std::pair<llvm::Constant *, bool>(NULL, false);
3835  const Type *elementType =
3836  (isVaryingInit == true) ? type->GetAsUniformType() : collectionType->GetElementType(i);
3837 
3838  Expr *expr = exprs[i];
3839 
3840  if (llvm::dyn_cast<ExprList>(expr) == NULL) {
3841  // If there's a simple type conversion from the type of this
3842  // expression to the type we need, then let the regular type
3843  // conversion machinery handle it.
3844  expr = TypeConvertExpr(exprs[i], elementType, "initializer list");
3845  if (expr == NULL) {
3846  AssertPos(pos, m->errorCount > 0);
3847  return std::pair<llvm::Constant *, bool>(NULL, false);
3848  }
3849  // Re-establish const-ness if possible
3850  expr = ::Optimize(expr);
3851  }
3852  std::pair<llvm::Constant *, bool> cPair;
3853  if (isStorageType)
3854  cPair = expr->GetStorageConstant(elementType);
3855  else
3856  cPair = expr->GetConstant(elementType);
3857  llvm::Constant *c = cPair.first;
3858  if (c == NULL)
3859  // If this list element couldn't convert to the right constant
3860  // type for the corresponding collection member, then give up.
3861  return std::pair<llvm::Constant *, bool>(NULL, false);
3862  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || cPair.second;
3863  cv.push_back(c);
3864  }
3865 
3866  // If there are too few, then treat missing ones as if they were zero
3867  if (isVaryingInit == false) {
3868  for (int i = (int)exprs.size(); i < collectionType->GetElementCount(); ++i) {
3869  const Type *elementType = collectionType->GetElementType(i);
3870  if (elementType == NULL) {
3871  AssertPos(pos, m->errorCount > 0);
3872  return std::pair<llvm::Constant *, bool>(NULL, false);
3873  }
3874  llvm::Type *llvmType = elementType->LLVMType(g->ctx);
3875  if (llvmType == NULL) {
3876  AssertPos(pos, m->errorCount > 0);
3877  return std::pair<llvm::Constant *, bool>(NULL, false);
3878  }
3879 
3880  llvm::Constant *c = llvm::Constant::getNullValue(llvmType);
3881  cv.push_back(c);
3882  }
3883  }
3884 
3885  if (CastType<StructType>(type) != NULL) {
3886  llvm::StructType *llvmStructType = llvm::dyn_cast<llvm::StructType>(collectionType->LLVMType(g->ctx));
3887  AssertPos(pos, llvmStructType != NULL);
3888  return std::pair<llvm::Constant *, bool>(llvm::ConstantStruct::get(llvmStructType, cv),
3889  isNotValidForMultiTargetGlobal);
3890  } else {
3891  llvm::Type *lt = type->LLVMType(g->ctx);
3892  llvm::ArrayType *lat = llvm::dyn_cast<llvm::ArrayType>(lt);
3893  if (lat != NULL)
3894  return std::pair<llvm::Constant *, bool>(llvm::ConstantArray::get(lat, cv), isNotValidForMultiTargetGlobal);
3895  else if (type->IsVaryingType()) {
3896  // uniform short vector type
3897  llvm::VectorType *lvt = llvm::dyn_cast<llvm::VectorType>(lt);
3898  AssertPos(pos, lvt != NULL);
3899  int vectorWidth = g->target->getVectorWidth();
3900 
3901  while ((cv.size() % vectorWidth) != 0) {
3902  cv.push_back(llvm::UndefValue::get(lvt->getElementType()));
3903  }
3904 
3905  return std::pair<llvm::Constant *, bool>(llvm::ConstantVector::get(cv), isNotValidForMultiTargetGlobal);
3906  } else {
3907  // uniform short vector type
3908  AssertPos(pos, type->IsUniformType() && CastType<VectorType>(type) != NULL);
3909 
3910  llvm::VectorType *lvt = llvm::dyn_cast<llvm::VectorType>(lt);
3911  AssertPos(pos, lvt != NULL);
3912 
3913  // Uniform short vectors are stored as vectors of length
3914  // rounded up to a power of 2 bits in size but not less then 128 bit.
3915  // So we add additional undef values here until we get the right size.
3916  const VectorType *vt = CastType<VectorType>(type);
3917  int vectorWidth = vt->getVectorMemoryCount();
3918 
3919  while ((cv.size() % vectorWidth) != 0) {
3920  cv.push_back(llvm::UndefValue::get(lvt->getElementType()));
3921  }
3922 
3923  return std::pair<llvm::Constant *, bool>(llvm::ConstantVector::get(cv), isNotValidForMultiTargetGlobal);
3924  }
3925  }
3926  return std::pair<llvm::Constant *, bool>(NULL, false);
3927 }
3928 
3929 std::pair<llvm::Constant *, bool> ExprList::GetStorageConstant(const Type *type) const {
3930  return lGetExprListConstant(type, this, true);
3931 }
3932 std::pair<llvm::Constant *, bool> ExprList::GetConstant(const Type *type) const {
3933  return lGetExprListConstant(type, this, false);
3934 }
3935 
3936 int ExprList::EstimateCost() const { return 0; }
3937 
3938 void ExprList::Print() const {
3939  printf("expr list (");
3940  for (unsigned int i = 0; i < exprs.size(); ++i) {
3941  if (exprs[i] != NULL)
3942  exprs[i]->Print();
3943  printf("%s", (i == exprs.size() - 1) ? ")" : ", ");
3944  }
3945  pos.Print();
3946 }
3947 
3948 ///////////////////////////////////////////////////////////////////////////
3949 // IndexExpr
3950 
3952  baseExpr = a;
3953  index = i;
3954  type = lvalueType = NULL;
3955 }
3956 
3957 /** When computing pointer values, we need to apply a per-lane offset when
3958  we have a varying pointer that is itself indexing into varying data.
3959  Consdier the following ispc code:
3960 
3961  uniform float u[] = ...;
3962  float v[] = ...;
3963  int index = ...;
3964  float a = u[index];
3965  float b = v[index];
3966 
3967  To compute the varying pointer that holds the addresses to load from
3968  for u[index], we basically just need to multiply index element-wise by
3969  sizeof(float) before doing the memory load. For v[index], we need to
3970  do the same scaling but also need to add per-lane offsets <0,
3971  sizeof(float), 2*sizeof(float), ...> so that the i'th lane loads the
3972  i'th of the varying values at its index value.
3973 
3974  This function handles figuring out when this additional offset is
3975  needed and then incorporates it in the varying pointer value.
3976  */
3977 static llvm::Value *lAddVaryingOffsetsIfNeeded(FunctionEmitContext *ctx, llvm::Value *ptr, const Type *ptrRefType) {
3978  if (CastType<ReferenceType>(ptrRefType) != NULL)
3979  // References are uniform pointers, so no offsetting is needed
3980  return ptr;
3981 
3982  const PointerType *ptrType = CastType<PointerType>(ptrRefType);
3983  Assert(ptrType != NULL);
3984  if (ptrType->IsUniformType() || ptrType->IsSlice())
3985  return ptr;
3986 
3987  const Type *baseType = ptrType->GetBaseType();
3988  if (baseType->IsVaryingType() == false)
3989  return ptr;
3990 
3991  // must be indexing into varying atomic, enum, or pointer types
3992  if (Type::IsBasicType(baseType) == false)
3993  return ptr;
3994 
3995  // Onward: compute the per lane offsets.
3996  llvm::Value *varyingOffsets = ctx->ProgramIndexVector();
3997 
3998  // And finally add the per-lane offsets. Note that we lie to the GEP
3999  // call and tell it that the pointers are to uniform elements and not
4000  // varying elements, so that the offsets in terms of (0,1,2,...) will
4001  // end up turning into the correct step in bytes...
4002  const Type *uniformElementType = baseType->GetAsUniformType();
4003  const Type *ptrUnifType = PointerType::GetVarying(uniformElementType);
4004  return ctx->GetElementPtrInst(ptr, varyingOffsets, ptrUnifType);
4005 }
4006 
4007 /** Check to see if the given type is an array of or pointer to a varying
4008  struct type that in turn has a member with bound 'uniform' variability.
4009  Issue an error and return true if such a member is found.
4010  */
4012  if (CastType<VectorType>(type) != NULL || CastType<ReferenceType>(type) != NULL)
4013  return false;
4014 
4015  const StructType *st = CastType<StructType>(type);
4016  if (st == NULL) {
4017  const ArrayType *at = CastType<ArrayType>(type);
4018  if (at != NULL)
4019  st = CastType<StructType>(at->GetElementType());
4020  else {
4021  const PointerType *pt = CastType<PointerType>(type);
4022  if (pt == NULL)
4023  return false;
4024 
4025  st = CastType<StructType>(pt->GetBaseType());
4026  }
4027 
4028  if (st == NULL)
4029  return false;
4030  }
4031 
4032  if (st->IsVaryingType() == false)
4033  return false;
4034 
4035  for (int i = 0; i < st->GetElementCount(); ++i) {
4036  const Type *eltType = st->GetElementType(i);
4037  if (eltType == NULL) {
4038  AssertPos(pos, m->errorCount > 0);
4039  continue;
4040  }
4041 
4042  if (CastType<StructType>(eltType) != NULL) {
4043  // We know that the enclosing struct is varying at this point,
4044  // so push that down to the enclosed struct before makign the
4045  // recursive call.
4046  eltType = eltType->GetAsVaryingType();
4047  if (lVaryingStructHasUniformMember(eltType, pos))
4048  return true;
4049  } else if (eltType->IsUniformType()) {
4050  Error(pos,
4051  "Gather operation is impossible due to the presence of "
4052  "struct member \"%s\" with uniform type \"%s\" in the "
4053  "varying struct type \"%s\".",
4054  st->GetElementName(i).c_str(), eltType->GetString().c_str(), st->GetString().c_str());
4055  return true;
4056  }
4057  }
4058 
4059  return false;
4060 }
4061 
4062 llvm::Value *IndexExpr::GetValue(FunctionEmitContext *ctx) const {
4063  const Type *indexType, *returnType;
4064  if (baseExpr == NULL || index == NULL || ((indexType = index->GetType()) == NULL) ||
4065  ((returnType = GetType()) == NULL)) {
4066  AssertPos(pos, m->errorCount > 0);
4067  return NULL;
4068  }
4069 
4070  // If this is going to be a gather, make sure that the varying return
4071  // type can represent the result (i.e. that we don't have a bound
4072  // 'uniform' member in a varying struct...)
4073  if (indexType->IsVaryingType() && lVaryingStructHasUniformMember(returnType, pos))
4074  return NULL;
4075 
4076  ctx->SetDebugPos(pos);
4077 
4078  llvm::Value *ptr = GetLValue(ctx);
4079  llvm::Value *mask = NULL;
4080  const Type *lvType = GetLValueType();
4081  if (ptr == NULL) {
4082  // We may be indexing into a temporary that hasn't hit memory, so
4083  // get the full value and stuff it into temporary alloca'd space so
4084  // that we can index from there...
4085  const Type *baseExprType = baseExpr->GetType();
4086  llvm::Value *val = baseExpr->GetValue(ctx);
4087  if (baseExprType == NULL || val == NULL) {
4088  AssertPos(pos, m->errorCount > 0);
4089  return NULL;
4090  }
4091  ctx->SetDebugPos(pos);
4092  llvm::Value *tmpPtr = ctx->AllocaInst(baseExprType, "array_tmp");
4093  ctx->StoreInst(val, tmpPtr, baseExprType);
4094 
4095  // Get a pointer type to the underlying elements
4096  const SequentialType *st = CastType<SequentialType>(baseExprType);
4097  if (st == NULL) {
4098  Assert(m->errorCount > 0);
4099  return NULL;
4100  }
4101  lvType = PointerType::GetUniform(st->GetElementType());
4102 
4103  // And do the indexing calculation into the temporary array in memory
4104  ptr = ctx->GetElementPtrInst(tmpPtr, LLVMInt32(0), index->GetValue(ctx), PointerType::GetUniform(baseExprType));
4105  ptr = lAddVaryingOffsetsIfNeeded(ctx, ptr, lvType);
4106 
4107  mask = LLVMMaskAllOn;
4108  } else {
4109  Symbol *baseSym = GetBaseSymbol();
4110  if (llvm::dyn_cast<FunctionCallExpr>(baseExpr) == NULL && llvm::dyn_cast<BinaryExpr>(baseExpr) == NULL) {
4111  // Don't check if we're doing a function call or pointer arith
4112  AssertPos(pos, baseSym != NULL);
4113  }
4114  mask = lMaskForSymbol(baseSym, ctx);
4115  }
4116 
4117  ctx->SetDebugPos(pos);
4118  return ctx->LoadInst(ptr, mask, lvType);
4119 }
4120 
4121 const Type *IndexExpr::GetType() const {
4122  if (type != NULL)
4123  return type;
4124 
4125  const Type *baseExprType, *indexType;
4126  if (!baseExpr || !index || ((baseExprType = baseExpr->GetType()) == NULL) ||
4127  ((indexType = index->GetType()) == NULL))
4128  return NULL;
4129 
4130  const Type *elementType = NULL;
4131  const PointerType *pointerType = CastType<PointerType>(baseExprType);
4132  if (pointerType != NULL)
4133  // ptr[index] -> type that the pointer points to
4134  elementType = pointerType->GetBaseType();
4135  else {
4136  // sequential type[index] -> element type of the sequential type
4137  const SequentialType *sequentialType = CastType<SequentialType>(baseExprType->GetReferenceTarget());
4138  // Typechecking should have caught this...
4139  AssertPos(pos, sequentialType != NULL);
4140  elementType = sequentialType->GetElementType();
4141  }
4142 
4143  // If we're indexing into a sequence of SOA types, the result type is
4144  // actually the underlying type, as a uniform or varying. Get the
4145  // uniform variant of it for starters, then below we'll make it varying
4146  // if the index is varying.
4147  // (If we ever provide a way to index into SOA types and get an entire
4148  // SOA'd struct out of the array, then we won't want to do this in that
4149  // case..)
4150  if (elementType->IsSOAType())
4151  elementType = elementType->GetAsUniformType();
4152 
4153  // If either the index is varying or we're indexing into a varying
4154  // pointer, then the result type is the varying variant of the indexed
4155  // type.
4156  if (indexType->IsUniformType() && (pointerType == NULL || pointerType->IsUniformType()))
4157  type = elementType;
4158  else
4159  type = elementType->GetAsVaryingType();
4160 
4161  return type;
4162 }
4163 
4165 
4166 /** Utility routine that takes a regualr pointer (either uniform or
4167  varying) and returns a slice pointer with zero offsets.
4168  */
4169 static llvm::Value *lConvertToSlicePointer(FunctionEmitContext *ctx, llvm::Value *ptr,
4170  const PointerType *slicePtrType) {
4171  llvm::Type *llvmSlicePtrType = slicePtrType->LLVMType(g->ctx);
4172  llvm::StructType *sliceStructType = llvm::dyn_cast<llvm::StructType>(llvmSlicePtrType);
4173  Assert(sliceStructType != NULL && sliceStructType->getElementType(0) == ptr->getType());
4174 
4175  // Get a null-initialized struct to take care of having zeros for the
4176  // offsets
4177  llvm::Value *result = llvm::Constant::getNullValue(sliceStructType);
4178  // And replace the pointer in the struct with the given pointer
4179  return ctx->InsertInst(result, ptr, 0, LLVMGetName(ptr, "_slice"));
4180 }
4181 
4182 /** If the given array index is a compile time constant, check to see if it
4183  value/values don't go past the end of the array; issue a warning if
4184  so.
4185 */
4186 static void lCheckIndicesVersusBounds(const Type *baseExprType, Expr *index) {
4187  const SequentialType *seqType = CastType<SequentialType>(baseExprType);
4188  if (seqType == NULL)
4189  return;
4190 
4191  int nElements = seqType->GetElementCount();
4192  if (nElements == 0)
4193  // Unsized array...
4194  return;
4195 
4196  // If it's an array of soa<> items, then the number of elements to
4197  // worry about w.r.t. index values is the product of the array size and
4198  // the soa width.
4199  int soaWidth = seqType->GetElementType()->GetSOAWidth();
4200  if (soaWidth > 0)
4201  nElements *= soaWidth;
4202 
4203  ConstExpr *ce = llvm::dyn_cast<ConstExpr>(index);
4204  if (ce == NULL)
4205  return;
4206 
4207  int32_t indices[ISPC_MAX_NVEC];
4208  int count = ce->GetValues(indices);
4209  for (int i = 0; i < count; ++i) {
4210  if (indices[i] < 0 || indices[i] >= nElements)
4211  Warning(index->pos,
4212  "Array index \"%d\" may be out of bounds for %d "
4213  "element array.",
4214  indices[i], nElements);
4215  }
4216 }
4217 
4218 /** Converts the given pointer value to a slice pointer if the pointer
4219  points to SOA'ed data.
4220 */
4221 static llvm::Value *lConvertPtrToSliceIfNeeded(FunctionEmitContext *ctx, llvm::Value *ptr, const Type **type) {
4222  Assert(*type != NULL);
4223  const PointerType *ptrType = CastType<PointerType>(*type);
4224  Assert(ptrType != NULL);
4225  bool convertToSlice = (ptrType->GetBaseType()->IsSOAType() && ptrType->IsSlice() == false);
4226  if (convertToSlice == false)
4227  return ptr;
4228 
4229  *type = ptrType->GetAsSlice();
4230  return lConvertToSlicePointer(ctx, ptr, ptrType->GetAsSlice());
4231 }
4232 
4233 llvm::Value *IndexExpr::GetLValue(FunctionEmitContext *ctx) const {
4234  const Type *baseExprType;
4235  if (baseExpr == NULL || index == NULL || ((baseExprType = baseExpr->GetType()) == NULL)) {
4236  AssertPos(pos, m->errorCount > 0);
4237  return NULL;
4238  }
4239 
4240  ctx->SetDebugPos(pos);
4241  llvm::Value *indexValue = index->GetValue(ctx);
4242  if (indexValue == NULL) {
4243  AssertPos(pos, m->errorCount > 0);
4244  return NULL;
4245  }
4246 
4247  ctx->SetDebugPos(pos);
4248  if (CastType<PointerType>(baseExprType) != NULL) {
4249  // We're indexing off of a pointer
4250  llvm::Value *basePtrValue = baseExpr->GetValue(ctx);
4251  if (basePtrValue == NULL) {
4252  AssertPos(pos, m->errorCount > 0);
4253  return NULL;
4254  }
4255  ctx->SetDebugPos(pos);
4256 
4257  // Convert to a slice pointer if we're indexing into SOA data
4258  basePtrValue = lConvertPtrToSliceIfNeeded(ctx, basePtrValue, &baseExprType);
4259 
4260  llvm::Value *ptr =
4261  ctx->GetElementPtrInst(basePtrValue, indexValue, baseExprType, LLVMGetName(basePtrValue, "_offset"));
4262  return lAddVaryingOffsetsIfNeeded(ctx, ptr, GetLValueType());
4263  }
4264 
4265  // Not a pointer: we must be indexing an array or vector (and possibly
4266  // a reference thereuponfore.)
4267  llvm::Value *basePtr = NULL;
4268  const PointerType *basePtrType = NULL;
4269  if (CastType<ArrayType>(baseExprType) || CastType<VectorType>(baseExprType)) {
4270  basePtr = baseExpr->GetLValue(ctx);
4271  basePtrType = CastType<PointerType>(baseExpr->GetLValueType());
4272  if (baseExpr->GetLValueType())
4273  AssertPos(pos, basePtrType != NULL);
4274  } else {
4275  baseExprType = baseExprType->GetReferenceTarget();
4276  AssertPos(pos, CastType<ArrayType>(baseExprType) || CastType<VectorType>(baseExprType));
4277  basePtr = baseExpr->GetValue(ctx);
4278  basePtrType = PointerType::GetUniform(baseExprType);
4279  }
4280  if (!basePtr)
4281  return NULL;
4282 
4283  // If possible, check the index value(s) against the size of the array
4284  lCheckIndicesVersusBounds(baseExprType, index);
4285 
4286  // Convert to a slice pointer if indexing into SOA data
4287  basePtr = lConvertPtrToSliceIfNeeded(ctx, basePtr, (const Type **)&basePtrType);
4288 
4289  ctx->SetDebugPos(pos);
4290 
4291  // And do the actual indexing calculation..
4292  llvm::Value *ptr =
4293  ctx->GetElementPtrInst(basePtr, LLVMInt32(0), indexValue, basePtrType, LLVMGetName(basePtr, "_offset"));
4294  return lAddVaryingOffsetsIfNeeded(ctx, ptr, GetLValueType());
4295 }
4296 
4298  if (lvalueType != NULL)
4299  return lvalueType;
4300 
4301  const Type *baseExprType, *baseExprLValueType, *indexType;
4302  if (baseExpr == NULL || index == NULL || ((baseExprType = baseExpr->GetType()) == NULL) ||
4303  ((baseExprLValueType = baseExpr->GetLValueType()) == NULL) || ((indexType = index->GetType()) == NULL))
4304  return NULL;
4305 
4306  // regularize to a PointerType
4307  if (CastType<ReferenceType>(baseExprLValueType) != NULL) {
4308  const Type *refTarget = baseExprLValueType->GetReferenceTarget();
4309  baseExprLValueType = PointerType::GetUniform(refTarget);
4310  }
4311  AssertPos(pos, CastType<PointerType>(baseExprLValueType) != NULL);
4312 
4313  // Find the type of thing that we're indexing into
4314  const Type *elementType;
4315  const SequentialType *st = CastType<SequentialType>(baseExprLValueType->GetBaseType());
4316  if (st != NULL)
4317  elementType = st->GetElementType();
4318  else {
4319  const PointerType *pt = CastType<PointerType>(baseExprLValueType->GetBaseType());
4320  // This assertion seems overly strict.
4321  // Why does it need to be a pointer to a pointer?
4322  // AssertPos(pos, pt != NULL);
4323 
4324  if (pt != NULL) {
4325  elementType = pt->GetBaseType();
4326  } else {
4327  elementType = baseExprLValueType->GetBaseType();
4328  }
4329  }
4330 
4331  // Are we indexing into a varying type, or are we indexing with a
4332  // varying pointer?
4333  bool baseVarying;
4334  if (CastType<PointerType>(baseExprType) != NULL)
4335  baseVarying = baseExprType->IsVaryingType();
4336  else
4337  baseVarying = baseExprLValueType->IsVaryingType();
4338 
4339  // The return type is uniform iff. the base is a uniform pointer / a
4340  // collection of uniform typed elements and the index is uniform.
4341  if (baseVarying == false && indexType->IsUniformType())
4342  lvalueType = PointerType::GetUniform(elementType);
4343  else
4344  lvalueType = PointerType::GetVarying(elementType);
4345 
4346  // Finally, if we're indexing into an SOA type, then the resulting
4347  // pointer must (currently) be a slice pointer; we don't allow indexing
4348  // the soa-width-wide structs directly.
4349  if (elementType->IsSOAType())
4351 
4352  return lvalueType;
4353 }
4354 
4356  if (baseExpr == NULL || index == NULL)
4357  return NULL;
4358  return this;
4359 }
4360 
4362  const Type *indexType;
4363  if (baseExpr == NULL || index == NULL || ((indexType = index->GetType()) == NULL)) {
4364  AssertPos(pos, m->errorCount > 0);
4365  return NULL;
4366  }
4367 
4368  const Type *baseExprType = baseExpr->GetType();
4369  if (baseExprType == NULL) {
4370  AssertPos(pos, m->errorCount > 0);
4371  return NULL;
4372  }
4373 
4374  if (!CastType<SequentialType>(baseExprType->GetReferenceTarget())) {
4375  if (const PointerType *pt = CastType<PointerType>(baseExprType)) {
4376  if (pt->GetBaseType()->IsVoidType()) {
4377  Error(pos, "Illegal to dereference void pointer type \"%s\".", baseExprType->GetString().c_str());
4378  return NULL;
4379  }
4380  } else {
4381  Error(pos,
4382  "Trying to index into non-array, vector, or pointer "
4383  "type \"%s\".",
4384  baseExprType->GetString().c_str());
4385  return NULL;
4386  }
4387  }
4388 
4389  bool isUniform = (index->GetType()->IsUniformType() && !g->opt.disableUniformMemoryOptimizations);
4390 
4391  if (!isUniform) {
4392  // Unless we have an explicit 64-bit index and are compiling to a
4393  // 64-bit target with 64-bit addressing, convert the index to an int32
4394  // type.
4395  // The range of varying index is limited to [0,2^31) as a result.
4399  const Type *indexType = AtomicType::VaryingInt32;
4400  index = TypeConvertExpr(index, indexType, "array index");
4401  if (index == NULL)
4402  return NULL;
4403  }
4404  } else { // isUniform
4405  // For 32-bit target:
4406  // force the index to 32 bit.
4407  // For 64-bit target:
4408  // We don't want to limit the index range.
4409  // We sxt/zxt the index to 64 bit right here because
4410  // LLVM doesn't distinguish unsigned from signed (both are i32)
4411  //
4412  // However, the index can be still truncated to signed int32 if
4413  // the index type is 64 bit and --addressing=32.
4414  bool force_32bit =
4417  const Type *indexType = force_32bit ? AtomicType::UniformInt32 : AtomicType::UniformInt64;
4418  index = TypeConvertExpr(index, indexType, "array index");
4419  if (index == NULL)
4420  return NULL;
4421  }
4422 
4423  return this;
4424 }
4425 
4427  if (index == NULL || baseExpr == NULL)
4428  return 0;
4429 
4430  const Type *indexType = index->GetType();
4431  const Type *baseExprType = baseExpr->GetType();
4432 
4433  if ((indexType != NULL && indexType->IsVaryingType()) ||
4434  (CastType<PointerType>(baseExprType) != NULL && baseExprType->IsVaryingType()))
4435  // be pessimistic; some of these will later turn out to be vector
4436  // loads/stores, but it's too early for us to know that here.
4437  return COST_GATHER;
4438  else
4439  return COST_LOAD;
4440 }
4441 
4442 void IndexExpr::Print() const {
4443  if (!baseExpr || !index || !GetType())
4444  return;
4445 
4446  printf("[%s] index ", GetType()->GetString().c_str());
4447  baseExpr->Print();
4448  printf("[");
4449  index->Print();
4450  printf("]");
4451  pos.Print();
4452 }
4453 
4454 ///////////////////////////////////////////////////////////////////////////
4455 // MemberExpr
4456 
4457 /** Map one character ids to vector element numbers. Allow a few different
4458  conventions--xyzw, rgba, uv.
4459 */
4460 static int lIdentifierToVectorElement(char id) {
4461  switch (id) {
4462  case 'x':
4463  case 'r':
4464  case 'u':
4465  return 0;
4466  case 'y':
4467  case 'g':
4468  case 'v':
4469  return 1;
4470  case 'z':
4471  case 'b':
4472  return 2;
4473  case 'w':
4474  case 'a':
4475  return 3;
4476  default:
4477  return -1;
4478  }
4479 }
4480 
4481 //////////////////////////////////////////////////
4482 // StructMemberExpr
4483 
4485  public:
4486  StructMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue);
4487 
4488  static inline bool classof(StructMemberExpr const *) { return true; }
4489  static inline bool classof(ASTNode const *N) { return N->getValueID() == StructMemberExprID; }
4490 
4491  const Type *GetType() const;
4492  const Type *GetLValueType() const;
4493  int getElementNumber() const;
4494  const Type *getElementType() const;
4495 
4496  private:
4497  const StructType *getStructType() const;
4498 };
4499 
4500 StructMemberExpr::StructMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue)
4501  : MemberExpr(e, id, p, idpos, derefLValue, StructMemberExprID) {}
4502 
4504  if (type != NULL)
4505  return type;
4506 
4507  // It's a struct, and the result type is the element type, possibly
4508  // promoted to varying if the struct type / lvalue is varying.
4509  const Type *exprType, *lvalueType;
4510  const StructType *structType;
4511  if (expr == NULL || ((exprType = expr->GetType()) == NULL) || ((structType = getStructType()) == NULL) ||
4512  ((lvalueType = GetLValueType()) == NULL)) {
4513  AssertPos(pos, m->errorCount > 0);
4514  return NULL;
4515  }
4516 
4517  const Type *elementType = structType->GetElementType(identifier);
4518  if (elementType == NULL) {
4519  Error(identifierPos, "Element name \"%s\" not present in struct type \"%s\".%s", identifier.c_str(),
4520  structType->GetString().c_str(), getCandidateNearMatches().c_str());
4521  return NULL;
4522  }
4523  AssertPos(pos, Type::Equal(lvalueType->GetBaseType(), elementType));
4524 
4525  bool isSlice = (CastType<PointerType>(lvalueType) && CastType<PointerType>(lvalueType)->IsSlice());
4526  if (isSlice) {
4527  // FIXME: not true if we allow bound unif/varying for soa<>
4528  // structs?...
4529  AssertPos(pos, elementType->IsSOAType());
4530 
4531  // If we're accessing a member of an soa structure via a uniform
4532  // slice pointer, then the result type is the uniform variant of
4533  // the element type.
4534  if (lvalueType->IsUniformType())
4535  elementType = elementType->GetAsUniformType();
4536  }
4537 
4538  if (lvalueType->IsVaryingType())
4539  // If the expression we're getting the member of has an lvalue that
4540  // is a varying pointer type (be it slice or non-slice), then the
4541  // result type must be the varying version of the element type.
4542  elementType = elementType->GetAsVaryingType();
4543 
4544  type = elementType;
4545  return type;
4546 }
4547 
4549  if (lvalueType != NULL)
4550  return lvalueType;
4551 
4552  if (expr == NULL) {
4553  AssertPos(pos, m->errorCount > 0);
4554  return NULL;
4555  }
4556 
4557  const Type *exprLValueType = dereferenceExpr ? expr->GetType() : expr->GetLValueType();
4558  if (exprLValueType == NULL) {
4559  AssertPos(pos, m->errorCount > 0);
4560  return NULL;
4561  }
4562 
4563  // The pointer type is varying if the lvalue type of the expression is
4564  // varying (and otherwise uniform)
4565  const PointerType *ptrType = (exprLValueType->IsUniformType() || CastType<ReferenceType>(exprLValueType) != NULL)
4568 
4569  // If struct pointer is a slice pointer, the resulting member pointer
4570  // needs to be a frozen slice pointer--i.e. any further indexing with
4571  // the result shouldn't modify the minor slice offset, but it should be
4572  // left unchanged until we get to a leaf SOA value.
4573  if (CastType<PointerType>(exprLValueType) && CastType<PointerType>(exprLValueType)->IsSlice())
4574  ptrType = ptrType->GetAsFrozenSlice();
4575 
4576  lvalueType = ptrType;
4577  return lvalueType;
4578 }
4579 
4581  const StructType *structType = getStructType();
4582  if (structType == NULL)
4583  return -1;
4584 
4585  int elementNumber = structType->GetElementNumber(identifier);
4586  if (elementNumber == -1)
4587  Error(identifierPos, "Element name \"%s\" not present in struct type \"%s\".%s", identifier.c_str(),
4588  structType->GetString().c_str(), getCandidateNearMatches().c_str());
4589 
4590  return elementNumber;
4591 }
4592 
4594  const StructType *structType = getStructType();
4595  if (structType == NULL)
4596  return NULL;
4597 
4598  return structType->GetElementType(identifier);
4599 }
4600 
4601 /** Returns the type of the underlying struct that we're returning a member
4602  of. */
4604  const Type *type = dereferenceExpr ? expr->GetType() : expr->GetLValueType();
4605  if (type == NULL)
4606  return NULL;
4607 
4608  const Type *structType;
4609  const ReferenceType *rt = CastType<ReferenceType>(type);
4610  if (rt != NULL)
4611  structType = rt->GetReferenceTarget();
4612  else {
4613  const PointerType *pt = CastType<PointerType>(type);
4614  AssertPos(pos, pt != NULL);
4615  structType = pt->GetBaseType();
4616  }
4617 
4618  const StructType *ret = CastType<StructType>(structType);
4619  AssertPos(pos, ret != NULL);
4620  return ret;
4621 }
4622 
4623 //////////////////////////////////////////////////
4624 // VectorMemberExpr
4625 
4627  public:
4628  VectorMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue);
4629 
4630  static inline bool classof(VectorMemberExpr const *) { return true; }
4631  static inline bool classof(ASTNode const *N) { return N->getValueID() == VectorMemberExprID; }
4632 
4633  llvm::Value *GetValue(FunctionEmitContext *ctx) const;
4634  llvm::Value *GetLValue(FunctionEmitContext *ctx) const;
4635  const Type *GetType() const;
4636  const Type *GetLValueType() const;
4637 
4638  int getElementNumber() const;
4639  const Type *getElementType() const;
4640 
4641  private:
4644 };
4645 
4646 VectorMemberExpr::VectorMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue)
4647  : MemberExpr(e, id, p, idpos, derefLValue, VectorMemberExprID) {
4648  const Type *exprType = e->GetType();
4649  exprVectorType = CastType<VectorType>(exprType);
4650  if (exprVectorType == NULL) {
4651  const PointerType *pt = CastType<PointerType>(exprType);
4652  if (pt != NULL)
4653  exprVectorType = CastType<VectorType>(pt->GetBaseType());
4654  else {
4655  AssertPos(pos, CastType<ReferenceType>(exprType) != NULL);
4656  exprVectorType = CastType<VectorType>(exprType->GetReferenceTarget());
4657  }
4658  AssertPos(pos, exprVectorType != NULL);
4659  }
4661 }
4662 
4664  if (type != NULL)
4665  return type;
4666 
4667  // For 1-element expressions, we have the base vector element
4668  // type. For n-element expressions, we have a shortvec type
4669  // with n > 1 elements. This can be changed when we get
4670  // type<1> -> type conversions.
4671  type = (identifier.length() == 1) ? (const Type *)exprVectorType->GetElementType() : (const Type *)memberType;
4672 
4673  const Type *lvType = GetLValueType();
4674  if (lvType != NULL) {
4675  bool isSlice = (CastType<PointerType>(lvType) && CastType<PointerType>(lvType)->IsSlice());
4676  if (isSlice) {
4677  // CO AssertPos(pos, type->IsSOAType());
4678  if (lvType->IsUniformType())
4679  type = type->GetAsUniformType();
4680  }
4681 
4682  if (lvType->IsVaryingType())
4683  type = type->GetAsVaryingType();
4684  }
4685 
4686  return type;
4687 }
4688 
4690  if (identifier.length() == 1) {
4691  return MemberExpr::GetLValue(ctx);
4692  } else {
4693  return NULL;
4694  }
4695 }
4696 
4698  if (lvalueType != NULL)
4699  return lvalueType;
4700 
4701  if (identifier.length() == 1) {
4702  if (expr == NULL) {
4703  AssertPos(pos, m->errorCount > 0);
4704  return NULL;
4705  }
4706 
4707  const Type *exprLValueType = dereferenceExpr ? expr->GetType() : expr->GetLValueType();
4708  if (exprLValueType == NULL)
4709  return NULL;
4710 
4711  const VectorType *vt = NULL;
4712  if (CastType<ReferenceType>(exprLValueType) != NULL)
4713  vt = CastType<VectorType>(exprLValueType->GetReferenceTarget());
4714  else
4715  vt = CastType<VectorType>(exprLValueType->GetBaseType());
4716  AssertPos(pos, vt != NULL);
4717 
4718  // we don't want to report that it's e.g. a pointer to a float<1>,
4719  // but a pointer to a float, etc.
4720  const Type *elementType = vt->GetElementType();
4721  if (CastType<ReferenceType>(exprLValueType) != NULL)
4722  lvalueType = new ReferenceType(elementType);
4723  else {
4724  const PointerType *ptrType = exprLValueType->IsUniformType() ? PointerType::GetUniform(elementType)
4725  : PointerType::GetVarying(elementType);
4726  // FIXME: replicated logic with structmemberexpr....
4727  if (CastType<PointerType>(exprLValueType) && CastType<PointerType>(exprLValueType)->IsSlice())
4728  ptrType = ptrType->GetAsFrozenSlice();
4729  lvalueType = ptrType;
4730  }
4731  }
4732 
4733  return lvalueType;
4734 }
4735 
4737  if (identifier.length() == 1) {
4738  return MemberExpr::GetValue(ctx);
4739  } else {
4740  std::vector<int> indices;
4741 
4742  for (size_t i = 0; i < identifier.size(); ++i) {
4743  int idx = lIdentifierToVectorElement(identifier[i]);
4744  if (idx == -1)
4745  Error(pos, "Invalid swizzle character '%c' in swizzle \"%s\".", identifier[i], identifier.c_str());
4746 
4747  indices.push_back(idx);
4748  }
4749 
4750  llvm::Value *basePtr = NULL;
4751  const Type *basePtrType = NULL;
4752  if (dereferenceExpr) {
4753  basePtr = expr->GetValue(ctx);
4754  basePtrType = expr->GetType();
4755  } else {
4756  basePtr = expr->GetLValue(ctx);
4757  basePtrType = expr->GetLValueType();
4758  }
4759 
4760  if (basePtr == NULL || basePtrType == NULL) {
4761  // Check that expression on the left side is a rvalue expression
4762  llvm::Value *exprValue = expr->GetValue(ctx);
4763  basePtr = ctx->AllocaInst(expr->GetType());
4764  basePtrType = PointerType::GetUniform(exprVectorType);
4765  if (basePtr == NULL || basePtrType == NULL) {
4766  AssertPos(pos, m->errorCount > 0);
4767  return NULL;
4768  }
4769  ctx->StoreInst(exprValue, basePtr, expr->GetType());
4770  }
4771 
4772  // Allocate temporary memory to store the result
4773  llvm::Value *resultPtr = ctx->AllocaInst(memberType, "vector_tmp");
4774 
4775  // FIXME: we should be able to use the internal mask here according
4776  // to the same logic where it's used elsewhere
4777  llvm::Value *elementMask = ctx->GetFullMask();
4778 
4779  const Type *elementPtrType = NULL;
4780  if (CastType<ReferenceType>(basePtrType) != NULL)
4781  elementPtrType = PointerType::GetUniform(basePtrType->GetReferenceTarget());
4782  else
4783  elementPtrType = basePtrType->IsUniformType() ? PointerType::GetUniform(exprVectorType->GetElementType())
4785 
4786  ctx->SetDebugPos(pos);
4787  for (size_t i = 0; i < identifier.size(); ++i) {
4788  char idStr[2] = {identifier[i], '\0'};
4789  llvm::Value *elementPtr =
4790  ctx->AddElementOffset(basePtr, indices[i], basePtrType, LLVMGetName(basePtr, idStr));
4791  llvm::Value *elementValue = ctx->LoadInst(elementPtr, elementMask, elementPtrType);
4792 
4793  const char *resultName = LLVMGetName(resultPtr, idStr);
4794  llvm::Value *ptmp = ctx->AddElementOffset(resultPtr, i, NULL, resultName);
4795  ctx->StoreInst(elementValue, ptmp, elementPtrType);
4796  }
4797 
4798  return ctx->LoadInst(resultPtr, memberType, LLVMGetName(basePtr, "_swizzle"));
4799  }
4800 }
4801 
4803  int elementNumber = lIdentifierToVectorElement(identifier[0]);
4804  if (elementNumber == -1)
4805  Error(pos, "Vector element identifier \"%s\" unknown.", identifier.c_str());
4806  return elementNumber;
4807 }
4808 
4810 
4811 MemberExpr *MemberExpr::create(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue) {
4812  // FIXME: we need to call TypeCheck() here so that we can call
4813  // e->GetType() in the following. But really we just shouldn't try to
4814  // resolve this now but just have a generic MemberExpr type that
4815  // handles all cases so that this is unnecessary.
4816  e = ::TypeCheck(e);
4817 
4818  const Type *exprType;
4819  if (e == NULL || (exprType = e->GetType()) == NULL)
4820  return NULL;
4821 
4822  const ReferenceType *referenceType = CastType<ReferenceType>(exprType);
4823  if (referenceType != NULL) {
4824  e = new RefDerefExpr(e, e->pos);
4825  exprType = e->GetType();
4826  Assert(exprType != NULL);
4827  }
4828 
4829  const PointerType *pointerType = CastType<PointerType>(exprType);
4830  if (pointerType != NULL)
4831  exprType = pointerType->GetBaseType();
4832 
4833  if (derefLValue == true && pointerType == NULL) {
4834  const Type *targetType = exprType->GetReferenceTarget();
4835  if (CastType<StructType>(targetType) != NULL)
4836  Error(p,
4837  "Member operator \"->\" can't be applied to non-pointer "
4838  "type \"%s\". Did you mean to use \".\"?",
4839  exprType->GetString().c_str());
4840  else
4841  Error(p,
4842  "Member operator \"->\" can't be applied to non-struct "
4843  "pointer type \"%s\".",
4844  exprType->GetString().c_str());
4845  return NULL;
4846  }
4847  if (derefLValue == false && pointerType != NULL && CastType<StructType>(pointerType->GetBaseType()) != NULL) {
4848  Error(p,
4849  "Member operator \".\" can't be applied to pointer "
4850  "type \"%s\". Did you mean to use \"->\"?",
4851  exprType->GetString().c_str());
4852  return NULL;
4853  }
4854  if (CastType<StructType>(exprType) != NULL) {
4855  const StructType *st = CastType<StructType>(exprType);
4856  if (st->IsDefined()) {
4857  return new StructMemberExpr(e, id, p, idpos, derefLValue);
4858  } else {
4859  Error(p,
4860  "Member operator \"%s\" can't be applied to declared "
4861  "struct \"%s\" containing an undefined struct type.",
4862  derefLValue ? "->" : ".", exprType->GetString().c_str());
4863  return NULL;
4864  }
4865  } else if (CastType<VectorType>(exprType) != NULL)
4866  return new VectorMemberExpr(e, id, p, idpos, derefLValue);
4867  else if (CastType<UndefinedStructType>(exprType)) {
4868  Error(p,
4869  "Member operator \"%s\" can't be applied to declared "
4870  "but not defined struct type \"%s\".",
4871  derefLValue ? "->" : ".", exprType->GetString().c_str());
4872  return NULL;
4873  } else {
4874  Error(p,
4875  "Member operator \"%s\" can't be used with expression of "
4876  "\"%s\" type.",
4877  derefLValue ? "->" : ".", exprType->GetString().c_str());
4878  return NULL;
4879  }
4880 }
4881 
4882 MemberExpr::MemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue, unsigned scid)
4883  : Expr(p, scid), identifierPos(idpos) {
4884  expr = e;
4885  identifier = id;
4886  dereferenceExpr = derefLValue;
4887  type = lvalueType = NULL;
4888 }
4889 
4890 llvm::Value *MemberExpr::GetValue(FunctionEmitContext *ctx) const {
4891  if (!expr)
4892  return NULL;
4893 
4894  llvm::Value *lvalue = GetLValue(ctx);
4895  const Type *lvalueType = GetLValueType();
4896 
4897  llvm::Value *mask = NULL;
4898  if (lvalue == NULL) {
4899  if (m->errorCount > 0)
4900  return NULL;
4901 
4902  // As in the array case, this may be a temporary that hasn't hit
4903  // memory; get the full value and stuff it into a temporary array
4904  // so that we can index from there...
4905  llvm::Value *val = expr->GetValue(ctx);
4906  if (!val) {
4907  AssertPos(pos, m->errorCount > 0);
4908  return NULL;
4909  }
4910  ctx->SetDebugPos(pos);
4911  const Type *exprType = expr->GetType();
4912  llvm::Value *ptr = ctx->AllocaInst(exprType, "struct_tmp");
4913  ctx->StoreInst(val, ptr, exprType);
4914 
4915  int elementNumber = getElementNumber();
4916  if (elementNumber == -1)
4917  return NULL;
4918 
4919  lvalue = ctx->AddElementOffset(ptr, elementNumber, PointerType::GetUniform(exprType));
4920  lvalueType = PointerType::GetUniform(GetType());
4921  mask = LLVMMaskAllOn;
4922  } else {
4923  Symbol *baseSym = GetBaseSymbol();
4924  AssertPos(pos, baseSym != NULL);
4925  mask = lMaskForSymbol(baseSym, ctx);
4926  }
4927 
4928  ctx->SetDebugPos(pos);
4929  std::string suffix = std::string("_") + identifier;
4930  return ctx->LoadInst(lvalue, mask, lvalueType, LLVMGetName(lvalue, suffix.c_str()));
4931 }
4932 
4933 const Type *MemberExpr::GetType() const { return NULL; }
4934 
4935 Symbol *MemberExpr::GetBaseSymbol() const { return expr ? expr->GetBaseSymbol() : NULL; }
4936 
4937 int MemberExpr::getElementNumber() const { return -1; }
4938 
4939 llvm::Value *MemberExpr::GetLValue(FunctionEmitContext *ctx) const {
4940  const Type *exprType;
4941  if (!expr || ((exprType = expr->GetType()) == NULL))
4942  return NULL;
4943 
4944  ctx->SetDebugPos(pos);
4945  llvm::Value *basePtr = dereferenceExpr ? expr->GetValue(ctx) : expr->GetLValue(ctx);
4946  if (!basePtr)
4947  return NULL;
4948 
4949  int elementNumber = getElementNumber();
4950  if (elementNumber == -1)
4951  return NULL;
4952 
4953  const Type *exprLValueType = dereferenceExpr ? expr->GetType() : expr->GetLValueType();
4954  ctx->SetDebugPos(pos);
4955  llvm::Value *ptr = ctx->AddElementOffset(basePtr, elementNumber, exprLValueType, basePtr->getName().str().c_str());
4956  if (ptr == NULL) {
4957  AssertPos(pos, m->errorCount > 0);
4958  return NULL;
4959  }
4960 
4961  ptr = lAddVaryingOffsetsIfNeeded(ctx, ptr, GetLValueType());
4962 
4963  return ptr;
4964 }
4965 
4966 Expr *MemberExpr::TypeCheck() { return expr ? this : NULL; }
4967 
4968 Expr *MemberExpr::Optimize() { return expr ? this : NULL; }
4969 
4971  const Type *lvalueType = GetLValueType();
4972  if (lvalueType != NULL && lvalueType->IsVaryingType())
4974  else
4976 }
4977 
4978 void MemberExpr::Print() const {
4979  if (!expr || !GetType())
4980  return;
4981 
4982  printf("[%s] member (", GetType()->GetString().c_str());
4983  expr->Print();
4984  printf(" . %s)", identifier.c_str());
4985  pos.Print();
4986 }
4987 
4988 /** There is no structure member with the name we've got in "identifier".
4989  Use the approximate string matching routine to see if the identifier is
4990  a minor misspelling of one of the ones that is there.
4991  */
4993  const StructType *structType = CastType<StructType>(expr->GetType());
4994  if (!structType)
4995  return "";
4996 
4997  std::vector<std::string> elementNames;
4998  for (int i = 0; i < structType->GetElementCount(); ++i)
4999  elementNames.push_back(structType->GetElementName(i));
5000  std::vector<std::string> alternates = MatchStrings(identifier, elementNames);
5001  if (!alternates.size())
5002  return "";
5003 
5004  std::string ret = " Did you mean ";
5005  for (unsigned int i = 0; i < alternates.size(); ++i) {
5006  ret += std::string("\"") + alternates[i] + std::string("\"");
5007  if (i < alternates.size() - 1)
5008  ret += ", or ";
5009  }
5010  ret += "?";
5011  return ret;
5012 }
5013 
5014 ///////////////////////////////////////////////////////////////////////////
5015 // ConstExpr
5016 
5017 ConstExpr::ConstExpr(const Type *t, int8_t i, SourcePos p) : Expr(p, ConstExprID) {
5018  type = t;
5019  type = type->GetAsConstType();
5020  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt8->GetAsConstType()));
5021  int8Val[0] = i;
5022 }
5023 
5024 ConstExpr::ConstExpr(const Type *t, int8_t *i, SourcePos p) : Expr(p, ConstExprID) {
5025  type = t;
5026  type = type->GetAsConstType();
5027  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt8->GetAsConstType()) ||
5028  Type::Equal(type, AtomicType::VaryingInt8->GetAsConstType()));
5029  for (int j = 0; j < Count(); ++j)
5030  int8Val[j] = i[j];
5031 }
5032 
5033 ConstExpr::ConstExpr(const Type *t, uint8_t u, SourcePos p) : Expr(p, ConstExprID) {
5034  type = t;
5035  type = type->GetAsConstType();
5036  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt8->GetAsConstType()));
5037  uint8Val[0] = u;
5038 }
5039 
5040 ConstExpr::ConstExpr(const Type *t, uint8_t *u, SourcePos p) : Expr(p, ConstExprID) {
5041  type = t;
5042  type = type->GetAsConstType();
5043  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt8->GetAsConstType()) ||
5044  Type::Equal(type, AtomicType::VaryingUInt8->GetAsConstType()));
5045  for (int j = 0; j < Count(); ++j)
5046  uint8Val[j] = u[j];
5047 }
5048 
5049 ConstExpr::ConstExpr(const Type *t, int16_t i, SourcePos p) : Expr(p, ConstExprID) {
5050  type = t;
5051  type = type->GetAsConstType();
5052  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt16->GetAsConstType()));
5053  int16Val[0] = i;
5054 }
5055 
5056 ConstExpr::ConstExpr(const Type *t, int16_t *i, SourcePos p) : Expr(p, ConstExprID) {
5057  type = t;
5058  type = type->GetAsConstType();
5059  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt16->GetAsConstType()) ||
5060  Type::Equal(type, AtomicType::VaryingInt16->GetAsConstType()));
5061  for (int j = 0; j < Count(); ++j)
5062  int16Val[j] = i[j];
5063 }
5064 
5065 ConstExpr::ConstExpr(const Type *t, uint16_t u, SourcePos p) : Expr(p, ConstExprID) {
5066  type = t;
5067  type = type->GetAsConstType();
5068  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt16->GetAsConstType()));
5069  uint16Val[0] = u;
5070 }
5071 
5072 ConstExpr::ConstExpr(const Type *t, uint16_t *u, SourcePos p) : Expr(p, ConstExprID) {
5073  type = t;
5074  type = type->GetAsConstType();
5075  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt16->GetAsConstType()) ||
5076  Type::Equal(type, AtomicType::VaryingUInt16->GetAsConstType()));
5077  for (int j = 0; j < Count(); ++j)
5078  uint16Val[j] = u[j];
5079 }
5080 
5081 ConstExpr::ConstExpr(const Type *t, int32_t i, SourcePos p) : Expr(p, ConstExprID) {
5082  type = t;
5083  type = type->GetAsConstType();
5084  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt32->GetAsConstType()));
5085  int32Val[0] = i;
5086 }
5087 
5088 ConstExpr::ConstExpr(const Type *t, int32_t *i, SourcePos p) : Expr(p, ConstExprID) {
5089  type = t;
5090  type = type->GetAsConstType();
5091  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt32->GetAsConstType()) ||
5092  Type::Equal(type, AtomicType::VaryingInt32->GetAsConstType()));
5093  for (int j = 0; j < Count(); ++j)
5094  int32Val[j] = i[j];
5095 }
5096 
5097 ConstExpr::ConstExpr(const Type *t, uint32_t u, SourcePos p) : Expr(p, ConstExprID) {
5098  type = t;
5099  type = type->GetAsConstType();
5100  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt32->GetAsConstType()) ||
5101  (CastType<EnumType>(type) != NULL && type->IsUniformType()));
5102  uint32Val[0] = u;
5103 }
5104 
5105 ConstExpr::ConstExpr(const Type *t, uint32_t *u, SourcePos p) : Expr(p, ConstExprID) {
5106  type = t;
5107  type = type->GetAsConstType();
5108  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt32->GetAsConstType()) ||
5109  Type::Equal(type, AtomicType::VaryingUInt32->GetAsConstType()) ||
5110  (CastType<EnumType>(type) != NULL));
5111  for (int j = 0; j < Count(); ++j)
5112  uint32Val[j] = u[j];
5113 }
5114 
5115 ConstExpr::ConstExpr(const Type *t, float f, SourcePos p) : Expr(p, ConstExprID) {
5116  type = t;
5117  type = type->GetAsConstType();
5118  AssertPos(pos, Type::Equal(type, AtomicType::UniformFloat->GetAsConstType()));
5119  floatVal[0] = f;
5120 }
5121 
5122 ConstExpr::ConstExpr(const Type *t, float *f, SourcePos p) : Expr(p, ConstExprID) {
5123  type = t;
5124  type = type->GetAsConstType();
5125  AssertPos(pos, Type::Equal(type, AtomicType::UniformFloat->GetAsConstType()) ||
5126  Type::Equal(type, AtomicType::VaryingFloat->GetAsConstType()));
5127  for (int j = 0; j < Count(); ++j)
5128  floatVal[j] = f[j];
5129 }
5130 
5131 ConstExpr::ConstExpr(const Type *t, int64_t i, SourcePos p) : Expr(p, ConstExprID) {
5132  type = t;
5133  type = type->GetAsConstType();
5134  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt64->GetAsConstType()));
5135  int64Val[0] = i;
5136 }
5137 
5138 ConstExpr::ConstExpr(const Type *t, int64_t *i, SourcePos p) : Expr(p, ConstExprID) {
5139  type = t;
5140  type = type->GetAsConstType();
5141  AssertPos(pos, Type::Equal(type, AtomicType::UniformInt64->GetAsConstType()) ||
5142  Type::Equal(type, AtomicType::VaryingInt64->GetAsConstType()));
5143  for (int j = 0; j < Count(); ++j)
5144  int64Val[j] = i[j];
5145 }
5146 
5147 ConstExpr::ConstExpr(const Type *t, uint64_t u, SourcePos p) : Expr(p, ConstExprID) {
5148  type = t;
5149  type = type->GetAsConstType();
5150  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt64->GetAsConstType()));
5151  uint64Val[0] = u;
5152 }
5153 
5154 ConstExpr::ConstExpr(const Type *t, uint64_t *u, SourcePos p) : Expr(p, ConstExprID) {
5155  type = t;
5156  type = type->GetAsConstType();
5157  AssertPos(pos, Type::Equal(type, AtomicType::UniformUInt64->GetAsConstType()) ||
5158  Type::Equal(type, AtomicType::VaryingUInt64->GetAsConstType()));
5159  for (int j = 0; j < Count(); ++j)
5160  uint64Val[j] = u[j];
5161 }
5162 
5163 ConstExpr::ConstExpr(const Type *t, double f, SourcePos p) : Expr(p, ConstExprID) {
5164  type = t;
5165  type = type->GetAsConstType();
5166  AssertPos(pos, Type::Equal(type, AtomicType::UniformDouble->GetAsConstType()));
5167  doubleVal[0] = f;
5168 }
5169 
5170 ConstExpr::ConstExpr(const Type *t, double *f, SourcePos p) : Expr(p, ConstExprID) {
5171  type = t;
5172  type = type->GetAsConstType();
5173  AssertPos(pos, Type::Equal(type, AtomicType::UniformDouble->GetAsConstType()) ||
5174  Type::Equal(type, AtomicType::VaryingDouble->GetAsConstType()));
5175  for (int j = 0; j < Count(); ++j)
5176  doubleVal[j] = f[j];
5177 }
5178 
5180  type = t;
5181  type = type->GetAsConstType();
5182  AssertPos(pos, Type::Equal(type, AtomicType::UniformBool->GetAsConstType()));
5183  boolVal[0] = b;
5184 }
5185 
5186 ConstExpr::ConstExpr(const Type *t, bool *b, SourcePos p) : Expr(p, ConstExprID) {
5187  type = t;
5188  type = type->GetAsConstType();
5189  AssertPos(pos, Type::Equal(type, AtomicType::UniformBool->GetAsConstType()) ||
5190  Type::Equal(type, AtomicType::VaryingBool->GetAsConstType()));
5191  for (int j = 0; j < Count(); ++j)
5192  boolVal[j] = b[j];
5193 }
5194 
5195 ConstExpr::ConstExpr(ConstExpr *old, double *v) : Expr(old->pos, ConstExprID) {
5196  type = old->type;
5197 
5198  AtomicType::BasicType basicType = getBasicType();
5199 
5200  switch (basicType) {
5201  case AtomicType::TYPE_BOOL:
5202  for (int i = 0; i < Count(); ++i)
5203  boolVal[i] = (v[i] != 0.);
5204  break;
5205  case AtomicType::TYPE_INT8:
5206  for (int i = 0; i < Count(); ++i)
5207  int8Val[i] = (int)v[i];
5208  break;
5210  for (int i = 0; i < Count(); ++i)
5211  uint8Val[i] = (unsigned int)v[i];
5212  break;
5214  for (int i = 0; i < Count(); ++i)
5215  int16Val[i] = (int)v[i];
5216  break;
5218  for (int i = 0; i < Count(); ++i)
5219  uint16Val[i] = (unsigned int)v[i];
5220  break;
5222  for (int i = 0; i < Count(); ++i)
5223  int32Val[i] = (int)v[i];
5224  break;
5226  for (int i = 0; i < Count(); ++i)
5227  uint32Val[i] = (unsigned int)v[i];
5228  break;
5230  for (int i = 0; i < Count(); ++i)
5231  floatVal[i] = (float)v[i];
5232  break;
5234  for (int i = 0; i < Count(); ++i)
5235  doubleVal[i] = v[i];
5236  break;
5239  // For now, this should never be reached
5240  FATAL("fixme; we need another constructor so that we're not trying to pass "
5241  "double values to init an int64 type...");
5242  default:
5243  FATAL("unimplemented const type");
5244  }
5245 }
5246 
5248  type = old->type;
5249 
5250  AtomicType::BasicType basicType = getBasicType();
5251 
5252  switch (basicType) {
5253  case AtomicType::TYPE_BOOL:
5254  memcpy(boolVal, old->boolVal, Count() * sizeof(bool));
5255  break;
5256  case AtomicType::TYPE_INT8:
5257  memcpy(int8Val, old->int8Val, Count() * sizeof(int8_t));
5258  break;
5260  memcpy(uint8Val, old->uint8Val, Count() * sizeof(uint8_t));
5261  break;
5263  memcpy(int16Val, old->int16Val, Count() * sizeof(int16_t));
5264  break;
5266  memcpy(uint16Val, old->uint16Val, Count() * sizeof(uint16_t));
5267  break;
5269  memcpy(int32Val, old->int32Val, Count() * sizeof(int32_t));
5270  break;
5272  memcpy(uint32Val, old->uint32Val, Count() * sizeof(uint32_t));
5273  break;
5275  memcpy(floatVal, old->floatVal, Count() * sizeof(float));
5276  break;
5278  memcpy(doubleVal, old->doubleVal, Count() * sizeof(double));
5279  break;
5281  memcpy(int64Val, old->int64Val, Count() * sizeof(int64_t));
5282  break;
5284  memcpy(uint64Val, old->uint64Val, Count() * sizeof(uint64_t));
5285  break;
5286  default:
5287  FATAL("unimplemented const type");
5288  }
5289 }
5290 
5292  const AtomicType *at = CastType<AtomicType>(type);
5293  if (at != NULL)
5294  return at->basicType;
5295  else {
5296  AssertPos(pos, CastType<EnumType>(type) != NULL);
5297  return AtomicType::TYPE_UINT32;
5298  }
5299 }
5300 
5301 const Type *ConstExpr::GetType() const { return type; }
5302 
5303 llvm::Value *ConstExpr::GetValue(FunctionEmitContext *ctx) const {
5304  ctx->SetDebugPos(pos);
5305  bool isVarying = type->IsVaryingType();
5306 
5307  AtomicType::BasicType basicType = getBasicType();
5308 
5309  switch (basicType) {
5310  case AtomicType::TYPE_BOOL:
5311  if (isVarying)
5312  return LLVMBoolVector(boolVal);
5313  else
5314  return boolVal[0] ? LLVMTrue : LLVMFalse;
5315  case AtomicType::TYPE_INT8:
5316  return isVarying ? LLVMInt8Vector(int8Val) : LLVMInt8(int8Val[0]);
5318  return isVarying ? LLVMUInt8Vector(uint8Val) : LLVMUInt8(uint8Val[0]);
5320  return isVarying ? LLVMInt16Vector(int16Val) : LLVMInt16(int16Val[0]);
5322  return isVarying ? LLVMUInt16Vector(uint16Val) : LLVMUInt16(uint16Val[0]);
5324  return isVarying ? LLVMInt32Vector(int32Val) : LLVMInt32(int32Val[0]);
5326  return isVarying ? LLVMUInt32Vector(uint32Val) : LLVMUInt32(uint32Val[0]);
5328  return isVarying ? LLVMFloatVector(floatVal) : LLVMFloat(floatVal[0]);
5330  return isVarying ? LLVMInt64Vector(int64Val) : LLVMInt64(int64Val[0]);
5332  return isVarying ? LLVMUInt64Vector(uint64Val) : LLVMUInt64(uint64Val[0]);
5334  return isVarying ? LLVMDoubleVector(doubleVal) : LLVMDouble(doubleVal[0]);
5335  default:
5336  FATAL("unimplemented const type");
5337  return NULL;
5338  }
5339 }
5340 
5341 /* Type conversion templates: take advantage of C++ function overloading
5342  rules to get the one we want to match. */
5343 
5344 /* First the most general case, just use C++ type conversion if nothing
5345  else matches */
5346 template <typename From, typename To> static inline void lConvertElement(From from, To *to) { *to = (To)from; }
5347 
5348 /** When converting from bool types to numeric types, make sure the result
5349  is one or zero.
5350  */
5351 template <typename To> static inline void lConvertElement(bool from, To *to) { *to = from ? (To)1 : (To)0; }
5352 
5353 /** When converting numeric types to bool, compare to zero. (Do we
5354  actually need this one??) */
5355 template <typename From> static inline void lConvertElement(From from, bool *to) { *to = (from != 0); }
5356 
5357 /** And bool -> bool is just assignment */
5358 static inline void lConvertElement(bool from, bool *to) { *to = from; }
5359 
5360 /** Type conversion utility function
5361  */
5362 template <typename From, typename To> static void lConvert(const From *from, To *to, int count, bool forceVarying) {
5363  for (int i = 0; i < count; ++i)
5364  lConvertElement(from[i], &to[i]);
5365 
5366  if (forceVarying && count == 1)
5367  for (int i = 1; i < g->target->getVectorWidth(); ++i)
5368  to[i] = to[0];
5369 }
5370 
5371 int ConstExpr::GetValues(int64_t *ip, bool forceVarying) const {
5372  switch (getBasicType()) {
5373  case AtomicType::TYPE_BOOL:
5374  lConvert(boolVal, ip, Count(), forceVarying);
5375  break;
5376  case AtomicType::TYPE_INT8:
5377  lConvert(int8Val, ip, Count(), forceVarying);
5378  break;
5380  lConvert(uint8Val, ip, Count(), forceVarying);
5381  break;
5383  lConvert(int16Val, ip, Count(), forceVarying);
5384  break;
5386  lConvert(uint16Val, ip, Count(), forceVarying);
5387  break;
5389  lConvert(int32Val, ip, Count(), forceVarying);
5390  break;
5392  lConvert(uint32Val, ip, Count(), forceVarying);
5393  break;
5395  lConvert(floatVal, ip, Count(), forceVarying);
5396  break;
5398  lConvert(doubleVal, ip, Count(), forceVarying);
5399  break;
5401  lConvert(int64Val, ip, Count(), forceVarying);
5402  break;
5404  lConvert(uint64Val, ip, Count(), forceVarying);
5405  break;
5406  default:
5407  FATAL("unimplemented const type");
5408  }
5409  return Count();
5410 }
5411 
5412 int ConstExpr::GetValues(uint64_t *up, bool forceVarying) const {
5413  switch (getBasicType()) {
5414  case AtomicType::TYPE_BOOL:
5415  lConvert(boolVal, up, Count(), forceVarying);
5416  break;
5417  case AtomicType::TYPE_INT8:
5418  lConvert(int8Val, up, Count(), forceVarying);
5419  break;
5421  lConvert(uint8Val, up, Count(), forceVarying);
5422  break;
5424  lConvert(int16Val, up, Count(), forceVarying);
5425  break;
5427  lConvert(uint16Val, up, Count(), forceVarying);
5428  break;
5430  lConvert(int32Val, up, Count(), forceVarying);
5431  break;
5433  lConvert(uint32Val, up, Count(), forceVarying);
5434  break;
5436  lConvert(floatVal, up, Count(), forceVarying);
5437  break;
5439  lConvert(doubleVal, up, Count(), forceVarying);
5440  break;
5442  lConvert(int64Val, up, Count(), forceVarying);
5443  break;
5445  lConvert(uint64Val, up, Count(), forceVarying);
5446  break;
5447  default:
5448  FATAL("unimplemented const type");
5449  }
5450  return Count();
5451 }
5452 
5453 int ConstExpr::GetValues(double *d, bool forceVarying) const {
5454  switch (getBasicType()) {
5455  case AtomicType::TYPE_BOOL:
5456  lConvert(boolVal, d, Count(), forceVarying);
5457  break;
5458  case AtomicType::TYPE_INT8:
5459  lConvert(int8Val, d, Count(), forceVarying);
5460  break;
5462  lConvert(uint8Val, d, Count(), forceVarying);
5463  break;
5465  lConvert(int16Val, d, Count(), forceVarying);
5466  break;
5468  lConvert(uint16Val, d, Count(), forceVarying);
5469  break;
5471  lConvert(int32Val, d, Count(), forceVarying);
5472  break;
5474  lConvert(uint32Val, d, Count(), forceVarying);
5475  break;
5477  lConvert(floatVal, d, Count(), forceVarying);
5478  break;
5480  lConvert(doubleVal, d, Count(), forceVarying);
5481  break;
5483  lConvert(int64Val, d, Count(), forceVarying);
5484  break;
5486  lConvert(uint64Val, d, Count(), forceVarying);
5487  break;
5488  default:
5489  FATAL("unimplemented const type");
5490  }
5491  return Count();
5492 }
5493 
5494 int ConstExpr::GetValues(float *fp, bool forceVarying) const {
5495  switch (getBasicType()) {
5496  case AtomicType::TYPE_BOOL:
5497  lConvert(boolVal, fp, Count(), forceVarying);
5498  break;
5499  case AtomicType::TYPE_INT8:
5500  lConvert(int8Val, fp, Count(), forceVarying);
5501  break;
5503  lConvert(uint8Val, fp, Count(), forceVarying);
5504  break;
5506  lConvert(int16Val, fp, Count(), forceVarying);
5507  break;
5509  lConvert(uint16Val, fp, Count(), forceVarying);
5510  break;
5512  lConvert(int32Val, fp, Count(), forceVarying);
5513  break;
5515  lConvert(uint32Val, fp, Count(), forceVarying);
5516  break;
5518  lConvert(floatVal, fp, Count(), forceVarying);
5519  break;
5521  lConvert(doubleVal, fp, Count(), forceVarying);
5522  break;
5524  lConvert(int64Val, fp, Count(), forceVarying);
5525  break;
5527  lConvert(uint64Val, fp, Count(), forceVarying);
5528  break;
5529  default:
5530  FATAL("unimplemented const type");
5531  }
5532  return Count();
5533 }
5534 
5535 int ConstExpr::GetValues(bool *b, bool forceVarying) const {
5536  switch (getBasicType()) {
5537  case AtomicType::TYPE_BOOL:
5538  lConvert(boolVal, b, Count(), forceVarying);
5539  break;
5540  case AtomicType::TYPE_INT8:
5541  lConvert(int8Val, b, Count(), forceVarying);
5542  break;
5544  lConvert(uint8Val, b, Count(), forceVarying);
5545  break;
5547  lConvert(int16Val, b, Count(), forceVarying);
5548  break;
5550  lConvert(uint16Val, b, Count(), forceVarying);
5551  break;
5553  lConvert(int32Val, b, Count(), forceVarying);
5554  break;
5556  lConvert(uint32Val, b, Count(), forceVarying);
5557  break;
5559  lConvert(floatVal, b, Count(), forceVarying);
5560  break;
5562  lConvert(doubleVal, b, Count(), forceVarying);
5563  break;
5565  lConvert(int64Val, b, Count(), forceVarying);
5566  break;
5568  lConvert(uint64Val, b, Count(), forceVarying);
5569  break;
5570  default:
5571  FATAL("unimplemented const type");
5572  }
5573  return Count();
5574 }
5575 
5576 int ConstExpr::GetValues(int8_t *ip, bool forceVarying) const {
5577  switch (getBasicType()) {
5578  case AtomicType::TYPE_BOOL:
5579  lConvert(boolVal, ip, Count(), forceVarying);
5580  break;
5581  case AtomicType::TYPE_INT8:
5582  lConvert(int8Val, ip, Count(), forceVarying);
5583  break;
5585  lConvert(uint8Val, ip, Count(), forceVarying);
5586  break;
5588  lConvert(int16Val, ip, Count(), forceVarying);
5589  break;
5591  lConvert(uint16Val, ip, Count(), forceVarying);
5592  break;
5594  lConvert(int32Val, ip, Count(), forceVarying);
5595  break;
5597  lConvert(uint32Val, ip, Count(), forceVarying);
5598  break;
5600  lConvert(floatVal, ip, Count(), forceVarying);
5601  break;
5603  lConvert(doubleVal, ip, Count(), forceVarying);
5604  break;
5606  lConvert(int64Val, ip, Count(), forceVarying);
5607  break;
5609  lConvert(uint64Val, ip, Count(), forceVarying);
5610  break;
5611  default:
5612  FATAL("unimplemented const type");
5613  }
5614  return Count();
5615 }
5616 
5617 int ConstExpr::GetValues(uint8_t *up, bool forceVarying) const {
5618  switch (getBasicType()) {
5619  case AtomicType::TYPE_BOOL:
5620  lConvert(boolVal, up, Count(), forceVarying);
5621  break;
5622  case AtomicType::TYPE_INT8:
5623  lConvert(int8Val, up, Count(), forceVarying);
5624  break;
5626  lConvert(uint8Val, up, Count(), forceVarying);
5627  break;
5629  lConvert(int16Val, up, Count(), forceVarying);
5630  break;
5632  lConvert(uint16Val, up, Count(), forceVarying);
5633  break;
5635  lConvert(int32Val, up, Count(), forceVarying);
5636  break;
5638  lConvert(uint32Val, up, Count(), forceVarying);
5639  break;
5641  lConvert(floatVal, up, Count(), forceVarying);
5642  break;
5644  lConvert(doubleVal, up, Count(), forceVarying);
5645  break;
5647  lConvert(int64Val, up, Count(), forceVarying);
5648  break;
5650  lConvert(uint64Val, up, Count(), forceVarying);
5651  break;
5652  default:
5653  FATAL("unimplemented const type");
5654  }
5655  return Count();
5656 }
5657 
5658 int ConstExpr::GetValues(int16_t *ip, bool forceVarying) const {
5659  switch (getBasicType()) {
5660  case AtomicType::TYPE_BOOL:
5661  lConvert(boolVal, ip, Count(), forceVarying);
5662  break;
5663  case AtomicType::TYPE_INT8:
5664  lConvert(int8Val, ip, Count(), forceVarying);
5665  break;
5667  lConvert(uint8Val, ip, Count(), forceVarying);
5668  break;
5670  lConvert(int16Val, ip, Count(), forceVarying);
5671  break;
5673  lConvert(uint16Val, ip, Count(), forceVarying);
5674  break;
5676  lConvert(int32Val, ip, Count(), forceVarying);
5677  break;
5679  lConvert(uint32Val, ip, Count(), forceVarying);
5680  break;
5682  lConvert(floatVal, ip, Count(), forceVarying);
5683  break;
5685  lConvert(doubleVal, ip, Count(), forceVarying);
5686  break;
5688  lConvert(int64Val, ip, Count(), forceVarying);
5689  break;
5691  lConvert(uint64Val, ip, Count(), forceVarying);
5692  break;
5693  default:
5694  FATAL("unimplemented const type");
5695  }
5696  return Count();
5697 }
5698 
5699 int ConstExpr::GetValues(uint16_t *up, bool forceVarying) const {
5700  switch (getBasicType()) {
5701  case AtomicType::TYPE_BOOL:
5702  lConvert(boolVal, up, Count(), forceVarying);
5703  break;
5704  case AtomicType::TYPE_INT8:
5705  lConvert(int8Val, up, Count(), forceVarying);
5706  break;
5708  lConvert(uint8Val, up, Count(), forceVarying);
5709  break;
5711  lConvert(int16Val, up, Count(), forceVarying);
5712  break;
5714  lConvert(uint16Val, up, Count(), forceVarying);
5715  break;
5717  lConvert(int32Val, up, Count(), forceVarying);
5718  break;
5720  lConvert(uint32Val, up, Count(), forceVarying);
5721  break;
5723  lConvert(floatVal, up, Count(), forceVarying);
5724  break;
5726  lConvert(doubleVal, up, Count(), forceVarying);
5727  break;
5729  lConvert(int64Val, up, Count(), forceVarying);
5730  break;
5732  lConvert(uint64Val, up, Count(), forceVarying);
5733  break;
5734  default:
5735  FATAL("unimplemented const type");
5736  }
5737  return Count();
5738 }
5739 
5740 int ConstExpr::GetValues(int32_t *ip, bool forceVarying) const {
5741  switch (getBasicType()) {
5742  case AtomicType::TYPE_BOOL:
5743  lConvert(boolVal, ip, Count(), forceVarying);
5744  break;
5745  case AtomicType::TYPE_INT8:
5746  lConvert(int8Val, ip, Count(), forceVarying);
5747  break;
5749  lConvert(uint8Val, ip, Count(), forceVarying);
5750  break;
5752  lConvert(int16Val, ip, Count(), forceVarying);
5753  break;
5755  lConvert(uint16Val, ip, Count(), forceVarying);
5756  break;
5758  lConvert(int32Val, ip, Count(), forceVarying);
5759  break;
5761  lConvert(uint32Val, ip, Count(), forceVarying);
5762  break;
5764  lConvert(floatVal, ip, Count(), forceVarying);
5765  break;
5767  lConvert(doubleVal, ip, Count(), forceVarying);
5768  break;
5770  lConvert(int64Val, ip, Count(), forceVarying);
5771  break;
5773  lConvert(uint64Val, ip, Count(), forceVarying);
5774  break;
5775  default:
5776  FATAL("unimplemented const type");
5777  }
5778  return Count();
5779 }
5780 
5781 int ConstExpr::GetValues(uint32_t *up, bool forceVarying) const {
5782  switch (getBasicType()) {
5783  case AtomicType::TYPE_BOOL:
5784  lConvert(boolVal, up, Count(), forceVarying);
5785  break;
5786  case AtomicType::TYPE_INT8:
5787  lConvert(int8Val, up, Count(), forceVarying);
5788  break;
5790  lConvert(uint8Val, up, Count(), forceVarying);
5791  break;
5793  lConvert(int16Val, up, Count(), forceVarying);
5794  break;
5796  lConvert(uint16Val, up, Count(), forceVarying);
5797  break;
5799  lConvert(int32Val, up, Count(), forceVarying);
5800  break;
5802  lConvert(uint32Val, up, Count(), forceVarying);
5803  break;
5805  lConvert(floatVal, up, Count(), forceVarying);
5806  break;
5808  lConvert(doubleVal, up, Count(), forceVarying);
5809  break;
5811  lConvert(int64Val, up, Count(), forceVarying);
5812  break;
5814  lConvert(uint64Val, up, Count(), forceVarying);
5815  break;
5816  default:
5817  FATAL("unimplemented const type");
5818  }
5819  return Count();
5820 }
5821 
5822 int ConstExpr::Count() const { return GetType()->IsVaryingType() ? g->target->getVectorWidth() : 1; }
5823 
5824 static std::pair<llvm::Constant *, bool> lGetConstExprConstant(const Type *constType, const ConstExpr *cExpr,
5825  bool isStorageType) {
5826  // Caller shouldn't be trying to stuff a varying value here into a
5827  // constant type.
5828  SourcePos pos = cExpr->pos;
5829  bool isNotValidForMultiTargetGlobal = false;
5830  if (constType->IsUniformType())
5831  AssertPos(pos, cExpr->Count() == 1);
5832 
5833  constType = constType->GetAsNonConstType();
5835  bool bv[ISPC_MAX_NVEC];
5836  cExpr->GetValues(bv, constType->IsVaryingType());
5837  if (constType->IsUniformType()) {
5838  if (isStorageType)
5839  return std::pair<llvm::Constant *, bool>(bv[0] ? LLVMTrueInStorage : LLVMFalseInStorage,
5840  isNotValidForMultiTargetGlobal);
5841  else
5842  return std::pair<llvm::Constant *, bool>(bv[0] ? LLVMTrue : LLVMFalse, isNotValidForMultiTargetGlobal);
5843  } else {
5844  if (isStorageType)
5845  return std::pair<llvm::Constant *, bool>(LLVMBoolVectorInStorage(bv), isNotValidForMultiTargetGlobal);
5846  else
5847  return std::pair<llvm::Constant *, bool>(LLVMBoolVector(bv), isNotValidForMultiTargetGlobal);
5848  }
5849  } else if (Type::Equal(constType, AtomicType::UniformInt8) || Type::Equal(constType, AtomicType::VaryingInt8)) {
5850  int8_t iv[ISPC_MAX_NVEC];
5851  cExpr->GetValues(iv, constType->IsVaryingType());
5852  if (constType->IsUniformType())
5853  return std::pair<llvm::Constant *, bool>(LLVMInt8(iv[0]), isNotValidForMultiTargetGlobal);
5854  else
5855  return std::pair<llvm::Constant *, bool>(LLVMInt8Vector(iv), isNotValidForMultiTargetGlobal);
5856  } else if (Type::Equal(constType, AtomicType::UniformUInt8) || Type::Equal(constType, AtomicType::VaryingUInt8)) {
5857  uint8_t uiv[ISPC_MAX_NVEC];
5858  cExpr->GetValues(uiv, constType->IsVaryingType());
5859  if (constType->IsUniformType())
5860  return std::pair<llvm::Constant *, bool>(LLVMUInt8(uiv[0]), isNotValidForMultiTargetGlobal);
5861  else
5862  return std::pair<llvm::Constant *, bool>(LLVMUInt8Vector(uiv), isNotValidForMultiTargetGlobal);
5863  } else if (Type::Equal(constType, AtomicType::UniformInt16) || Type::Equal(constType, AtomicType::VaryingInt16)) {
5864  int16_t iv[ISPC_MAX_NVEC];
5865  cExpr->GetValues(iv, constType->IsVaryingType());
5866  if (constType->IsUniformType())
5867  return std::pair<llvm::Constant *, bool>(LLVMInt16(iv[0]), isNotValidForMultiTargetGlobal);
5868  else
5869  return std::pair<llvm::Constant *, bool>(LLVMInt16Vector(iv), isNotValidForMultiTargetGlobal);
5870  } else if (Type::Equal(constType, AtomicType::UniformUInt16) || Type::Equal(constType, AtomicType::VaryingUInt16)) {
5871  uint16_t uiv[ISPC_MAX_NVEC];
5872  cExpr->GetValues(uiv, constType->IsVaryingType());
5873  if (constType->IsUniformType())
5874  return std::pair<llvm::Constant *, bool>(LLVMUInt16(uiv[0]), isNotValidForMultiTargetGlobal);
5875  else
5876  return std::pair<llvm::Constant *, bool>(LLVMUInt16Vector(uiv), isNotValidForMultiTargetGlobal);
5877  } else if (Type::Equal(constType, AtomicType::UniformInt32) || Type::Equal(constType, AtomicType::VaryingInt32)) {
5878  int32_t iv[ISPC_MAX_NVEC];
5879  cExpr->GetValues(iv, constType->IsVaryingType());
5880  if (constType->IsUniformType())
5881  return std::pair<llvm::Constant *, bool>(LLVMInt32(iv[0]), isNotValidForMultiTargetGlobal);
5882  else
5883  return std::pair<llvm::Constant *, bool>(LLVMInt32Vector(iv), isNotValidForMultiTargetGlobal);
5884  } else if (Type::Equal(constType, AtomicType::UniformUInt32) || Type::Equal(constType, AtomicType::VaryingUInt32) ||
5885  CastType<EnumType>(constType) != NULL) {
5886  uint32_t uiv[ISPC_MAX_NVEC];
5887  cExpr->GetValues(uiv, constType->IsVaryingType());
5888  if (constType->IsUniformType())
5889  return std::pair<llvm::Constant *, bool>(LLVMUInt32(uiv[0]), isNotValidForMultiTargetGlobal);
5890  else
5891  return std::pair<llvm::Constant *, bool>(LLVMUInt32Vector(uiv), isNotValidForMultiTargetGlobal);
5892  } else if (Type::Equal(constType, AtomicType::UniformFloat) || Type::Equal(constType, AtomicType::VaryingFloat)) {
5893  float fv[ISPC_MAX_NVEC];
5894  cExpr->GetValues(fv, constType->IsVaryingType());
5895  if (constType->IsUniformType())
5896  return std::pair<llvm::Constant *, bool>(LLVMFloat(fv[0]), isNotValidForMultiTargetGlobal);
5897  else
5898  return std::pair<llvm::Constant *, bool>(LLVMFloatVector(fv), isNotValidForMultiTargetGlobal);
5899  } else if (Type::Equal(constType, AtomicType::UniformInt64) || Type::Equal(constType, AtomicType::VaryingInt64)) {
5900  int64_t iv[ISPC_MAX_NVEC];
5901  cExpr->GetValues(iv, constType->IsVaryingType());
5902  if (constType->IsUniformType())
5903  return std::pair<llvm::Constant *, bool>(LLVMInt64(iv[0]), isNotValidForMultiTargetGlobal);
5904  else
5905  return std::pair<llvm::Constant *, bool>(LLVMInt64Vector(iv), isNotValidForMultiTargetGlobal);
5906  } else if (Type::Equal(constType, AtomicType::UniformUInt64) || Type::Equal(constType, AtomicType::VaryingUInt64)) {
5907  uint64_t uiv[ISPC_MAX_NVEC];
5908  cExpr->GetValues(uiv, constType->IsVaryingType());
5909  if (constType->IsUniformType())
5910  return std::pair<llvm::Constant *, bool>(LLVMUInt64(uiv[0]), isNotValidForMultiTargetGlobal);
5911  else
5912  return std::pair<llvm::Constant *, bool>(LLVMUInt64Vector(uiv), isNotValidForMultiTargetGlobal);
5913  } else if (Type::Equal(constType, AtomicType::UniformDouble) || Type::Equal(constType, AtomicType::VaryingDouble)) {
5914  double dv[ISPC_MAX_NVEC];
5915  cExpr->GetValues(dv, constType->IsVaryingType());
5916  if (constType->IsUniformType())
5917  return std::pair<llvm::Constant *, bool>(LLVMDouble(dv[0]), isNotValidForMultiTargetGlobal);
5918  else
5919  return std::pair<llvm::Constant *, bool>(LLVMDoubleVector(dv), isNotValidForMultiTargetGlobal);
5920  } else if (CastType<PointerType>(constType) != NULL) {
5921  // The only time we should get here is if we have an integer '0'
5922  // constant that should be turned into a NULL pointer of the
5923  // appropriate type.
5924  llvm::Type *llvmType = constType->LLVMType(g->ctx);
5925  if (llvmType == NULL) {
5926  AssertPos(pos, m->errorCount > 0);
5927  return std::pair<llvm::Constant *, bool>(NULL, false);
5928  }
5929 
5930  int64_t iv[ISPC_MAX_NVEC];
5931  cExpr->GetValues(iv, constType->IsVaryingType());
5932  for (int i = 0; i < cExpr->Count(); ++i)
5933  if (iv[i] != 0)
5934  // We'll issue an error about this later--trying to assign
5935  // a constant int to a pointer, without a typecast.
5936  return std::pair<llvm::Constant *, bool>(NULL, false);
5937 
5938  return std::pair<llvm::Constant *, bool>(llvm::Constant::getNullValue(llvmType),
5939  isNotValidForMultiTargetGlobal);
5940  } else {
5941  Debug(pos, "Unable to handle type \"%s\" in ConstExpr::GetConstant().", constType->GetString().c_str());
5942  return std::pair<llvm::Constant *, bool>(NULL, isNotValidForMultiTargetGlobal);
5943  }
5944 }
5945 
5946 std::pair<llvm::Constant *, bool> ConstExpr::GetStorageConstant(const Type *constType) const {
5947  return lGetConstExprConstant(constType, this, true);
5948 }
5949 std::pair<llvm::Constant *, bool> ConstExpr::GetConstant(const Type *constType) const {
5950  return lGetConstExprConstant(constType, this, false);
5951 }
5952 
5953 Expr *ConstExpr::Optimize() { return this; }
5954 
5955 Expr *ConstExpr::TypeCheck() { return this; }
5956 
5957 int ConstExpr::EstimateCost() const { return 0; }
5958 
5959 void ConstExpr::Print() const {
5960  printf("[%s] (", GetType()->GetString().c_str());
5961  for (int i = 0; i < Count(); ++i) {
5962  switch (getBasicType()) {
5963  case AtomicType::TYPE_BOOL:
5964  printf("%s", boolVal[i] ? "true" : "false");
5965  break;
5966  case AtomicType::TYPE_INT8:
5967  printf("%d", (int)int8Val[i]);
5968  break;
5970  printf("%u", (int)uint8Val[i]);
5971  break;
5973  printf("%d", (int)int16Val[i]);
5974  break;
5976  printf("%u", (int)uint16Val[i]);
5977  break;
5979  printf("%d", int32Val[i]);
5980  break;
5982  printf("%u", uint32Val[i]);
5983  break;
5985  printf("%f", floatVal[i]);
5986  break;
5988  printf("%" PRId64, int64Val[i]);
5989  break;
5991  printf("%" PRIu64, uint64Val[i]);
5992  break;
5994  printf("%f", doubleVal[i]);
5995  break;
5996  default:
5997  FATAL("unimplemented const type");
5998  }
5999  if (i != Count() - 1)
6000  printf(", ");
6001  }
6002  printf(")");
6003  pos.Print();
6004 }
6005 
6006 ///////////////////////////////////////////////////////////////////////////
6007 // TypeCastExpr
6008 
6010  type = t;
6011  expr = e;
6012 }
6013 
6014 /** Handle all the grungy details of type conversion between atomic types.
6015  Given an input value in exprVal of type fromType, convert it to the
6016  llvm::Value with type toType.
6017  */
6018 static llvm::Value *lTypeConvAtomic(FunctionEmitContext *ctx, llvm::Value *exprVal, const AtomicType *toType,
6019  const AtomicType *fromType, SourcePos pos) {
6020  llvm::Value *cast = NULL;
6021 
6022  std::string opName = exprVal->getName().str();
6023  switch (toType->basicType) {
6024  case AtomicType::TYPE_BOOL:
6025  opName += "_to_bool";
6026  break;
6027  case AtomicType::TYPE_INT8:
6028  opName += "_to_int8";
6029  break;
6031  opName += "_to_uint8";
6032  break;
6034  opName += "_to_int16";
6035  break;
6037  opName += "_to_uint16";
6038  break;
6040  opName += "_to_int32";
6041  break;
6043  opName += "_to_uint32";
6044  break;
6046  opName += "_to_int64";
6047  break;
6049  opName += "_to_uint64";
6050  break;
6052  opName += "_to_float";
6053  break;
6055  opName += "_to_double";
6056  break;
6057  default:
6058  FATAL("Unimplemented");
6059  }
6060  const char *cOpName = opName.c_str();
6061 
6062  switch (toType->basicType) {
6063  case AtomicType::TYPE_FLOAT: {
6064  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::FloatType : LLVMTypes::FloatVectorType;
6065  switch (fromType->basicType) {
6066  case AtomicType::TYPE_BOOL:
6068  // If we have a bool vector of non-i1 elements, first
6069  // truncate down to a single bit.
6070  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6071  // And then do an unisgned int->float cast
6072  cast = ctx->CastInst(llvm::Instruction::UIToFP, // unsigned int
6073  exprVal, targetType, cOpName);
6074  break;
6075  case AtomicType::TYPE_INT8:
6079  cast = ctx->CastInst(llvm::Instruction::SIToFP, // signed int to float
6080  exprVal, targetType, cOpName);
6081  break;
6086  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6087  PerformanceWarning(pos, "Conversion from unsigned int to float is slow. "
6088  "Use \"int\" if possible");
6089  cast = ctx->CastInst(llvm::Instruction::UIToFP, // unsigned int to float
6090  exprVal, targetType, cOpName);
6091  break;
6093  // No-op cast.
6094  cast = exprVal;
6095  break;
6097  cast = ctx->FPCastInst(exprVal, targetType, cOpName);
6098  break;
6099  default:
6100  FATAL("unimplemented");
6101  }
6102  break;
6103  }
6104  case AtomicType::TYPE_DOUBLE: {
6105  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::DoubleType : LLVMTypes::DoubleVectorType;
6106  switch (fromType->basicType) {
6107  case AtomicType::TYPE_BOOL:
6109  // truncate bool vector values to i1s
6110  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6111  cast = ctx->CastInst(llvm::Instruction::UIToFP, // unsigned int to double
6112  exprVal, targetType, cOpName);
6113  break;
6114  case AtomicType::TYPE_INT8:
6118  cast = ctx->CastInst(llvm::Instruction::SIToFP, // signed int
6119  exprVal, targetType, cOpName);
6120  break;
6125  cast = ctx->CastInst(llvm::Instruction::UIToFP, // unsigned int
6126  exprVal, targetType, cOpName);
6127  break;
6129  cast = ctx->FPCastInst(exprVal, targetType, cOpName);
6130  break;
6132  cast = exprVal;
6133  break;
6134  default:
6135  FATAL("unimplemented");
6136  }
6137  break;
6138  }
6139  case AtomicType::TYPE_INT8: {
6140  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int8Type : LLVMTypes::Int8VectorType;
6141  switch (fromType->basicType) {
6142  case AtomicType::TYPE_BOOL:
6144  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6145  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6146  break;
6147  case AtomicType::TYPE_INT8:
6149  cast = exprVal;
6150  break;
6157  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6158  break;
6161  cast = ctx->CastInst(llvm::Instruction::FPToSI, // signed int
6162  exprVal, targetType, cOpName);
6163  break;
6164  default:
6165  FATAL("unimplemented");
6166  }
6167  break;
6168  }
6169  case AtomicType::TYPE_UINT8: {
6170  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int8Type : LLVMTypes::Int8VectorType;
6171  switch (fromType->basicType) {
6172  case AtomicType::TYPE_BOOL:
6174  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6175  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6176  break;
6177  case AtomicType::TYPE_INT8:
6179  cast = exprVal;
6180  break;
6187  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6188  break;
6190  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6191  PerformanceWarning(pos, "Conversion from float to unsigned int is slow. "
6192  "Use \"int\" if possible");
6193  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6194  exprVal, targetType, cOpName);
6195  break;
6197  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6198  PerformanceWarning(pos, "Conversion from double to unsigned int is slow. "
6199  "Use \"int\" if possible");
6200  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6201  exprVal, targetType, cOpName);
6202  break;
6203  default:
6204  FATAL("unimplemented");
6205  }
6206  break;
6207  }
6208  case AtomicType::TYPE_INT16: {
6209  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int16Type : LLVMTypes::Int16VectorType;
6210  switch (fromType->basicType) {
6211  case AtomicType::TYPE_BOOL:
6213  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6214  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6215  break;
6216  case AtomicType::TYPE_INT8:
6217  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6218  break;
6220  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6221  break;
6224  cast = exprVal;
6225  break;
6230  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6231  break;
6234  cast = ctx->CastInst(llvm::Instruction::FPToSI, // signed int
6235  exprVal, targetType, cOpName);
6236  break;
6237  default:
6238  FATAL("unimplemented");
6239  }
6240  break;
6241  }
6242  case AtomicType::TYPE_UINT16: {
6243  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int16Type : LLVMTypes::Int16VectorType;
6244  switch (fromType->basicType) {
6245  case AtomicType::TYPE_BOOL:
6247  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6248  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6249  break;
6250  case AtomicType::TYPE_INT8:
6251  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6252  break;
6254  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6255  break;
6258  cast = exprVal;
6259  break;
6261  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6262  PerformanceWarning(pos, "Conversion from float to unsigned int is slow. "
6263  "Use \"int\" if possible");
6264  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6265  exprVal, targetType, cOpName);
6266  break;
6271  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6272  break;
6274  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6275  PerformanceWarning(pos, "Conversion from double to unsigned int is slow. "
6276  "Use \"int\" if possible");
6277  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6278  exprVal, targetType, cOpName);
6279  break;
6280  default:
6281  FATAL("unimplemented");
6282  }
6283  break;
6284  }
6285  case AtomicType::TYPE_INT32: {
6286  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int32Type : LLVMTypes::Int32VectorType;
6287  switch (fromType->basicType) {
6288  case AtomicType::TYPE_BOOL:
6290  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6291  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6292  break;
6293  case AtomicType::TYPE_INT8:
6295  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6296  break;
6299  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6300  break;
6303  cast = exprVal;
6304  break;
6307  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6308  break;
6311  cast = ctx->CastInst(llvm::Instruction::FPToSI, // signed int
6312  exprVal, targetType, cOpName);
6313  break;
6314  default:
6315  FATAL("unimplemented");
6316  }
6317  break;
6318  }
6319  case AtomicType::TYPE_UINT32: {
6320  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int32Type : LLVMTypes::Int32VectorType;
6321  switch (fromType->basicType) {
6322  case AtomicType::TYPE_BOOL:
6324  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6325  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6326  break;
6327  case AtomicType::TYPE_INT8:
6329  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6330  break;
6333  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6334  break;
6337  cast = exprVal;
6338  break;
6340  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6341  PerformanceWarning(pos, "Conversion from float to unsigned int is slow. "
6342  "Use \"int\" if possible");
6343  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6344  exprVal, targetType, cOpName);
6345  break;
6348  cast = ctx->TruncInst(exprVal, targetType, cOpName);
6349  break;
6351  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6352  PerformanceWarning(pos, "Conversion from double to unsigned int is slow. "
6353  "Use \"int\" if possible");
6354  cast = ctx->CastInst(llvm::Instruction::FPToUI, // unsigned int
6355  exprVal, targetType, cOpName);
6356  break;
6357  default:
6358  FATAL("unimplemented");
6359  }
6360  break;
6361  }
6362  case AtomicType::TYPE_INT64: {
6363  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int64Type : LLVMTypes::Int64VectorType;
6364  switch (fromType->basicType) {
6365  case AtomicType::TYPE_BOOL:
6367  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6368  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6369  break;
6370  case AtomicType::TYPE_INT8:
6373  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6374  break;
6378  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6379  break;
6382  cast = exprVal;
6383  break;
6386  cast = ctx->CastInst(llvm::Instruction::FPToSI, // signed int
6387  exprVal, targetType, cOpName);
6388  break;
6389  default:
6390  FATAL("unimplemented");
6391  }
6392  break;
6393  }
6394  case AtomicType::TYPE_UINT64: {
6395  llvm::Type *targetType = fromType->IsUniformType() ? LLVMTypes::Int64Type : LLVMTypes::Int64VectorType;
6396  switch (fromType->basicType) {
6397  case AtomicType::TYPE_BOOL:
6399  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6400  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6401  break;
6402  case AtomicType::TYPE_INT8:
6405  cast = ctx->SExtInst(exprVal, targetType, cOpName);
6406  break;
6410  cast = ctx->ZExtInst(exprVal, targetType, cOpName);
6411  break;
6413  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6414  PerformanceWarning(pos, "Conversion from float to unsigned int64 is slow. "
6415  "Use \"int64\" if possible");
6416  cast = ctx->CastInst(llvm::Instruction::FPToUI, // signed int
6417  exprVal, targetType, cOpName);
6418  break;
6421  cast = exprVal;
6422  break;
6424  if (fromType->IsVaryingType() && g->target->getISA() != Target::GENERIC)
6425  PerformanceWarning(pos, "Conversion from double to unsigned int64 is slow. "
6426  "Use \"int64\" if possible");
6427  cast = ctx->CastInst(llvm::Instruction::FPToUI, // signed int
6428  exprVal, targetType, cOpName);
6429  break;
6430  default:
6431  FATAL("unimplemented");
6432  }
6433  break;
6434  }
6435  case AtomicType::TYPE_BOOL: {
6436  switch (fromType->basicType) {
6437  case AtomicType::TYPE_BOOL:
6439  // truncate bool vector values to i1s
6440  exprVal = ctx->TruncInst(exprVal, LLVMTypes::Int1VectorType, cOpName);
6441  }
6442  cast = exprVal;
6443  break;
6444  case AtomicType::TYPE_INT8:
6445  case AtomicType::TYPE_UINT8: {
6446  llvm::Value *zero =
6447  fromType->IsUniformType() ? (llvm::Value *)LLVMInt8(0) : (llvm::Value *)LLVMInt8Vector((int8_t)0);
6448  cast = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, exprVal, zero, cOpName);
6449  break;
6450  }
6452  case AtomicType::TYPE_UINT16: {
6453  llvm::Value *zero =
6454  fromType->IsUniformType() ? (llvm::Value *)LLVMInt16(0) : (llvm::Value *)LLVMInt16Vector((int16_t)0);
6455  cast = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, exprVal, zero, cOpName);
6456  break;
6457  }
6459  case AtomicType::TYPE_UINT32: {
6460  llvm::Value *zero =
6461  fromType->IsUniformType() ? (llvm::Value *)LLVMInt32(0) : (llvm::Value *)LLVMInt32Vector(0);
6462  cast = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, exprVal, zero, cOpName);
6463  break;
6464  }
6465  case AtomicType::TYPE_FLOAT: {
6466  llvm::Value *zero =
6467  fromType->IsUniformType() ? (llvm::Value *)LLVMFloat(0.f) : (llvm::Value *)LLVMFloatVector(0.f);
6468  cast = ctx->CmpInst(llvm::Instruction::FCmp, llvm::CmpInst::FCMP_ONE, exprVal, zero, cOpName);
6469  break;
6470  }
6472  case AtomicType::TYPE_UINT64: {
6473  llvm::Value *zero =
6474  fromType->IsUniformType() ? (llvm::Value *)LLVMInt64(0) : (llvm::Value *)LLVMInt64Vector((int64_t)0);
6475  cast = ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, exprVal, zero, cOpName);
6476  break;
6477  }
6478  case AtomicType::TYPE_DOUBLE: {
6479  llvm::Value *zero =
6480  fromType->IsUniformType() ? (llvm::Value *)LLVMDouble(0.) : (llvm::Value *)LLVMDoubleVector(0.);
6481  cast = ctx->CmpInst(llvm::Instruction::FCmp, llvm::CmpInst::FCMP_ONE, exprVal, zero, cOpName);
6482  break;
6483  }
6484  default:
6485  FATAL("unimplemented");
6486  }
6487 
6488  if (fromType->IsUniformType()) {
6490  // extend out to an bool as an i8/i16/i32 from the i1 here.
6491  // Then we'll turn that into a vector below, the way it
6492  // does for everyone else...
6493  cast = ctx->SExtInst(cast, LLVMTypes::BoolVectorType->getElementType(), LLVMGetName(cast, "to_i_bool"));
6494  }
6495  } else {
6496  // fromType->IsVaryingType())
6497  cast = ctx->I1VecToBoolVec(cast);
6498  }
6499  break;
6500  }
6501  default:
6502  FATAL("unimplemented");
6503  }
6504 
6505  // If we also want to go from uniform to varying, replicate out the
6506  // value across the vector elements..
6507  if (toType->IsVaryingType() && fromType->IsUniformType())
6508  return ctx->SmearUniform(cast);
6509  else
6510  return cast;
6511 }
6512 
6513 // FIXME: fold this into the FunctionEmitContext::SmearUniform() method?
6514 
6515 /** Converts the given value of the given type to be the varying
6516  equivalent, returning the resulting value.
6517  */
6518 static llvm::Value *lUniformValueToVarying(FunctionEmitContext *ctx, llvm::Value *value, const Type *type,
6519  SourcePos pos) {
6520  // nothing to do if it's already varying
6521  if (type->IsVaryingType())
6522  return value;
6523 
6524  // for structs/arrays/vectors, just recursively make their elements
6525  // varying (if needed) and populate the return value.
6526  const CollectionType *collectionType = CastType<CollectionType>(type);
6527  if (collectionType != NULL) {
6528  llvm::Type *llvmType = type->GetAsVaryingType()->LLVMStorageType(g->ctx);
6529  llvm::Value *retValue = llvm::UndefValue::get(llvmType);
6530 
6531  const StructType *structType = CastType<StructType>(type->GetAsVaryingType());
6532 
6533  for (int i = 0; i < collectionType->GetElementCount(); ++i) {
6534  llvm::Value *v = ctx->ExtractInst(value, i, "get_element");
6535  // If struct has "bound uniform" member, we don't need to cast it to varying
6536  if (!(structType != NULL && structType->GetElementType(i)->IsUniformType())) {
6537  const Type *elemType = collectionType->GetElementType(i);
6538  // If member is a uniform bool, it needs to be truncated to i1 since
6539  // uniform bool in IR is i1 and i8 in struct
6540  // Consider switching to just a broadcast for bool
6541  if ((elemType->IsBoolType()) && (CastType<AtomicType>(elemType) != NULL)) {
6542  v = ctx->TruncInst(v, LLVMTypes::BoolType);
6543  }
6544  v = lUniformValueToVarying(ctx, v, elemType, pos);
6545  // If the extracted element if bool and varying needs to be
6546  // converted back to i8 vector to insert into varying struct.
6547  if ((elemType->IsBoolType()) && (CastType<AtomicType>(elemType) != NULL)) {
6548  v = ctx->SwitchBoolSize(v, v->getType(), LLVMTypes::BoolVectorStorageType);
6549  }
6550  }
6551  retValue = ctx->InsertInst(retValue, v, i, "set_element");
6552  }
6553  return retValue;
6554  }
6555 
6556  // Otherwise we must have a uniform atomic or pointer type, so smear
6557  // its value across the vector lanes.
6558  if (CastType<AtomicType>(type)) {
6559  return lTypeConvAtomic(ctx, value, CastType<AtomicType>(type->GetAsVaryingType()), CastType<AtomicType>(type),
6560  pos);
6561  }
6562 
6563  Assert(CastType<PointerType>(type) != NULL);
6564  return ctx->SmearUniform(value);
6565 }
6566 
6568  if (!expr)
6569  return NULL;
6570 
6571  ctx->SetDebugPos(pos);
6572  const Type *toType = GetType(), *fromType = expr->GetType();
6573  if (toType == NULL || fromType == NULL) {
6574  AssertPos(pos, m->errorCount > 0);
6575  return NULL;
6576  }
6577 
6578  if (toType->IsVoidType()) {
6579  // emit the code for the expression in case it has side-effects but
6580  // then we're done.
6581  (void)expr->GetValue(ctx);
6582  return NULL;
6583  }
6584 
6585  const PointerType *fromPointerType = CastType<PointerType>(fromType);
6586  const PointerType *toPointerType = CastType<PointerType>(toType);
6587  const ArrayType *toArrayType = CastType<ArrayType>(toType);
6588  const ArrayType *fromArrayType = CastType<ArrayType>(fromType);
6589  if (fromPointerType != NULL) {
6590  if (toArrayType != NULL) {
6591  return expr->GetValue(ctx);
6592  } else if (toPointerType != NULL) {
6593  llvm::Value *value = expr->GetValue(ctx);
6594  if (value == NULL)
6595  return NULL;
6596 
6597  if (fromPointerType->IsSlice() == false && toPointerType->IsSlice() == true) {
6598  // Convert from a non-slice pointer to a slice pointer by
6599  // creating a slice pointer structure with zero offsets.
6600  if (fromPointerType->IsUniformType())
6601  value = ctx->MakeSlicePointer(value, LLVMInt32(0));
6602  else
6603  value = ctx->MakeSlicePointer(value, LLVMInt32Vector(0));
6604 
6605  // FIXME: avoid error from unnecessary bitcast when all we
6606  // need to do is the slice conversion and don't need to
6607  // also do unif->varying conversions. But this is really
6608  // ugly logic.
6609  if (value->getType() == toType->LLVMType(g->ctx))
6610  return value;
6611  }
6612 
6613  if (fromType->IsUniformType() && toType->IsUniformType())
6614  // bitcast to the actual pointer type
6615  return ctx->BitCastInst(value, toType->LLVMType(g->ctx));
6616  else if (fromType->IsVaryingType() && toType->IsVaryingType()) {
6617  // both are vectors of ints already, nothing to do at the IR
6618  // level
6619  return value;
6620  } else {
6621  // Uniform -> varying pointer conversion
6622  AssertPos(pos, fromType->IsUniformType() && toType->IsVaryingType());
6623  if (fromPointerType->IsSlice()) {
6624  // For slice pointers, we need to smear out both the
6625  // pointer and the offset vector
6626  AssertPos(pos, toPointerType->IsSlice());
6627  llvm::Value *ptr = ctx->ExtractInst(value, 0);
6628  llvm::Value *offset = ctx->ExtractInst(value, 1);
6629  ptr = ctx->PtrToIntInst(ptr);
6630  ptr = ctx->SmearUniform(ptr);
6631  offset = ctx->SmearUniform(offset);
6632  return ctx->MakeSlicePointer(ptr, offset);
6633  } else {
6634  // Otherwise we just bitcast it to an int and smear it
6635  // out to a vector
6636  value = ctx->PtrToIntInst(value);
6637  return ctx->SmearUniform(value);
6638  }
6639  }
6640  } else {
6641  AssertPos(pos, CastType<AtomicType>(toType) != NULL);
6642  if (toType->IsBoolType()) {
6643  // convert pointer to bool
6644  llvm::Type *lfu = fromType->GetAsUniformType()->LLVMType(g->ctx);
6645  llvm::PointerType *llvmFromUnifType = llvm::dyn_cast<llvm::PointerType>(lfu);
6646 
6647  llvm::Value *nullPtrValue = llvm::ConstantPointerNull::get(llvmFromUnifType);
6648  if (fromType->IsVaryingType())
6649  nullPtrValue = ctx->SmearUniform(nullPtrValue);
6650 
6651  llvm::Value *exprVal = expr->GetValue(ctx);
6652  llvm::Value *cmp =
6653  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, exprVal, nullPtrValue, "ptr_ne_NULL");
6654 
6655  if (toType->IsVaryingType()) {
6656  if (fromType->IsUniformType())
6657  cmp = ctx->SmearUniform(cmp);
6658  cmp = ctx->I1VecToBoolVec(cmp);
6659  }
6660 
6661  return cmp;
6662  } else {
6663  // ptr -> int
6664  llvm::Value *value = expr->GetValue(ctx);
6665  if (value == NULL)
6666  return NULL;
6667 
6668  if (toType->IsVaryingType() && fromType->IsUniformType())
6669  value = ctx->SmearUniform(value);
6670 
6671  llvm::Type *llvmToType = toType->LLVMType(g->ctx);
6672  if (llvmToType == NULL)
6673  return NULL;
6674  return ctx->PtrToIntInst(value, llvmToType, "ptr_typecast");
6675  }
6676  }
6677  }
6678 
6679  if (Type::EqualIgnoringConst(toType, fromType))
6680  // There's nothing to do, just return the value. (LLVM's type
6681  // system doesn't worry about constiness.)
6682  return expr->GetValue(ctx);
6683 
6684  if (fromArrayType != NULL && toPointerType != NULL) {
6685  // implicit array to pointer to first element
6686  Expr *arrayAsPtr = lArrayToPointer(expr);
6687  if (Type::EqualIgnoringConst(arrayAsPtr->GetType(), toPointerType) == false) {
6688  AssertPos(pos,
6689  PointerType::IsVoidPointer(toPointerType) ||
6690  Type::EqualIgnoringConst(arrayAsPtr->GetType()->GetAsVaryingType(), toPointerType) == true);
6691  arrayAsPtr = new TypeCastExpr(toPointerType, arrayAsPtr, pos);
6692  arrayAsPtr = ::TypeCheck(arrayAsPtr);
6693  AssertPos(pos, arrayAsPtr != NULL);
6694  arrayAsPtr = ::Optimize(arrayAsPtr);
6695  AssertPos(pos, arrayAsPtr != NULL);
6696  }
6697  AssertPos(pos, Type::EqualIgnoringConst(arrayAsPtr->GetType(), toPointerType));
6698  return arrayAsPtr->GetValue(ctx);
6699  }
6700 
6701  // This also should be caught during typechecking
6702  AssertPos(pos, !(toType->IsUniformType() && fromType->IsVaryingType()));
6703 
6704  if (toArrayType != NULL && fromArrayType != NULL) {
6705  // cast array pointer from [n x foo] to [0 x foo] if needed to be able
6706  // to pass to a function that takes an unsized array as a parameter
6707  if (toArrayType->GetElementCount() != 0 && (toArrayType->GetElementCount() != fromArrayType->GetElementCount()))
6708  Warning(pos, "Type-converting array of length %d to length %d", fromArrayType->GetElementCount(),
6709  toArrayType->GetElementCount());
6710  AssertPos(pos, Type::EqualIgnoringConst(toArrayType->GetBaseType(), fromArrayType->GetBaseType()));
6711  llvm::Value *v = expr->GetValue(ctx);
6712  llvm::Type *ptype = toType->LLVMType(g->ctx);
6713  return ctx->BitCastInst(v, ptype); //, "array_cast_0size");
6714  }
6715 
6716  const ReferenceType *toReference = CastType<ReferenceType>(toType);
6717  const ReferenceType *fromReference = CastType<ReferenceType>(fromType);
6718  if (toReference && fromReference) {
6719  const Type *toTarget = toReference->GetReferenceTarget();
6720  const Type *fromTarget = fromReference->GetReferenceTarget();
6721 
6722  const ArrayType *toArray = CastType<ArrayType>(toTarget);
6723  const ArrayType *fromArray = CastType<ArrayType>(fromTarget);
6724  if (toArray && fromArray) {
6725  // cast array pointer from [n x foo] to [0 x foo] if needed to be able
6726  // to pass to a function that takes an unsized array as a parameter
6727  if (toArray->GetElementCount() != 0 && (toArray->GetElementCount() != fromArray->GetElementCount()))
6728  Warning(pos, "Type-converting array of length %d to length %d", fromArray->GetElementCount(),
6729  toArray->GetElementCount());
6730  AssertPos(pos, Type::EqualIgnoringConst(toArray->GetBaseType(), fromArray->GetBaseType()));
6731  llvm::Value *v = expr->GetValue(ctx);
6732  llvm::Type *ptype = toType->LLVMType(g->ctx);
6733  return ctx->BitCastInst(v, ptype); //, "array_cast_0size");
6734  }
6735 
6736  // Just bitcast it. See Issue #721
6737  llvm::Value *value = expr->GetValue(ctx);
6738  return ctx->BitCastInst(value, toType->LLVMType(g->ctx), "refcast");
6739  }
6740 
6741  const StructType *toStruct = CastType<StructType>(toType);
6742  const StructType *fromStruct = CastType<StructType>(fromType);
6743  if (toStruct && fromStruct) {
6744  // The only legal type conversions for structs are to go from a
6745  // uniform to a varying instance of the same struct type.
6746  AssertPos(pos, toStruct->IsVaryingType() && fromStruct->IsUniformType() &&
6747  Type::EqualIgnoringConst(toStruct, fromStruct->GetAsVaryingType()));
6748 
6749  llvm::Value *origValue = expr->GetValue(ctx);
6750  if (!origValue)
6751  return NULL;
6752  return lUniformValueToVarying(ctx, origValue, fromType, pos);
6753  }
6754 
6755  const VectorType *toVector = CastType<VectorType>(toType);
6756  const VectorType *fromVector = CastType<VectorType>(fromType);
6757  if (toVector && fromVector) {
6758  // this should be caught during typechecking
6759  AssertPos(pos, toVector->GetElementCount() == fromVector->GetElementCount());
6760 
6761  llvm::Value *exprVal = expr->GetValue(ctx);
6762  if (!exprVal)
6763  return NULL;
6764 
6765  // Emit instructions to do type conversion of each of the elements
6766  // of the vector.
6767  // FIXME: since uniform vectors are represented as
6768  // llvm::VectorTypes, we should just be able to issue the
6769  // corresponding vector type convert, which should be more
6770  // efficient by avoiding serialization!
6771  llvm::Value *cast = llvm::UndefValue::get(toType->LLVMStorageType(g->ctx));
6772  for (int i = 0; i < toVector->GetElementCount(); ++i) {
6773  llvm::Value *ei = ctx->ExtractInst(exprVal, i);
6774  llvm::Value *conv = lTypeConvAtomic(ctx, ei, toVector->GetElementType(), fromVector->GetElementType(), pos);
6775  if (!conv)
6776  return NULL;
6777  if ((toVector->GetElementType()->IsBoolType()) &&
6778  (CastType<AtomicType>(toVector->GetElementType()) != NULL)) {
6779  conv = ctx->SwitchBoolSize(conv, conv->getType(), toVector->GetElementType()->LLVMStorageType(g->ctx));
6780  }
6781 
6782  cast = ctx->InsertInst(cast, conv, i);
6783  }
6784  return cast;
6785  }
6786 
6787  llvm::Value *exprVal = expr->GetValue(ctx);
6788  if (!exprVal)
6789  return NULL;
6790 
6791  const EnumType *fromEnum = CastType<EnumType>(fromType);
6792  const EnumType *toEnum = CastType<EnumType>(toType);
6793  if (fromEnum)
6794  // treat it as an uint32 type for the below and all will be good.
6796  if (toEnum)
6797  // treat it as an uint32 type for the below and all will be good.
6799 
6800  const AtomicType *fromAtomic = CastType<AtomicType>(fromType);
6801  // at this point, coming from an atomic type is all that's left...
6802  AssertPos(pos, fromAtomic != NULL);
6803 
6804  if (toVector) {
6805  // scalar -> short vector conversion
6806  llvm::Value *conv = lTypeConvAtomic(ctx, exprVal, toVector->GetElementType(), fromAtomic, pos);
6807  if (!conv)
6808  return NULL;
6809 
6810  llvm::Value *cast = NULL;
6811  llvm::Type *toTypeLLVM = toType->LLVMStorageType(g->ctx);
6812  if (llvm::isa<llvm::VectorType>(toTypeLLVM)) {
6813  // Example uniform float => uniform float<3>
6814  cast = ctx->BroadcastValue(conv, toTypeLLVM);
6815  } else if (llvm::isa<llvm::ArrayType>(toTypeLLVM)) {
6816  // Example varying float => varying float<3>
6817  cast = llvm::UndefValue::get(toType->LLVMStorageType(g->ctx));
6818  for (int i = 0; i < toVector->GetElementCount(); ++i) {
6819  if ((toVector->GetElementType()->IsBoolType()) &&
6820  (CastType<AtomicType>(toVector->GetElementType()) != NULL)) {
6821  conv =
6822  ctx->SwitchBoolSize(conv, conv->getType(), toVector->GetElementType()->LLVMStorageType(g->ctx));
6823  }
6824  // Here's InsertInst produces InsertValueInst.
6825  cast = ctx->InsertInst(cast, conv, i);
6826  }
6827  } else {
6828  FATAL("TypeCastExpr::GetValue: problem with cast");
6829  }
6830 
6831  return cast;
6832  } else if (toPointerType != NULL) {
6833  // int -> ptr
6834  if (toType->IsVaryingType() && fromType->IsUniformType())
6835  exprVal = ctx->SmearUniform(exprVal);
6836 
6837  llvm::Type *llvmToType = toType->LLVMType(g->ctx);
6838  if (llvmToType == NULL)
6839  return NULL;
6840 
6841  return ctx->IntToPtrInst(exprVal, llvmToType, "int_to_ptr");
6842  } else {
6843  const AtomicType *toAtomic = CastType<AtomicType>(toType);
6844  // typechecking should ensure this is the case
6845  AssertPos(pos, toAtomic != NULL);
6846 
6847  return lTypeConvAtomic(ctx, exprVal, toAtomic, fromAtomic, pos);
6848  }
6849 }
6850 
6852  if (GetLValueType() != NULL) {
6853  return GetValue(ctx);
6854  } else {
6855  return NULL;
6856  }
6857 }
6858 
6859 const Type *TypeCastExpr::GetType() const {
6860  // Here we try to resolve situation where (base_type) can be treated as
6861  // (uniform base_type) of (varying base_type). This is a part of function
6862  // TypeCastExpr::TypeCheck. After implementation of operators we
6863  // have to have this functionality here.
6864  const Type *toType = type, *fromType = expr->GetType();
6865  if (toType == NULL || fromType == NULL)
6866  return NULL;
6867  if (toType->HasUnboundVariability()) {
6868  if (fromType->IsUniformType()) {
6870  } else {
6872  }
6873  }
6874  AssertPos(pos, toType->HasUnboundVariability() == false);
6875  return toType;
6876 }
6877 
6879  AssertPos(pos, type->HasUnboundVariability() == false);
6880  if (CastType<PointerType>(GetType()) != NULL) {
6881  return type;
6882  } else {
6883  return NULL;
6884  }
6885 }
6886 
6887 static const Type *lDeconstifyType(const Type *t) {
6888  const PointerType *pt = CastType<PointerType>(t);
6889  if (pt != NULL)
6890  return new PointerType(lDeconstifyType(pt->GetBaseType()), pt->GetVariability(), false);
6891  else
6892  return t->GetAsNonConstType();
6893 }
6894 
6896  if (expr == NULL)
6897  return NULL;
6898 
6899  const Type *toType = type, *fromType = expr->GetType();
6900  if (toType == NULL || fromType == NULL)
6901  return NULL;
6902 
6903  if (toType->HasUnboundVariability() && fromType->IsUniformType()) {
6904  TypeCastExpr *tce = new TypeCastExpr(toType->GetAsUniformType(), expr, pos);
6905  return ::TypeCheck(tce);
6906  }
6908 
6909  fromType = lDeconstifyType(fromType);
6910  toType = lDeconstifyType(toType);
6911 
6912  // Anything can be cast to void...
6913  if (toType->IsVoidType())
6914  return this;
6915 
6916  if (fromType->IsVoidType() || (fromType->IsVaryingType() && toType->IsUniformType())) {
6917  Error(pos, "Can't type cast from type \"%s\" to type \"%s\"", fromType->GetString().c_str(),
6918  toType->GetString().c_str());
6919  return NULL;
6920  }
6921 
6922  // First some special cases that we allow only with an explicit type cast
6923  const PointerType *fromPtr = CastType<PointerType>(fromType);
6924  const PointerType *toPtr = CastType<PointerType>(toType);
6925  if (fromPtr != NULL && toPtr != NULL)
6926  // allow explicit typecasts between any two different pointer types
6927  return this;
6928 
6929  const ReferenceType *fromRef = CastType<ReferenceType>(fromType);
6930  const ReferenceType *toRef = CastType<ReferenceType>(toType);
6931  if (fromRef != NULL && toRef != NULL) {
6932  // allow explicit typecasts between any two different reference types
6933  // Issues #721
6934  return this;
6935  }
6936 
6937  const AtomicType *fromAtomic = CastType<AtomicType>(fromType);
6938  const AtomicType *toAtomic = CastType<AtomicType>(toType);
6939  const EnumType *fromEnum = CastType<EnumType>(fromType);
6940  const EnumType *toEnum = CastType<EnumType>(toType);
6941  if ((fromAtomic || fromEnum) && (toAtomic || toEnum))
6942  // Allow explicit casts between all of these
6943  return this;
6944 
6945  // ptr -> int type casts
6946  if (fromPtr != NULL && toAtomic != NULL && toAtomic->IsIntType()) {
6947  bool safeCast =
6948  (toAtomic->basicType == AtomicType::TYPE_INT64 || toAtomic->basicType == AtomicType::TYPE_UINT64);
6949  if (g->target->is32Bit())
6950  safeCast |=
6951  (toAtomic->basicType == AtomicType::TYPE_INT32 || toAtomic->basicType == AtomicType::TYPE_UINT32);
6952  if (safeCast == false)
6953  Warning(pos,
6954  "Pointer type cast of type \"%s\" to integer type "
6955  "\"%s\" may lose information.",
6956  fromType->GetString().c_str(), toType->GetString().c_str());
6957  return this;
6958  }
6959 
6960  // int -> ptr
6961  if (fromAtomic != NULL && fromAtomic->IsIntType() && toPtr != NULL)
6962  return this;
6963 
6964  // And otherwise see if it's one of the conversions allowed to happen
6965  // implicitly.
6966  Expr *e = TypeConvertExpr(expr, toType, "type cast expression");
6967  if (e == NULL)
6968  return NULL;
6969  else
6970  return e;
6971 }
6972 
6974  ConstExpr *constExpr = llvm::dyn_cast<ConstExpr>(expr);
6975  if (constExpr == NULL)
6976  // We can't do anything if this isn't a const expr
6977  return this;
6978 
6979  const Type *toType = GetType();
6980  const AtomicType *toAtomic = CastType<AtomicType>(toType);
6981  const EnumType *toEnum = CastType<EnumType>(toType);
6982  // If we're not casting to an atomic or enum type, we can't do anything
6983  // here, since ConstExprs can only represent those two types. (So
6984  // e.g. we're casting from an int to an int<4>.)
6985  if (toAtomic == NULL && toEnum == NULL)
6986  return this;
6987 
6988  bool forceVarying = toType->IsVaryingType();
6989 
6990  // All of the type conversion smarts we need is already in the
6991  // ConstExpr::GetValues(), etc., methods, so we just need to call the
6992  // appropriate one for the type that this cast is converting to.
6993  AtomicType::BasicType basicType = toAtomic ? toAtomic->basicType : AtomicType::TYPE_UINT32;
6994  switch (basicType) {
6995  case AtomicType::TYPE_BOOL: {
6996  bool bv[ISPC_MAX_NVEC];
6997  constExpr->GetValues(bv, forceVarying);
6998  return new ConstExpr(toType, bv, pos);
6999  }
7000  case AtomicType::TYPE_INT8: {
7001  int8_t iv[ISPC_MAX_NVEC];
7002  constExpr->GetValues(iv, forceVarying);
7003  return new ConstExpr(toType, iv, pos);
7004  }
7005  case AtomicType::TYPE_UINT8: {
7006  uint8_t uv[ISPC_MAX_NVEC];
7007  constExpr->GetValues(uv, forceVarying);
7008  return new ConstExpr(toType, uv, pos);
7009  }
7010  case AtomicType::TYPE_INT16: {
7011  int16_t iv[ISPC_MAX_NVEC];
7012  constExpr->GetValues(iv, forceVarying);
7013  return new ConstExpr(toType, iv, pos);
7014  }
7015  case AtomicType::TYPE_UINT16: {
7016  uint16_t uv[ISPC_MAX_NVEC];
7017  constExpr->GetValues(uv, forceVarying);
7018  return new ConstExpr(toType, uv, pos);
7019  }
7020  case AtomicType::TYPE_INT32: {
7021  int32_t iv[ISPC_MAX_NVEC];
7022  constExpr->GetValues(iv, forceVarying);
7023  return new ConstExpr(toType, iv, pos);
7024  }
7025  case AtomicType::TYPE_UINT32: {
7026  uint32_t uv[ISPC_MAX_NVEC];
7027  constExpr->GetValues(uv, forceVarying);
7028  return new ConstExpr(toType, uv, pos);
7029  }
7030  case AtomicType::TYPE_FLOAT: {
7031  float fv[ISPC_MAX_NVEC];
7032  constExpr->GetValues(fv, forceVarying);
7033  return new ConstExpr(toType, fv, pos);
7034  }
7035  case AtomicType::TYPE_INT64: {
7036  int64_t iv[ISPC_MAX_NVEC];
7037  constExpr->GetValues(iv, forceVarying);
7038  return new ConstExpr(toType, iv, pos);
7039  }
7040  case AtomicType::TYPE_UINT64: {
7041  uint64_t uv[ISPC_MAX_NVEC];
7042  constExpr->GetValues(uv, forceVarying);
7043  return new ConstExpr(toType, uv, pos);
7044  }
7045  case AtomicType::TYPE_DOUBLE: {
7046  double dv[ISPC_MAX_NVEC];
7047  constExpr->GetValues(dv, forceVarying);
7048  return new ConstExpr(toType, dv, pos);
7049  }
7050  default:
7051  FATAL("unimplemented");
7052  }
7053  return this;
7054 }
7055 
7057  if (llvm::dyn_cast<ConstExpr>(expr) != NULL)
7058  return 0;
7059 
7060  // FIXME: return COST_TYPECAST_COMPLEX when appropriate
7061  return COST_TYPECAST_SIMPLE;
7062 }
7063 
7064 void TypeCastExpr::Print() const {
7065  printf("[%s] type cast (", GetType()->GetString().c_str());
7066  expr->Print();
7067  printf(")");
7068  pos.Print();
7069 }
7070 
7072 
7073 static llvm::Constant *lConvertPointerConstant(llvm::Constant *c, const Type *constType) {
7074  if (c == NULL || constType->IsUniformType())
7075  return c;
7076 
7077  // Handle conversion to int and then to vector of int or array of int
7078  // (for varying and soa types, respectively)
7079  llvm::Constant *intPtr = llvm::ConstantExpr::getPtrToInt(c, LLVMTypes::PointerIntType);
7080  Assert(constType->IsVaryingType() || constType->IsSOAType());
7081  int count = constType->IsVaryingType() ? g->target->getVectorWidth() : constType->GetSOAWidth();
7082 
7083  std::vector<llvm::Constant *> smear;
7084  for (int i = 0; i < count; ++i)
7085  smear.push_back(intPtr);
7086 
7087  if (constType->IsVaryingType())
7088  return llvm::ConstantVector::get(smear);
7089  else {
7090  llvm::ArrayType *at = llvm::ArrayType::get(LLVMTypes::PointerIntType, count);
7091  return llvm::ConstantArray::get(at, smear);
7092  }
7093 }
7094 
7095 std::pair<llvm::Constant *, bool> TypeCastExpr::GetConstant(const Type *constType) const {
7096  // We don't need to worry about most the basic cases where the type
7097  // cast can resolve to a constant here, since the
7098  // TypeCastExpr::Optimize() method generally ends up doing the type
7099  // conversion and returning a ConstExpr, which in turn will have its
7100  // GetConstant() method called. However, because ConstExpr currently
7101  // can't represent pointer values, we have to handle a few cases
7102  // related to pointers here:
7103  //
7104  // 1. Null pointer (NULL, 0) valued initializers
7105  // 2. Converting function types to pointer-to-function types
7106  // 3. And converting these from uniform to the varying/soa equivalents.
7107  //
7108 
7109  if ((CastType<PointerType>(constType) == NULL) && (llvm::dyn_cast<SizeOfExpr>(expr) == NULL))
7110  return std::pair<llvm::Constant *, bool>(NULL, false);
7111 
7112  llvm::Value *ptr = NULL;
7113  if (GetBaseSymbol())
7114  ptr = GetBaseSymbol()->storagePtr;
7115 
7116  if (ptr && llvm::dyn_cast<llvm::GlobalVariable>(ptr)) {
7117  if (CastType<ArrayType>(expr->GetType())) {
7118  if (llvm::Constant *c = llvm::dyn_cast<llvm::Constant>(ptr)) {
7119  llvm::Value *offsets[2] = {LLVMInt32(0), LLVMInt32(0)};
7120  llvm::ArrayRef<llvm::Value *> arrayRef(&offsets[0], &offsets[2]);
7121  llvm::Value *resultPtr = llvm::ConstantExpr::getGetElementPtr(PTYPE(c), c, arrayRef);
7122  if (resultPtr->getType() == constType->LLVMType(g->ctx)) {
7123  llvm::Constant *ret = llvm::dyn_cast<llvm::Constant>(resultPtr);
7124  return std::pair<llvm::Constant *, bool>(ret, false);
7125  }
7126  }
7127  }
7128  }
7129 
7130  std::pair<llvm::Constant *, bool> cPair = expr->GetConstant(constType->GetAsUniformType());
7131  llvm::Constant *c = cPair.first;
7132  return std::pair<llvm::Constant *, bool>(lConvertPointerConstant(c, constType), cPair.second);
7133 }
7134 
7135 ///////////////////////////////////////////////////////////////////////////
7136 // ReferenceExpr
7137 
7139 
7141  ctx->SetDebugPos(pos);
7142  if (expr == NULL) {
7143  AssertPos(pos, m->errorCount > 0);
7144  return NULL;
7145  }
7146 
7147  llvm::Value *value = expr->GetLValue(ctx);
7148  if (value != NULL)
7149  return value;
7150 
7151  // value is NULL if the expression is a temporary; in this case, we'll
7152  // allocate storage for it so that we can return the pointer to that...
7153  const Type *type;
7154  llvm::Type *llvmType;
7155  if ((type = expr->GetType()) == NULL || (llvmType = type->LLVMType(g->ctx)) == NULL) {
7156  AssertPos(pos, m->errorCount > 0);
7157  return NULL;
7158  }
7159 
7160  value = expr->GetValue(ctx);
7161  if (value == NULL) {
7162  AssertPos(pos, m->errorCount > 0);
7163  return NULL;
7164  }
7165 
7166  llvm::Value *ptr = ctx->AllocaInst(type);
7167  ctx->StoreInst(value, ptr, type);
7168  return ptr;
7169 }
7170 
7172 
7174  if (!expr)
7175  return NULL;
7176 
7177  const Type *type = expr->GetType();
7178  if (!type)
7179  return NULL;
7180 
7181  return new ReferenceType(type);
7182 }
7183 
7185  if (!expr)
7186  return NULL;
7187 
7188  const Type *type = expr->GetType();
7189  if (!type)
7190  return NULL;
7191 
7192  return PointerType::GetUniform(type);
7193 }
7194 
7196  if (expr == NULL)
7197  return NULL;
7198  return this;
7199 }
7200 
7202  if (expr == NULL)
7203  return NULL;
7204  return this;
7205 }
7206 
7207 int ReferenceExpr::EstimateCost() const { return 0; }
7208 
7209 void ReferenceExpr::Print() const {
7210  if (expr == NULL || GetType() == NULL)
7211  return;
7212 
7213  printf("[%s] &(", GetType()->GetString().c_str());
7214  expr->Print();
7215  printf(")");
7216  pos.Print();
7217 }
7218 
7219 ///////////////////////////////////////////////////////////////////////////
7220 // DerefExpr
7221 
7222 DerefExpr::DerefExpr(Expr *e, SourcePos p, unsigned scid) : Expr(p, scid) { expr = e; }
7223 
7224 llvm::Value *DerefExpr::GetValue(FunctionEmitContext *ctx) const {
7225  if (expr == NULL)
7226  return NULL;
7227  llvm::Value *ptr = expr->GetValue(ctx);
7228  if (ptr == NULL)
7229  return NULL;
7230  const Type *type = expr->GetType();
7231  if (type == NULL)
7232  return NULL;
7233 
7234  if (lVaryingStructHasUniformMember(type, pos))
7235  return NULL;
7236 
7237  // If dealing with 'varying * varying' add required offsets.
7238  ptr = lAddVaryingOffsetsIfNeeded(ctx, ptr, type);
7239 
7240  Symbol *baseSym = expr->GetBaseSymbol();
7241  llvm::Value *mask = baseSym ? lMaskForSymbol(baseSym, ctx) : ctx->GetFullMask();
7242 
7243  ctx->SetDebugPos(pos);
7244  return ctx->LoadInst(ptr, mask, type);
7245 }
7246 
7247 llvm::Value *DerefExpr::GetLValue(FunctionEmitContext *ctx) const {
7248  if (expr == NULL)
7249  return NULL;
7250  return expr->GetValue(ctx);
7251 }
7252 
7254  if (expr == NULL)
7255  return NULL;
7256  return expr->GetType();
7257 }
7258 
7259 Symbol *DerefExpr::GetBaseSymbol() const { return expr ? expr->GetBaseSymbol() : NULL; }
7260 
7262  if (expr == NULL)
7263  return NULL;
7264  return this;
7265 }
7266 
7267 ///////////////////////////////////////////////////////////////////////////
7268 // PtrDerefExpr
7269 
7271 
7272 const Type *PtrDerefExpr::GetType() const {
7273  const Type *type;
7274  if (expr == NULL || (type = expr->GetType()) == NULL) {
7275  AssertPos(pos, m->errorCount > 0);
7276  return NULL;
7277  }
7278  AssertPos(pos, CastType<PointerType>(type) != NULL);
7279 
7280  if (type->IsUniformType())
7281  return type->GetBaseType();
7282  else
7283  return type->GetBaseType()->GetAsVaryingType();
7284 }
7285 
7287  const Type *type;
7288  if (expr == NULL || (type = expr->GetType()) == NULL) {
7289  AssertPos(pos, m->errorCount > 0);
7290  return NULL;
7291  }
7292 
7293  if (const PointerType *pt = CastType<PointerType>(type)) {
7294  if (pt->GetBaseType()->IsVoidType()) {
7295  Error(pos, "Illegal to dereference void pointer type \"%s\".", type->GetString().c_str());
7296  return NULL;
7297  }
7298  } else {
7299  Error(pos, "Illegal to dereference non-pointer type \"%s\".", type->GetString().c_str());
7300  return NULL;
7301  }
7302 
7303  return this;
7304 }
7305 
7307  const Type *type;
7308  if (expr == NULL || (type = expr->GetType()) == NULL) {
7309  AssertPos(pos, m->errorCount > 0);
7310  return 0;
7311  }
7312 
7313  if (type->IsVaryingType())
7314  // Be pessimistic; some of these will later be optimized into
7315  // vector loads/stores..
7316  return COST_GATHER + COST_DEREF;
7317  else
7318  return COST_DEREF;
7319 }
7320 
7321 void PtrDerefExpr::Print() const {
7322  if (expr == NULL || GetType() == NULL)
7323  return;
7324 
7325  printf("[%s] *(", GetType()->GetString().c_str());
7326  expr->Print();
7327  printf(")");
7328  pos.Print();
7329 }
7330 
7331 ///////////////////////////////////////////////////////////////////////////
7332 // RefDerefExpr
7333 
7335 
7336 const Type *RefDerefExpr::GetType() const {
7337  const Type *type;
7338  if (expr == NULL || (type = expr->GetType()) == NULL) {
7339  AssertPos(pos, m->errorCount > 0);
7340  return NULL;
7341  }
7342 
7343  AssertPos(pos, CastType<ReferenceType>(type) != NULL);
7344  return type->GetReferenceTarget();
7345 }
7346 
7348  const Type *type;
7349  if (expr == NULL || (type = expr->GetType()) == NULL) {
7350  AssertPos(pos, m->errorCount > 0);
7351  return NULL;
7352  }
7353 
7354  // We only create RefDerefExprs internally for references in
7355  // expressions, so we should never create one with a non-reference
7356  // expression...
7357  AssertPos(pos, CastType<ReferenceType>(type) != NULL);
7358 
7359  return this;
7360 }
7361 
7363  if (expr == NULL)
7364  return 0;
7365 
7366  return COST_DEREF;
7367 }
7368 
7369 void RefDerefExpr::Print() const {
7370  if (expr == NULL || GetType() == NULL)
7371  return;
7372 
7373  printf("[%s] deref-reference (", GetType()->GetString().c_str());
7374  expr->Print();
7375  printf(")");
7376  pos.Print();
7377 }
7378 
7379 ///////////////////////////////////////////////////////////////////////////
7380 // AddressOfExpr
7381 
7383 
7385  ctx->SetDebugPos(pos);
7386  if (expr == NULL)
7387  return NULL;
7388 
7389  const Type *exprType = expr->GetType();
7390  if (CastType<ReferenceType>(exprType) != NULL || CastType<FunctionType>(exprType) != NULL)
7391  return expr->GetValue(ctx);
7392  else
7393  return expr->GetLValue(ctx);
7394 }
7395 
7397  if (expr == NULL)
7398  return NULL;
7399 
7400  const Type *exprType = expr->GetType();
7401  if (CastType<ReferenceType>(exprType) != NULL)
7402  return PointerType::GetUniform(exprType->GetReferenceTarget());
7403 
7404  const Type *t = expr->GetLValueType();
7405  if (t != NULL)
7406  return t;
7407  else {
7408  t = expr->GetType();
7409  if (t == NULL) {
7410  AssertPos(pos, m->errorCount > 0);
7411  return NULL;
7412  }
7413  return PointerType::GetUniform(t);
7414  }
7415 }
7416 
7418  if (!expr)
7419  return NULL;
7420 
7421  const Type *type = expr->GetType();
7422  if (!type)
7423  return NULL;
7424 
7425  return PointerType::GetUniform(type);
7426 }
7427 
7429 
7430 void AddressOfExpr::Print() const {
7431  printf("&(");
7432  if (expr)
7433  expr->Print();
7434  else
7435  printf("NULL expr");
7436  printf(")");
7437  pos.Print();
7438 }
7439 
7441  const Type *exprType;
7442  if (expr == NULL || (exprType = expr->GetType()) == NULL) {
7443  AssertPos(pos, m->errorCount > 0);
7444  return NULL;
7445  }
7446 
7447  if (CastType<ReferenceType>(exprType) != NULL || CastType<FunctionType>(exprType) != NULL) {
7448  return this;
7449  }
7450 
7451  if (expr->GetLValueType() != NULL)
7452  return this;
7453 
7454  Error(expr->pos, "Illegal to take address of non-lvalue or function.");
7455  return NULL;
7456 }
7457 
7458 Expr *AddressOfExpr::Optimize() { return this; }
7459 
7460 int AddressOfExpr::EstimateCost() const { return 0; }
7461 
7462 std::pair<llvm::Constant *, bool> AddressOfExpr::GetConstant(const Type *type) const {
7463  const Type *exprType;
7464  if (expr == NULL || (exprType = expr->GetType()) == NULL) {
7465  AssertPos(pos, m->errorCount > 0);
7466  return std::pair<llvm::Constant *, bool>(NULL, false);
7467  }
7468 
7469  const PointerType *pt = CastType<PointerType>(type);
7470  if (pt == NULL)
7471  return std::pair<llvm::Constant *, bool>(NULL, false);
7472 
7473  bool isNotValidForMultiTargetGlobal = false;
7474  const FunctionType *ft = CastType<FunctionType>(pt->GetBaseType());
7475  if (ft != NULL) {
7476  std::pair<llvm::Constant *, bool> cPair = expr->GetConstant(ft);
7477  llvm::Constant *c = cPair.first;
7478  return std::pair<llvm::Constant *, bool>(lConvertPointerConstant(c, type), cPair.second);
7479  }
7480  llvm::Value *ptr = NULL;
7481  if (GetBaseSymbol())
7482  ptr = GetBaseSymbol()->storagePtr;
7483  if (ptr && llvm::dyn_cast<llvm::GlobalVariable>(ptr)) {
7484  const Type *eTYPE = GetType();
7485  if (type->LLVMType(g->ctx) == eTYPE->LLVMType(g->ctx)) {
7486  if (llvm::dyn_cast<SymbolExpr>(expr) != NULL) {
7487  return std::pair<llvm::Constant *, bool>(llvm::cast<llvm::Constant>(ptr),
7488  isNotValidForMultiTargetGlobal);
7489 
7490  } else if (IndexExpr *IExpr = llvm::dyn_cast<IndexExpr>(expr)) {
7491  std::vector<llvm::Value *> gepIndex;
7492  Expr *mBaseExpr = NULL;
7493  while (IExpr) {
7494  std::pair<llvm::Constant *, bool> cIndexPair = IExpr->index->GetConstant(IExpr->index->GetType());
7495  llvm::Constant *cIndex = cIndexPair.first;
7496  if (cIndex == NULL)
7497  return std::pair<llvm::Constant *, bool>(NULL, false);
7498  gepIndex.insert(gepIndex.begin(), cIndex);
7499  mBaseExpr = IExpr->baseExpr;
7500  IExpr = llvm::dyn_cast<IndexExpr>(mBaseExpr);
7501  isNotValidForMultiTargetGlobal = isNotValidForMultiTargetGlobal || cIndexPair.second;
7502  }
7503  // The base expression needs to be a global symbol so that the
7504  // address is a constant.
7505  if (llvm::dyn_cast<SymbolExpr>(mBaseExpr) == NULL)
7506  return std::pair<llvm::Constant *, bool>(NULL, false);
7507  gepIndex.insert(gepIndex.begin(), LLVMInt64(0));
7508  llvm::Constant *c = llvm::cast<llvm::Constant>(ptr);
7509  llvm::Constant *c1 = llvm::ConstantExpr::getGetElementPtr(PTYPE(c), c, gepIndex);
7510  return std::pair<llvm::Constant *, bool>(c1, isNotValidForMultiTargetGlobal);
7511  }
7512  }
7513  }
7514  return std::pair<llvm::Constant *, bool>(NULL, false);
7515 }
7516 
7517 ///////////////////////////////////////////////////////////////////////////
7518 // SizeOfExpr
7519 
7521 
7524 }
7525 
7526 llvm::Value *SizeOfExpr::GetValue(FunctionEmitContext *ctx) const {
7527  ctx->SetDebugPos(pos);
7528  const Type *t = expr ? expr->GetType() : type;
7529  if (t == NULL)
7530  return NULL;
7531 
7532  llvm::Type *llvmType = t->LLVMType(g->ctx);
7533  if (llvmType == NULL)
7534  return NULL;
7535 
7536  return g->target->SizeOf(llvmType, ctx->GetCurrentBasicBlock());
7537 }
7538 
7539 const Type *SizeOfExpr::GetType() const {
7542 }
7543 
7544 void SizeOfExpr::Print() const {
7545  printf("Sizeof (");
7546  if (expr != NULL)
7547  expr->Print();
7548  const Type *t = expr ? expr->GetType() : type;
7549  if (t != NULL)
7550  printf(" [type %s]", t->GetString().c_str());
7551  printf(")");
7552  pos.Print();
7553 }
7554 
7556  // Can't compute the size of a struct without a definition
7557  if (type != NULL && CastType<UndefinedStructType>(type) != NULL) {
7558  Error(pos,
7559  "Can't compute the size of declared but not defined "
7560  "struct type \"%s\".",
7561  type->GetString().c_str());
7562  return NULL;
7563  }
7564 
7565  return this;
7566 }
7567 
7568 Expr *SizeOfExpr::Optimize() { return this; }
7569 
7570 int SizeOfExpr::EstimateCost() const { return 0; }
7571 
7572 std::pair<llvm::Constant *, bool> SizeOfExpr::GetConstant(const Type *rtype) const {
7573  const Type *t = expr ? expr->GetType() : type;
7574  if (t == NULL)
7575  return std::pair<llvm::Constant *, bool>(NULL, false);
7576 
7577  bool isNotValidForMultiTargetGlobal = false;
7578  if (t->IsVaryingType())
7579  isNotValidForMultiTargetGlobal = true;
7580 
7581  llvm::Type *llvmType = t->LLVMType(g->ctx);
7582  if (llvmType == NULL)
7583  return std::pair<llvm::Constant *, bool>(NULL, false);
7584 
7585  if (g->target->IsGenericTypeLayoutIndeterminate(llvmType))
7586  return std::pair<llvm::Constant *, bool>(NULL, false);
7587  uint64_t byteSize = g->target->getDataLayout()->getTypeStoreSize(llvmType);
7588  return std::pair<llvm::Constant *, bool>(llvm::ConstantInt::get(rtype->LLVMType(g->ctx), byteSize),
7589  isNotValidForMultiTargetGlobal);
7590 }
7591 
7592 ///////////////////////////////////////////////////////////////////////////
7593 // SymbolExpr
7594 
7596 
7597 llvm::Value *SymbolExpr::GetValue(FunctionEmitContext *ctx) const {
7598  // storagePtr may be NULL due to an earlier compilation error
7599  if (!symbol || !symbol->storagePtr)
7600  return NULL;
7601  ctx->SetDebugPos(pos);
7602 
7603  std::string loadName = symbol->name + std::string("_load");
7604  return ctx->LoadInst(symbol->storagePtr, symbol->type, loadName.c_str());
7605 }
7606 
7607 llvm::Value *SymbolExpr::GetLValue(FunctionEmitContext *ctx) const {
7608  if (symbol == NULL)
7609  return NULL;
7610  ctx->SetDebugPos(pos);
7611  return symbol->storagePtr;
7612 }
7613 
7615  if (symbol == NULL)
7616  return NULL;
7617 
7618  if (CastType<ReferenceType>(symbol->type) != NULL)
7620  else
7622 }
7623 
7625 
7626 const Type *SymbolExpr::GetType() const { return symbol ? symbol->type : NULL; }
7627 
7628 Expr *SymbolExpr::TypeCheck() { return this; }
7629 
7631  if (symbol == NULL)
7632  return NULL;
7633  else if (symbol->constValue != NULL) {
7634  AssertPos(pos, GetType()->IsConstType());
7635  return new ConstExpr(symbol->constValue, pos);
7636  } else
7637  return this;
7638 }
7639 
7641  // Be optimistic and assume it's in a register or can be used as a
7642  // memory operand..
7643  return 0;
7644 }
7645 
7646 void SymbolExpr::Print() const {
7647  if (symbol == NULL || GetType() == NULL)
7648  return;
7649 
7650  printf("[%s] sym: (%s)", GetType()->GetString().c_str(), symbol->name.c_str());
7651  pos.Print();
7652 }
7653 
7654 ///////////////////////////////////////////////////////////////////////////
7655 // FunctionSymbolExpr
7656 
7657 FunctionSymbolExpr::FunctionSymbolExpr(const char *n, const std::vector<Symbol *> &candidates, SourcePos p)
7658  : Expr(p, FunctionSymbolExprID) {
7659  name = n;
7660  candidateFunctions = candidates;
7661  matchingFunc = (candidates.size() == 1) ? candidates[0] : NULL;
7662  triedToResolve = false;
7663 }
7664 
7666  if (triedToResolve == false && matchingFunc == NULL) {
7667  Error(pos, "Ambiguous use of overloaded function \"%s\".", name.c_str());
7668  return NULL;
7669  }
7670 
7671  return matchingFunc ? matchingFunc->type : NULL;
7672 }
7673 
7675  return matchingFunc ? matchingFunc->function : NULL;
7676 }
7677 
7679 
7681 
7683 
7684 int FunctionSymbolExpr::EstimateCost() const { return 0; }
7685 
7687  if (!matchingFunc || !GetType())
7688  return;
7689 
7690  printf("[%s] fun sym (%s)", GetType()->GetString().c_str(), matchingFunc->name.c_str());
7691  pos.Print();
7692 }
7693 
7694 std::pair<llvm::Constant *, bool> FunctionSymbolExpr::GetConstant(const Type *type) const {
7695  if (matchingFunc == NULL || matchingFunc->function == NULL)
7696  return std::pair<llvm::Constant *, bool>(NULL, false);
7697 
7698  const FunctionType *ft = CastType<FunctionType>(type);
7699  if (ft == NULL)
7700  return std::pair<llvm::Constant *, bool>(NULL, false);
7701 
7702  if (Type::Equal(type, matchingFunc->type) == false) {
7703  Error(pos,
7704  "Type of function symbol \"%s\" doesn't match expected type "
7705  "\"%s\".",
7706  matchingFunc->type->GetString().c_str(), type->GetString().c_str());
7707  return std::pair<llvm::Constant *, bool>(NULL, false);
7708  }
7709 
7710  return std::pair<llvm::Constant *, bool>(matchingFunc->function, false);
7711 }
7712 
7713 static std::string lGetOverloadCandidateMessage(const std::vector<Symbol *> &funcs,
7714  const std::vector<const Type *> &argTypes,
7715  const std::vector<bool> *argCouldBeNULL) {
7716  std::string message = "Passed types: (";
7717  for (unsigned int i = 0; i < argTypes.size(); ++i) {
7718  if (argTypes[i] != NULL)
7719  message += argTypes[i]->GetString();
7720  else
7721  message += "(unknown type)";
7722  message += (i < argTypes.size() - 1) ? ", " : ")\n";
7723  }
7724 
7725  for (unsigned int i = 0; i < funcs.size(); ++i) {
7726  const FunctionType *ft = CastType<FunctionType>(funcs[i]->type);
7727  Assert(ft != NULL);
7728  message += "Candidate: ";
7729  message += ft->GetString();
7730  if (i < funcs.size() - 1)
7731  message += "\n";
7732  }
7733  return message;
7734 }
7735 
7736 /** Helper function used for function overload resolution: returns true if
7737  converting the argument to the call type only requires a type
7738  conversion that won't lose information. Otherwise return false.
7739  */
7740 static bool lIsMatchWithTypeWidening(const Type *callType, const Type *funcArgType) {
7741  const AtomicType *callAt = CastType<AtomicType>(callType);
7742  const AtomicType *funcAt = CastType<AtomicType>(funcArgType);
7743  if (callAt == NULL || funcAt == NULL)
7744  return false;
7745 
7746  if (callAt->IsUniformType() != funcAt->IsUniformType())
7747  return false;
7748 
7749  switch (callAt->basicType) {
7750  case AtomicType::TYPE_BOOL:
7751  return true;
7752  case AtomicType::TYPE_INT8:
7754  return (funcAt->basicType != AtomicType::TYPE_BOOL);
7757  return (funcAt->basicType != AtomicType::TYPE_BOOL && funcAt->basicType != AtomicType::TYPE_INT8 &&
7758  funcAt->basicType != AtomicType::TYPE_UINT8);
7761  return (funcAt->basicType == AtomicType::TYPE_INT32 || funcAt->basicType == AtomicType::TYPE_UINT32 ||
7762  funcAt->basicType == AtomicType::TYPE_INT64 || funcAt->basicType == AtomicType::TYPE_UINT64);
7764  return (funcAt->basicType == AtomicType::TYPE_DOUBLE);
7767  return (funcAt->basicType == AtomicType::TYPE_INT64 || funcAt->basicType == AtomicType::TYPE_UINT64);
7769  return false;
7770  default:
7771  FATAL("Unhandled atomic type");
7772  return false;
7773  }
7774 }
7775 
7776 /* Returns the set of function overloads that are potential matches, given
7777  argCount values being passed as arguments to the function call.
7778  */
7779 std::vector<Symbol *> FunctionSymbolExpr::getCandidateFunctions(int argCount) const {
7780  std::vector<Symbol *> ret;
7781  for (int i = 0; i < (int)candidateFunctions.size(); ++i) {
7782  const FunctionType *ft = CastType<FunctionType>(candidateFunctions[i]->type);
7783  AssertPos(pos, ft != NULL);
7784 
7785  // There's no way to match if the caller is passing more arguments
7786  // than this function instance takes.
7787  if (argCount > ft->GetNumParameters())
7788  continue;
7789 
7790  // Not enough arguments, and no default argument value to save us
7791  if (argCount < ft->GetNumParameters() && ft->GetParameterDefault(argCount) == NULL)
7792  continue;
7793 
7794  // Success
7795  ret.push_back(candidateFunctions[i]);
7796  }
7797  return ret;
7798 }
7799 
7800 static bool lArgIsPointerType(const Type *type) {
7801  if (CastType<PointerType>(type) != NULL)
7802  return true;
7803 
7804  const ReferenceType *rt = CastType<ReferenceType>(type);
7805  if (rt == NULL)
7806  return false;
7807 
7808  const Type *t = rt->GetReferenceTarget();
7809  return (CastType<PointerType>(t) != NULL);
7810 }
7811 
7812 /** This function computes the value of a cost function that represents the
7813  cost of calling a function of the given type with arguments of the
7814  given types. If it's not possible to call the function, regardless of
7815  any type conversions applied, a cost of -1 is returned.
7816  */
7817 int FunctionSymbolExpr::computeOverloadCost(const FunctionType *ftype, const std::vector<const Type *> &argTypes,
7818  const std::vector<bool> *argCouldBeNULL,
7819  const std::vector<bool> *argIsConstant, int *cost) {
7820  int costSum = 0;
7821 
7822  // In computing the cost function, we only worry about the actual
7823  // argument types--using function default parameter values is free for
7824  // the purposes here...
7825  for (int i = 0; i < (int)argTypes.size(); ++i) {
7826  cost[i] = 0;
7827  // The cost imposed by this argument will be a multiple of
7828  // costScale, which has a value set so that for each of the cost
7829  // buckets, even if all of the function arguments undergo the next
7830  // lower-cost conversion, the sum of their costs will be less than
7831  // a single instance of the next higher-cost conversion.
7832  int costScale = argTypes.size() + 1;
7833 
7834  const Type *fargType = ftype->GetParameterType(i);
7835  const Type *callType = argTypes[i];
7836 
7837  if (Type::Equal(callType, fargType))
7838  // Perfect match: no cost
7839  // Step "1" from documentation
7840  cost[i] += 0;
7841  else if (argCouldBeNULL && (*argCouldBeNULL)[i] && lArgIsPointerType(fargType))
7842  // Passing NULL to a pointer-typed parameter is also a no-cost operation
7843  // Step "1" from documentation
7844  cost[i] += 0;
7845  else {
7846  // If the argument is a compile-time constant, we'd like to
7847  // count the cost of various conversions as much lower than the
7848  // cost if it wasn't--so scale up the cost when this isn't the
7849  // case..
7850  if (argIsConstant == NULL || (*argIsConstant)[i] == false)
7851  costScale *= 512;
7852 
7853  if (CastType<ReferenceType>(fargType)) {
7854  // Here we completely handle the case where fargType is reference.
7855  if (callType->IsConstType() && !fargType->IsConstType()) {
7856  // It is forbidden to pass const object to non-const reference (cvf -> vfr)
7857  return -1;
7858  }
7859  if (!callType->IsConstType() && fargType->IsConstType()) {
7860  // It is possible to pass (vf -> cvfr)
7861  // but it is worse than (vf -> vfr) or (cvf -> cvfr)
7862  // Step "3" from documentation
7863  cost[i] += 2 * costScale;
7864  }
7865  if (!Type::Equal(callType->GetReferenceTarget()->GetAsNonConstType(),
7866  fargType->GetReferenceTarget()->GetAsNonConstType())) {
7867  // Types under references must be equal completely.
7868  // vd -> vfr or vd -> cvfr are forbidden. (Although clang allows vd -> cvfr case.)
7869  return -1;
7870  }
7871  // penalty for equal types under reference (vf -> vfr is worse than vf -> vf)
7872  // Step "2" from documentation
7873  cost[i] += 2 * costScale;
7874  continue;
7875  }
7876  const Type *callTypeNP = callType;
7877  if (CastType<ReferenceType>(callType)) {
7878  callTypeNP = callType->GetReferenceTarget();
7879  // we can treat vfr as vf for callType with some penalty
7880  // Step "5" from documentation
7881  cost[i] += 2 * costScale;
7882  }
7883 
7884  // Now we deal with references, so we can normalize to non-const types
7885  // because we're passing by value anyway, so const doesn't matter.
7886  const Type *callTypeNC = callTypeNP->GetAsNonConstType();
7887  const Type *fargTypeNC = fargType->GetAsNonConstType();
7888 
7889  // Now we forget about constants and references!
7890  if (Type::EqualIgnoringConst(callTypeNP, fargType)) {
7891  // The best case: vf -> vf.
7892  // Step "4" from documentation
7893  cost[i] += 1 * costScale;
7894  continue;
7895  }
7896  if (lIsMatchWithTypeWidening(callTypeNC, fargTypeNC)) {
7897  // A little bit worse case: vf -> vd.
7898  // Step "6" from documentation
7899  cost[i] += 8 * costScale;
7900  continue;
7901  }
7902  if (fargType->IsVaryingType() && callType->IsUniformType()) {
7903  // Here we deal with brodcasting uniform to varying.
7904  // callType - varying and fargType - uniform is forbidden.
7905  if (Type::Equal(callTypeNC->GetAsVaryingType(), fargTypeNC)) {
7906  // uf -> vf is better than uf -> ui or uf -> ud
7907  // Step "7" from documentation
7908  cost[i] += 16 * costScale;
7909  continue;
7910  }
7911  if (lIsMatchWithTypeWidening(callTypeNC->GetAsVaryingType(), fargTypeNC)) {
7912  // uf -> vd is better than uf -> vi (128 < 128 + 64)
7913  // but worse than uf -> ui (128 > 64)
7914  // Step "9" from documentation
7915  cost[i] += 128 * costScale;
7916  continue;
7917  }
7918  // 128 + 64 is the max. uf -> vi is the worst case.
7919  // Step "10" from documentation
7920  cost[i] += 128 * costScale;
7921  }
7922  if (CanConvertTypes(callTypeNC, fargTypeNC))
7923  // two cases: the worst is 128 + 64: uf -> vi and
7924  // the only 64: (64 < 128) uf -> ui worse than uf -> vd
7925  // Step "8" from documentation
7926  cost[i] += 64 * costScale;
7927  else
7928  // Failure--no type conversion possible...
7929  return -1;
7930  }
7931  }
7932 
7933  for (int i = 0; i < (int)argTypes.size(); ++i) {
7934  costSum = costSum + cost[i];
7935  }
7936  return costSum;
7937 }
7938 
7939 bool FunctionSymbolExpr::ResolveOverloads(SourcePos argPos, const std::vector<const Type *> &argTypes,
7940  const std::vector<bool> *argCouldBeNULL,
7941  const std::vector<bool> *argIsConstant) {
7942  const char *funName = candidateFunctions.front()->name.c_str();
7943  if (triedToResolve == true) {
7944  return true;
7945  }
7946 
7947  triedToResolve = true;
7948 
7949  // Functions with names that start with "__" should only be various
7950  // builtins. For those, we'll demand an exact match, since we'll
7951  // expect whichever function in stdlib.ispc is calling out to one of
7952  // those to be matching the argument types exactly; this is to be a bit
7953  // extra safe to be sure that the expected builtin is in fact being
7954  // called.
7955  bool exactMatchOnly = (name.substr(0, 2) == "__");
7956 
7957  // First, find the subset of overload candidates that take the same
7958  // number of arguments as have parameters (including functions that
7959  // take more arguments but have defaults starting no later than after
7960  // our last parameter).
7961  std::vector<Symbol *> actualCandidates = getCandidateFunctions(argTypes.size());
7962 
7963  int bestMatchCost = 1 << 30;
7964  std::vector<Symbol *> matches;
7965  std::vector<int> candidateCosts;
7966  std::vector<int *> candidateExpandCosts;
7967 
7968  if (actualCandidates.size() == 0)
7969  goto failure;
7970 
7971  // Compute the cost for calling each of the candidate functions
7972  for (int i = 0; i < (int)actualCandidates.size(); ++i) {
7973  const FunctionType *ft = CastType<FunctionType>(actualCandidates[i]->type);
7974  AssertPos(pos, ft != NULL);
7975  int *cost = new int[argTypes.size()];
7976  candidateCosts.push_back(computeOverloadCost(ft, argTypes, argCouldBeNULL, argIsConstant, cost));
7977  candidateExpandCosts.push_back(cost);
7978  }
7979 
7980  // Find the best cost, and then the candidate or candidates that have
7981  // that cost.
7982  for (int i = 0; i < (int)candidateCosts.size(); ++i) {
7983  if (candidateCosts[i] != -1 && candidateCosts[i] < bestMatchCost)
7984  bestMatchCost = candidateCosts[i];
7985  }
7986  // None of the candidates matched
7987  if (bestMatchCost == (1 << 30))
7988  goto failure;
7989  for (int i = 0; i < (int)candidateCosts.size(); ++i) {
7990  if (candidateCosts[i] == bestMatchCost) {
7991  for (int j = 0; j < (int)candidateCosts.size(); ++j) {
7992  for (int k = 0; k < argTypes.size(); k++) {
7993  if (candidateCosts[j] != -1 && candidateExpandCosts[j][k] < candidateExpandCosts[i][k]) {
7994  std::vector<Symbol *> temp;
7995  temp.push_back(actualCandidates[i]);
7996  temp.push_back(actualCandidates[j]);
7997  std::string candidateMessage = lGetOverloadCandidateMessage(temp, argTypes, argCouldBeNULL);
7998  Warning(pos,
7999  "call to \"%s\" is ambiguous. "
8000  "This warning will be turned into error in the next ispc release.\n"
8001  "Please add explicit cast to arguments to have unambiguous match."
8002  "\n%s",
8003  funName, candidateMessage.c_str());
8004  }
8005  }
8006  }
8007  matches.push_back(actualCandidates[i]);
8008  }
8009  }
8010  for (int i = 0; i < (int)candidateExpandCosts.size(); ++i) {
8011  delete[] candidateExpandCosts[i];
8012  }
8013 
8014  if (matches.size() == 1) {
8015  // Only one match: success
8016  matchingFunc = matches[0];
8017  return true;
8018  } else if (matches.size() > 1) {
8019  // Multiple matches: ambiguous
8020  std::string candidateMessage = lGetOverloadCandidateMessage(matches, argTypes, argCouldBeNULL);
8021  Error(pos,
8022  "Multiple overloaded functions matched call to function "
8023  "\"%s\"%s.\n%s",
8024  funName, exactMatchOnly ? " only considering exact matches" : "", candidateMessage.c_str());
8025  return false;
8026  } else {
8027  // No matches at all
8028  failure:
8029  std::string candidateMessage = lGetOverloadCandidateMessage(matches, argTypes, argCouldBeNULL);
8030  Error(pos,
8031  "Unable to find any matching overload for call to function "
8032  "\"%s\"%s.\n%s",
8033  funName, exactMatchOnly ? " only considering exact matches" : "", candidateMessage.c_str());
8034  return false;
8035  }
8036 }
8037 
8039 
8040 ///////////////////////////////////////////////////////////////////////////
8041 // SyncExpr
8042 
8043 const Type *SyncExpr::GetType() const { return AtomicType::Void; }
8044 
8045 llvm::Value *SyncExpr::GetValue(FunctionEmitContext *ctx) const {
8046  ctx->SetDebugPos(pos);
8047  ctx->SyncInst();
8048  return NULL;
8049 }
8050 
8051 int SyncExpr::EstimateCost() const { return COST_SYNC; }
8052 
8053 void SyncExpr::Print() const {
8054  printf("sync");
8055  pos.Print();
8056 }
8057 
8058 Expr *SyncExpr::TypeCheck() { return this; }
8059 
8060 Expr *SyncExpr::Optimize() { return this; }
8061 
8062 ///////////////////////////////////////////////////////////////////////////
8063 // NullPointerExpr
8064 
8066  return llvm::ConstantPointerNull::get(LLVMTypes::VoidPointerType);
8067 }
8068 
8070 
8072 
8073 Expr *NullPointerExpr::Optimize() { return this; }
8074 
8075 std::pair<llvm::Constant *, bool> NullPointerExpr::GetConstant(const Type *type) const {
8076  const PointerType *pt = CastType<PointerType>(type);
8077  if (pt == NULL)
8078  return std::pair<llvm::Constant *, bool>(NULL, false);
8079 
8080  llvm::Type *llvmType = type->LLVMType(g->ctx);
8081  if (llvmType == NULL) {
8082  AssertPos(pos, m->errorCount > 0);
8083  return std::pair<llvm::Constant *, bool>(NULL, false);
8084  }
8085 
8086  return std::pair<llvm::Constant *, bool>(llvm::Constant::getNullValue(llvmType), false);
8087 }
8088 
8090  printf("NULL");
8091  pos.Print();
8092 }
8093 
8094 int NullPointerExpr::EstimateCost() const { return 0; }
8095 
8096 ///////////////////////////////////////////////////////////////////////////
8097 // NewExpr
8098 
8099 NewExpr::NewExpr(int typeQual, const Type *t, Expr *init, Expr *count, SourcePos tqPos, SourcePos p)
8100  : Expr(p, NewExprID) {
8101  allocType = t;
8102 
8103  initExpr = init;
8104  countExpr = count;
8105 
8106  /* (The below cases actually should be impossible, since the parser
8107  doesn't allow more than a single type qualifier before a "new".) */
8108  if ((typeQual & ~(TYPEQUAL_UNIFORM | TYPEQUAL_VARYING)) != 0) {
8109  Error(tqPos, "Illegal type qualifiers in \"new\" expression (only "
8110  "\"uniform\" and \"varying\" are allowed.");
8111  isVarying = false;
8112  } else if ((typeQual & TYPEQUAL_UNIFORM) != 0 && (typeQual & TYPEQUAL_VARYING) != 0) {
8113  Error(tqPos, "Illegal to provide both \"uniform\" and \"varying\" "
8114  "qualifiers to \"new\" expression.");
8115  isVarying = false;
8116  } else
8117  // If no type qualifier is given before the 'new', treat it as a
8118  // varying new.
8119  isVarying = (typeQual == 0) || (typeQual & TYPEQUAL_VARYING);
8120 
8121  if (allocType != NULL)
8123 }
8124 
8125 llvm::Value *NewExpr::GetValue(FunctionEmitContext *ctx) const {
8126  bool do32Bit = (g->target->is32Bit() || g->opt.force32BitAddressing);
8127 
8128  // Determine how many elements we need to allocate. Note that this
8129  // will be a varying value if this is a varying new.
8130  llvm::Value *countValue;
8131  if (countExpr != NULL) {
8132  countValue = countExpr->GetValue(ctx);
8133  if (countValue == NULL) {
8134  AssertPos(pos, m->errorCount > 0);
8135  return NULL;
8136  }
8137  } else {
8138  if (isVarying) {
8139  if (do32Bit)
8140  countValue = LLVMInt32Vector(1);
8141  else
8142  countValue = LLVMInt64Vector(1);
8143  } else {
8144  if (do32Bit)
8145  countValue = LLVMInt32(1);
8146  else
8147  countValue = LLVMInt64(1);
8148  }
8149  }
8150 
8151  // Compute the total amount of memory to allocate, allocSize, as the
8152  // product of the number of elements to allocate and the size of a
8153  // single element.
8154  llvm::Value *eltSize = g->target->SizeOf(allocType->LLVMType(g->ctx), ctx->GetCurrentBasicBlock());
8155  if (isVarying)
8156  eltSize = ctx->SmearUniform(eltSize, "smear_size");
8157  llvm::Value *allocSize = ctx->BinaryOperator(llvm::Instruction::Mul, countValue, eltSize, "alloc_size");
8158 
8159  // Determine which allocation builtin function to call: uniform or
8160  // varying, and taking 32-bit or 64-bit allocation counts.
8161  llvm::Function *func;
8162  if (isVarying) {
8163  if (g->target->is32Bit()) {
8164  func = m->module->getFunction("__new_varying32_32rt");
8165  } else if (g->opt.force32BitAddressing) {
8166  func = m->module->getFunction("__new_varying32_64rt");
8167  } else {
8168  func = m->module->getFunction("__new_varying64_64rt");
8169  }
8170  } else {
8171  // FIXME: __new_uniform_32rt should take i32
8172  if (allocSize->getType() != LLVMTypes::Int64Type)
8173  allocSize = ctx->SExtInst(allocSize, LLVMTypes::Int64Type, "alloc_size64");
8174  if (g->target->is32Bit()) {
8175  func = m->module->getFunction("__new_uniform_32rt");
8176  } else {
8177  func = m->module->getFunction("__new_uniform_64rt");
8178  }
8179  }
8180  AssertPos(pos, func != NULL);
8181 
8182  // Make the call for the the actual allocation.
8183  llvm::Value *ptrValue = ctx->CallInst(func, NULL, allocSize, "new");
8184 
8185  // Now handle initializers and returning the right type for the result.
8186  const Type *retType = GetType();
8187  if (retType == NULL)
8188  return NULL;
8189  if (isVarying) {
8190  if (g->target->is32Bit())
8191  // Convert i64 vector values to i32 if we are compiling to a
8192  // 32-bit target.
8193  ptrValue = ctx->TruncInst(ptrValue, LLVMTypes::VoidPointerVectorType, "ptr_to_32bit");
8194 
8195  if (initExpr != NULL) {
8196  // If we have an initializer expression, emit code that checks
8197  // to see if each lane is active and if so, runs the code to do
8198  // the initialization. Note that we're we're taking advantage
8199  // of the fact that the __new_varying*() functions are
8200  // implemented to return NULL for program instances that aren't
8201  // executing; more generally, we should be using the current
8202  // execution mask for this...
8203  for (int i = 0; i < g->target->getVectorWidth(); ++i) {
8204  llvm::BasicBlock *bbInit = ctx->CreateBasicBlock("init_ptr");
8205  llvm::BasicBlock *bbSkip = ctx->CreateBasicBlock("skip_init");
8206  llvm::Value *p = ctx->ExtractInst(ptrValue, i);
8207  llvm::Value *nullValue = g->target->is32Bit() ? LLVMInt32(0) : LLVMInt64(0);
8208  // Is the pointer for the current lane non-zero?
8209  llvm::Value *nonNull =
8210  ctx->CmpInst(llvm::Instruction::ICmp, llvm::CmpInst::ICMP_NE, p, nullValue, "non_null");
8211  ctx->BranchInst(bbInit, bbSkip, nonNull);
8212 
8213  // Initialize the memory pointed to by the pointer for the
8214  // current lane.
8215  ctx->SetCurrentBasicBlock(bbInit);
8216  llvm::Type *ptrType = retType->GetAsUniformType()->LLVMType(g->ctx);
8217  llvm::Value *ptr = ctx->IntToPtrInst(p, ptrType);
8218  InitSymbol(ptr, allocType, initExpr, ctx, pos);
8219  ctx->BranchInst(bbSkip);
8220 
8221  ctx->SetCurrentBasicBlock(bbSkip);
8222  }
8223  }
8224 
8225  return ptrValue;
8226  } else {
8227  // For uniform news, we just need to cast the void * to be a
8228  // pointer of the return type and to run the code for initializers,
8229  // if present.
8230  llvm::Type *ptrType = retType->LLVMType(g->ctx);
8231  ptrValue = ctx->BitCastInst(ptrValue, ptrType, LLVMGetName(ptrValue, "_cast_ptr"));
8232 
8233  if (initExpr != NULL)
8234  InitSymbol(ptrValue, allocType, initExpr, ctx, pos);
8235 
8236  return ptrValue;
8237  }
8238 }
8239 
8240 const Type *NewExpr::GetType() const {
8241  if (allocType == NULL)
8242  return NULL;
8243 
8245 }
8246 
8248  // It's illegal to call new with an undefined struct type
8249  if (allocType == NULL) {
8250  AssertPos(pos, m->errorCount > 0);
8251  return NULL;
8252  }
8253  if (CastType<UndefinedStructType>(allocType) != NULL) {
8254  Error(pos,
8255  "Can't dynamically allocate storage for declared "
8256  "but not defined type \"%s\".",
8257  allocType->GetString().c_str());
8258  return NULL;
8259  }
8260  const StructType *st = CastType<StructType>(allocType);
8261  if (st != NULL && !st->IsDefined()) {
8262  Error(pos,
8263  "Can't dynamically allocate storage for declared "
8264  "type \"%s\" containing undefined member type.",
8265  allocType->GetString().c_str());
8266  return NULL;
8267  }
8268 
8269  // Otherwise we only need to make sure that if we have an expression
8270  // giving a number of elements to allocate that it can be converted to
8271  // an integer of the appropriate variability.
8272  if (countExpr == NULL)
8273  return this;
8274 
8275  const Type *countType;
8276  if ((countType = countExpr->GetType()) == NULL)
8277  return NULL;
8278 
8279  if (isVarying == false && countType->IsVaryingType()) {
8280  Error(pos, "Illegal to provide \"varying\" allocation count with "
8281  "\"uniform new\" expression.");
8282  return NULL;
8283  }
8284 
8285  // Figure out the type that the allocation count should be
8286  const Type *t =
8288  if (isVarying)
8289  t = t->GetAsVaryingType();
8290 
8291  countExpr = TypeConvertExpr(countExpr, t, "item count");
8292  if (countExpr == NULL)
8293  return NULL;
8294 
8295  return this;
8296 }
8297 
8298 Expr *NewExpr::Optimize() { return this; }
8299 
8300 void NewExpr::Print() const { printf("new (%s)", allocType ? allocType->GetString().c_str() : "NULL"); }
8301 
8302 int NewExpr::EstimateCost() const { return COST_NEW; }
const Function * GetFunction() const
Definition: ctx.cpp:357
llvm::Constant * LLVMIntAsType(int64_t val, llvm::Type *type)
Definition: llvmutil.cpp:463
virtual bool IsIntType() const =0
llvm::Value * storagePtr
Definition: sym.h:70
static const AtomicType * VaryingInt32
Definition: type.h:325
static llvm::Type * FloatType
Definition: llvmutil.h:69
llvm::Value * Any(llvm::Value *mask)
Definition: ctx.cpp:1123
Symbol * GetMatchingFunction()
Definition: expr.cpp:8038
llvm::Value * lEmitLogicalOp(BinaryExpr::Op op, Expr *arg0, Expr *arg1, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:1631
virtual const Type * GetAsVaryingType() const =0
bool IsReferenceType() const
Definition: type.cpp:165
Common base class that provides shared functionality for PtrDerefExpr and RefDerefExpr.
Definition: expr.h:536
std::pair< llvm::Constant *, bool > GetConstant(const Type *constType) const
Definition: expr.cpp:5949
static const AtomicType * VaryingInt16
Definition: type.h:324
const Type * type
Definition: expr.h:627
bool IsUniformType() const
Definition: type.h:134
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4939
llvm::Function * function
Definition: sym.h:74
llvm::Constant * LLVMUInt64Vector(uint64_t ival)
Definition: llvmutil.cpp:388
Expr * Optimize()
Definition: expr.cpp:7682
const Type * type
Definition: expr.h:320
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7526
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:3932
const Type * GetType() const
Definition: expr.cpp:4121
const Type * GetLValueType() const
Definition: expr.cpp:4697
std::string GetString() const
Definition: type.cpp:302
llvm::Value * PtrToIntInst(llvm::Value *value, const char *name=NULL)
Definition: ctx.cpp:1532
Expr * countExpr
Definition: expr.h:764
|= assignment
Definition: expr.h:201
void Print() const
Definition: expr.cpp:7321
llvm::Constant * LLVMUInt32Vector(uint32_t ival)
Definition: llvmutil.cpp:328
Expr * TypeCheck()
Definition: expr.cpp:7440
llvm::ConstantInt * LLVMUInt32(uint32_t ival)
Definition: llvmutil.cpp:237
virtual int getElementNumber() const =0
Definition: expr.cpp:4937
const Type * type
Definition: expr.h:364
llvm::Value * AddElementOffset(llvm::Value *basePtr, int elementNum, const Type *ptrType, const char *name=NULL, const PointerType **resultPtrType=NULL)
Definition: ctx.cpp:1951
Opt opt
Definition: ispc.h:509
int EstimateCost() const
Definition: expr.cpp:4970
Expr * Optimize()
Definition: expr.cpp:4968
llvm::Value * ProgramIndexVector(bool is32bits=true)
Definition: ctx.cpp:1208
StructMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue)
Definition: expr.cpp:4500
void SetInternalMask(llvm::Value *val)
Definition: ctx.cpp:381
llvm::Instruction * FPCastInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1639
const Type * GetReturnType() const
Definition: type.h:864
DerefExpr(Expr *e, SourcePos p, unsigned scid=DerefExprID)
Definition: expr.cpp:7222
int8_t int8Val[ISPC_MAX_NVEC]
Definition: expr.h:475
Division.
Definition: expr.h:146
Declaration of the FunctionEmitContext class
virtual const Type * ResolveUnboundVariability(Variability v) const =0
void Print() const
Definition: expr.cpp:2653
const Type * GetType() const
Definition: expr.cpp:3574
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7674
llvm::Constant * LLVMBoolVector(bool b)
Definition: llvmutil.cpp:403
Expr * TypeCheck()
Definition: expr.cpp:7555
static int lIdentifierToVectorElement(char id)
Definition: expr.cpp:4460
void Print() const
Definition: expr.cpp:7064
int EstimateCost() const
Definition: expr.cpp:3059
static const AtomicType * VaryingUInt64
Definition: type.h:331
static llvm::Type * DoubleType
Definition: llvmutil.h:70
/= assignment
Definition: expr.h:193
bool SafeToRunWithMaskAllOff(ASTNode *root)
Definition: ast.cpp:417
static llvm::Value * lTypeConvAtomic(FunctionEmitContext *ctx, llvm::Value *exprVal, const AtomicType *toType, const AtomicType *fromType, SourcePos pos)
Definition: expr.cpp:6018
int EstimateCost() const
Definition: expr.cpp:1272
Bitwise OR.
Definition: expr.h:160
bool IsVaryingType() const
Definition: type.h:137
void SetInternalMaskAnd(llvm::Value *oldMask, llvm::Value *val)
Definition: ctx.cpp:387
void BranchInst(llvm::BasicBlock *block)
Definition: ctx.cpp:2819
bool IsSOAType() const
Definition: type.h:141
static PointerType * Void
Definition: type.h:463
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:1885
static void lCheckIndicesVersusBounds(const Type *baseExprType, Expr *index)
Definition: expr.cpp:4186
llvm::ConstantInt * LLVMInt8(int8_t ival)
Definition: llvmutil.cpp:217
llvm::Instruction * ZExtInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1671
#define AssertPos(pos, expr)
Definition: util.h:142
Expression that represents taking a reference of a (non-reference) variable.
Definition: expr.h:515
Expr * TypeCheck()
Definition: expr.cpp:6895
Expr * Optimize()
Definition: expr.cpp:2200
llvm::Constant * LLVMInt64Vector(int64_t ival)
Definition: llvmutil.cpp:373
An expression that represents a NULL pointer.
Definition: expr.h:726
SourcePos Union(const SourcePos &p1, const SourcePos &p2)
Definition: ispc.cpp:1523
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:8045
std::pair< llvm::Constant *, bool > GetStorageConstant(const Type *type) const
Definition: expr.cpp:2749
Expr * Optimize()
Definition: expr.cpp:7261
llvm::ConstantInt * LLVMUInt8(uint8_t ival)
Definition: llvmutil.cpp:221
llvm::Value * NotOperator(llvm::Value *v, const char *name=NULL)
Definition: ctx.cpp:1412
std::string GetString() const
Definition: type.cpp:85
llvm::Type * LLVMStorageType(llvm::LLVMContext *ctx) const
Definition: type.cpp:509
void Print() const
Definition: expr.cpp:8089
int GetSOAWidth() const
Definition: type.h:145
Target * target
Definition: ispc.h:512
llvm::Value * SizeOf(llvm::Type *type, llvm::BasicBlock *insertAtEnd)
Definition: ispc.cpp:1359
const Type * GetType() const
Definition: expr.cpp:7272
Logical AND.
Definition: expr.h:161
llvm::Value * LoadInst(llvm::Value *ptr, llvm::Value *mask, const Type *ptrType, const char *name=NULL, bool one_elem=false)
Definition: ctx.cpp:2172
static llvm::VectorType * VoidPointerVectorType
Definition: llvmutil.h:98
void Print() const
Definition: expr.cpp:7369
static llvm::VectorType * BoolVectorType
Definition: llvmutil.h:81
int EstimateCost() const
Definition: expr.cpp:7460
int16_t int16Val[ISPC_MAX_NVEC]
Definition: expr.h:477
AtomicType::BasicType getBasicType() const
Definition: expr.cpp:5291
ASTNode * TypeCheck(ASTNode *root)
Definition: ast.cpp:242
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:5303
static const AtomicType * VaryingDouble
Definition: type.h:332
virtual std::pair< llvm::Constant *, bool > GetStorageConstant(const Type *type) const
Definition: expr.cpp:84
const char * LLVMGetName(llvm::Value *v, const char *s)
Definition: llvmutil.cpp:1549
llvm::Instruction * TruncInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1606
static bool lIsMatchWithTypeWidening(const Type *callType, const Type *funcArgType)
Definition: expr.cpp:7740
llvm::Constant * LLVMMaskAllOn
Definition: llvmutil.cpp:94
static void lStoreAssignResult(llvm::Value *value, llvm::Value *ptr, const Type *valueType, const Type *ptrType, FunctionEmitContext *ctx, Symbol *baseSym)
Definition: expr.cpp:921
llvm::Value * AllocaInst(llvm::Type *llvmType, const char *name=NULL, int align=0, bool atEntryBlock=true)
Definition: ctx.cpp:2401
Expr * baseExpr
Definition: expr.h:317
Expression representing a compile-time constant value.
Definition: expr.h:374
Abstract base class for types that represent sequences.
Definition: type.h:498
static bool classof(ASTNode const *N)
Definition: expr.cpp:4631
SymbolExpr(Symbol *s, SourcePos p)
Definition: expr.cpp:7595
std::string GetString() const
Definition: type.cpp:1746
TypeCastExpr(const Type *t, Expr *e, SourcePos p)
Definition: expr.cpp:6009
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7428
bool IsBoolType() const
Definition: type.cpp:181
Symbol * GetBaseSymbol() const
Definition: expr.cpp:4935
int getVectorMemoryCount() const
Definition: type.cpp:1491
llvm::Value * CmpInst(llvm::Instruction::OtherOps inst, llvm::CmpInst::Predicate pred, llvm::Value *v0, llvm::Value *v1, const char *name=NULL)
Definition: ctx.cpp:1454
const PointerType * lvalueType
Definition: expr.h:321
Expr * MakeBinaryExpr(BinaryExpr::Op o, Expr *a, Expr *b, SourcePos p)
Definition: expr.cpp:1617
Greater than.
Definition: expr.h:152
std::string GetString() const
Definition: type.cpp:897
const Type * GetLValueType() const
Definition: expr.cpp:2636
static llvm::Type * BoolType
Definition: llvmutil.h:62
int EstimateCost() const
Definition: expr.cpp:7306
Expr * TypeCheck()
Definition: expr.cpp:8247
llvm::Value * LaunchInst(llvm::Value *callee, std::vector< llvm::Value *> &argVals, llvm::Value *launchCount[3])
Definition: ctx.cpp:3160
void Print() const
Definition: expr.cpp:3752
static void lConvertElement(From from, To *to)
Definition: expr.cpp:5346
bool FullResolveOverloads(Expr *func, ExprList *args, std::vector< const Type *> *argTypes, std::vector< bool > *argCouldBeNULL, std::vector< bool > *argIsConstant)
Definition: expr.cpp:3558
const Type * GetType() const
Definition: expr.cpp:3247
const Type * GetElementType() const
Definition: type.cpp:1185
Expr * expr
Definition: expr.h:351
llvm::ConstantInt * LLVMInt16(int16_t ival)
Definition: llvmutil.cpp:225
bool IsDefined() const
Definition: type.cpp:1653
std::string getCandidateNearMatches() const
Definition: expr.cpp:4992
BinaryExpr(Op o, Expr *a, Expr *b, SourcePos p)
Definition: expr.cpp:1571
int EstimateCost() const
Definition: expr.cpp:8051
std::string name
Definition: expr.h:695
Expr * TypeCheck()
Definition: expr.cpp:2327
const Type * GetLValueType() const
Definition: expr.cpp:7614
virtual Expr * Optimize()=0
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:1029
bool triedToResolve
Definition: expr.h:705
const Type * GetLValueType() const
Definition: expr.cpp:4297
const Type * GetType() const
Definition: expr.cpp:8240
Less than.
Definition: expr.h:151
Symbol * symbol
Definition: expr.h:649
static llvm::VectorType * Int32VectorType
Definition: llvmutil.h:86
Expr * TypeConvertExpr(Expr *expr, const Type *toType, const char *errorMsgBase)
Definition: expr.cpp:548
Negation.
Definition: expr.h:118
bool PossiblyResolveFunctionOverloads(Expr *expr, const Type *type)
Definition: expr.cpp:565
static const AtomicType * UniformUInt32
Definition: type.h:328
const Type * GetLValueType() const
Definition: expr.cpp:7253
int GetElementNumber(const std::string &name) const
Definition: type.cpp:1888
static ConstExpr * lConstFoldBoolBinaryOp(BinaryExpr::Op op, const bool *v0, const bool *v1, ConstExpr *carg0)
Definition: expr.cpp:2104
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:7462
static llvm::VectorType * BoolVectorStorageType
Definition: llvmutil.h:82
static const char * lOpString(BinaryExpr::Op op)
Definition: expr.cpp:1308
static PointerType * GetVarying(const Type *t)
Definition: type.cpp:803
llvm::Constant * LLVMFalseInStorage
Definition: llvmutil.cpp:93
ReferenceExpr(Expr *e, SourcePos p)
Definition: expr.cpp:7138
#define FOLD_OP(O, E)
Definition: expr.cpp:2011
llvm::Value * GetFullMask()
Definition: ctx.cpp:367
const Type * GetType() const
Definition: expr.cpp:7539
const Op op
Definition: expr.h:135
PtrDerefExpr(Expr *e, SourcePos p)
Definition: expr.cpp:7270
Comma operator.
Definition: expr.h:164
int VaryingCFDepth() const
Definition: ctx.cpp:996
virtual std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:85
Symbol * matchingFunc
Definition: expr.h:703
llvm::Value * MakeSlicePointer(llvm::Value *ptr, llvm::Value *offset)
Definition: ctx.cpp:1810
void Print() const
Definition: expr.cpp:4978
int GetNumParameters() const
Definition: type.h:874
const Type * GetType() const
Definition: expr.cpp:7173
SelectExpr(Expr *test, Expr *a, Expr *b, SourcePos p)
Definition: expr.cpp:3083
Module * m
Definition: ispc.cpp:73
std::string name
Definition: sym.h:69
llvm::Value * SwitchBoolSize(llvm::Value *value, llvm::Type *fromType, llvm::Type *toType, const char *name=NULL)
Definition: ctx.cpp:2051
int Count() const
Definition: expr.cpp:5822
void Print() const
Definition: expr.cpp:5959
A list of expressions.
Definition: expr.h:249
Expr * Optimize()
Definition: expr.cpp:7630
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7259
static llvm::Value * lEmitPrePostIncDec(UnaryExpr::Op op, Expr *expr, SourcePos pos, FunctionEmitContext *ctx)
Definition: expr.cpp:944
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7247
const Type * GetType() const
Definition: expr.cpp:6859
static std::string lGetOverloadCandidateMessage(const std::vector< Symbol *> &funcs, const std::vector< const Type *> &argTypes, const std::vector< bool > *argCouldBeNULL)
Definition: expr.cpp:7713
const Type * GetType() const
Definition: expr.cpp:5301
Type implementation for pointers to other types.
Definition: type.h:419
Expr * expr
Definition: expr.h:510
static bool lDoTypeConv(const Type *fromType, const Type *toType, Expr **expr, bool failureOk, const char *errorMsgBase, SourcePos pos)
Definition: expr.cpp:175
const Type * GetType() const
Definition: expr.cpp:4933
Expr * Optimize()
Definition: expr.cpp:6973
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:2886
std::pair< llvm::Constant *, bool > GetStorageConstant(const Type *type) const
Definition: expr.cpp:5946
static llvm::Constant * lLLVMConstantValue(const Type *type, llvm::LLVMContext *ctx, double value)
Definition: expr.cpp:794
static llvm::Type * Int16Type
Definition: llvmutil.h:66
void Print() const
Definition: expr.cpp:7544
VectorMemberExpr(Expr *e, const char *id, SourcePos p, SourcePos idpos, bool derefLValue)
Definition: expr.cpp:4646
ExprList * args
Definition: expr.h:289
const StructType * GetAsVaryingType() const
Definition: type.cpp:1672
static bool lCheckForConstStructMember(SourcePos pos, const StructType *structType, const StructType *initialType)
Definition: expr.cpp:2951
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4233
virtual void Print() const =0
static llvm::Value * lEmitNegate(Expr *arg, SourcePos pos, FunctionEmitContext *ctx)
Definition: expr.cpp:1009
const Type * GetType() const
Definition: expr.cpp:4663
Expr * arg0
Definition: expr.h:184
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7171
AssignExpr(Op o, Expr *a, Expr *b, SourcePos p)
Definition: expr.cpp:2881
llvm::BasicBlock * GetCurrentBasicBlock()
Definition: ctx.cpp:359
static const AtomicType * UniformUInt16
Definition: type.h:327
std::vector< std::string > MatchStrings(const std::string &str, const std::vector< std::string > &options)
Definition: util.cpp:490
static PointerType * GetUniform(const Type *t, bool isSlice=false)
Definition: type.cpp:799
FunctionCallExpr(Expr *func, ExprList *args, SourcePos p, bool isLaunch=false, Expr *launchCountExpr[3]=NULL)
Definition: expr.cpp:3417
virtual llvm::Value * GetValue(FunctionEmitContext *ctx) const =0
bool boolVal[ISPC_MAX_NVEC]
Definition: expr.h:481
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4689
Pre-increment.
Definition: expr.h:114
ConstExpr * constValue
Definition: sym.h:85
static llvm::VectorType * Int1VectorType
Definition: llvmutil.h:83
const VectorType * memberType
Definition: expr.cpp:4643
llvm::Value * CallInst(llvm::Value *func, const FunctionType *funcType, const std::vector< llvm::Value *> &args, const char *name=NULL)
Definition: ctx.cpp:2975
llvm::BasicBlock * CreateBasicBlock(const char *name)
Definition: ctx.cpp:1228
Expr * expr
Definition: expr.h:552
const Type * GetLValueType() const
Definition: expr.cpp:7184
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7597
std::pair< llvm::Constant *, bool > GetStorageConstant(const Type *type) const
Definition: expr.cpp:3929
Modulus.
Definition: expr.h:147
virtual llvm::Type * LLVMType(llvm::LLVMContext *ctx) const =0
header file with declarations for symbol and symbol table classes.
void Print() const
Definition: expr.cpp:7686
static const AtomicType * UniformBool
Definition: type.h:322
Expr * test
Definition: expr.h:240
std::string identifier
Definition: expr.h:352
llvm::Value * BroadcastValue(llvm::Value *v, llvm::Type *vecType, const char *name=NULL)
Definition: ctx.cpp:2893
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:8075
#define PRIu64
Definition: opt.cpp:113
int costOverride
Definition: type.h:903
Type representing a reference to another (non-reference) type.
Definition: type.h:782
Expr * expr
Definition: expr.h:136
llvm::Constant * LLVMFloatVector(float fval)
Definition: llvmutil.cpp:343
virtual const Type * GetReferenceTarget() const
Definition: type.cpp:2564
uint8_t uint8Val[ISPC_MAX_NVEC]
Definition: expr.h:476
bool disableMaskAllOnOptimizations
Definition: ispc.h:431
RefDerefExpr(Expr *e, SourcePos p)
Definition: expr.cpp:7334
Binary expression.
Definition: expr.h:140
const Type * lvalueType
Definition: expr.h:364
std::string GetString() const
Definition: type.cpp:2170
bool isVarying
Definition: expr.h:772
llvm::Module * module
Definition: module.h:151
virtual llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:73
static bool IsVoidPointer(const Type *t)
Definition: type.cpp:807
Expr * GetParameterDefault(int i) const
Definition: type.cpp:2546
llvm::Constant * LLVMDoubleVector(double dval)
Definition: llvmutil.cpp:358
void StoreInst(llvm::Value *value, llvm::Value *ptr, const Type *ptrType=NULL)
Definition: ctx.cpp:2674
static bool lIsAllIntZeros(Expr *expr)
Definition: expr.cpp:154
Expr * TypeCheck()
Definition: expr.cpp:7680
void PerformanceWarning(SourcePos p, const char *fmt,...)
Definition: util.cpp:397
Expression representing a type cast of the given expression to a probably-different type...
Definition: expr.h:491
static const AtomicType * UniformUInt64
Definition: type.h:331
int EstimateCost() const
Definition: expr.cpp:7684
uint32_t uint32Val[ISPC_MAX_NVEC]
Definition: expr.h:480
Expr * TypeCheck()
Definition: expr.cpp:7347
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7678
Expr * Optimize()
Definition: expr.cpp:7458
static llvm::VectorType * Int8VectorType
Definition: llvmutil.h:84
const Type * GetType() const
Definition: expr.cpp:1057
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:8125
Multiplication.
Definition: expr.h:145
llvm::Constant * LLVMInt32Vector(int32_t ival)
Definition: llvmutil.cpp:313
Shift left.
Definition: expr.h:148
bool IsSlice() const
Definition: type.h:439
void Print() const
Definition: expr.cpp:4442
Abstract base class for nodes in the abstract syntax tree (AST).
Definition: ast.h:49
llvm::Value * GetElementPtrInst(llvm::Value *basePtr, llvm::Value *index, const Type *ptrType, const char *name=NULL)
Definition: ctx.cpp:1825
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7140
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7607
SizeOfExpr(Expr *e, SourcePos p)
Definition: expr.cpp:7520
Symbol * GetBaseSymbol() const
Definition: expr.cpp:4164
virtual int GetElementCount() const =0
const Type * GetType() const
Definition: expr.cpp:1936
Expr * func
Definition: expr.h:288
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:7694
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:6851
bool LookupFunction(const char *name, std::vector< Symbol *> *matches=NULL)
Definition: sym.cpp:139
Expr * Optimize()
Definition: expr.cpp:8060
float floatVal[ISPC_MAX_NVEC]
Definition: expr.h:482
int EstimateCost() const
Definition: expr.cpp:3936
static int computeOverloadCost(const FunctionType *ftype, const std::vector< const Type *> &argTypes, const std::vector< bool > *argCouldBeNULL, const std::vector< bool > *argIsConstant, int *cost)
Definition: expr.cpp:7817
llvm::Constant * LLVMTrue
Definition: llvmutil.cpp:90
int EstimateCost() const
Definition: expr.cpp:7207
unsigned getValueID() const
Definition: ast.h:133
static llvm::Value * lEmitBinaryCmp(BinaryExpr::Op op, llvm::Value *e0Val, llvm::Value *e1Val, const Type *type, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:1523
static llvm::VectorType * FloatVectorType
Definition: llvmutil.h:88
const Type * GetReferenceTarget() const
Definition: type.cpp:2087
Expr * arg1
Definition: expr.h:184
Expr * TypeCheck()
Definition: expr.cpp:5955
static bool lCanImproveVectorDivide(Expr *arg0, Expr *arg1, int *divisor)
Definition: expr.cpp:2163
virtual bool IsBoolType() const =0
static ConstExpr * lConstFoldBinaryIntOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0, SourcePos pos)
Definition: expr.cpp:2032
static bool lVaryingStructHasUniformMember(const Type *type, SourcePos pos)
Definition: expr.cpp:4011
Expr * expr
Definition: expr.h:603
virtual const Type * GetLValueType() const
Definition: expr.cpp:78
static llvm::Type * Int64Type
Definition: llvmutil.h:68
static llvm::Type * Int8Type
Definition: llvmutil.h:65
static const Type * MoreGeneralType(const Type *type0, const Type *type1, SourcePos pos, const char *reason, bool forceVarying=false, int vecSize=0)
Definition: type.cpp:2602
void MemcpyInst(llvm::Value *dest, llvm::Value *src, llvm::Value *count, llvm::Value *align=NULL)
Definition: ctx.cpp:2777
llvm::PHINode * PhiNode(llvm::Type *type, int count, const char *name=NULL)
Definition: ctx.cpp:2934
int EstimateCost() const
Definition: expr.cpp:3730
Representation of a structure holding a number of members.
Definition: type.h:650
void InitSymbol(llvm::Value *ptr, const Type *symType, Expr *initExpr, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:594
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:7572
int GetValues(bool *, bool forceVarying=false) const
Definition: expr.cpp:5535
static bool lIsDifficultShiftAmount(Expr *expr)
Definition: expr.cpp:1857
Expr * Optimize()
Definition: expr.cpp:5953
static llvm::VectorType * Int64VectorType
Definition: llvmutil.h:87
Header file with declarations for various LLVM utility stuff.
virtual bool IsFloatType() const =0
void Print() const
Definition: expr.cpp:7646
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7384
const std::string & GetElementName(int i) const
Definition: type.h:696
const Type * GetLValueType() const
Definition: expr.cpp:7417
void MatchIntegerTypes(llvm::Value **v0, llvm::Value **v1)
Definition: ctx.cpp:1746
const Type * GetBaseType() const
Definition: type.cpp:1108
static llvm::Value * lConvertPtrToSliceIfNeeded(FunctionEmitContext *ctx, llvm::Value *ptr, const Type **type)
Definition: expr.cpp:4221
bool IsGenericTypeLayoutIndeterminate(llvm::Type *type)
Definition: ispc.cpp:1352
static bool IsBasicType(const Type *type)
Definition: type.cpp:2762
Expr * TypeCheck()
Definition: expr.cpp:2976
int EstimateCost() const
Definition: expr.cpp:3398
llvm::ConstantInt * LLVMUInt64(uint64_t ival)
Definition: llvmutil.cpp:245
virtual const Type * GetType() const =0
Expr * Optimize()
Definition: expr.cpp:7195
Expr * TypeCheck()
Definition: expr.cpp:3349
llvm::Constant * LLVMBoolVectorInStorage(bool b)
Definition: llvmutil.cpp:446
const Op op
Definition: expr.h:217
%= assignment
Definition: expr.h:194
Expr * TypeCheck()
Definition: expr.cpp:4966
Expr * expr
Definition: expr.h:531
const Type * GetType() const
Definition: expr.cpp:7665
AtomicType represents basic types like floats, ints, etc.
Definition: type.h:270
Expr * Optimize()
Definition: expr.cpp:8073
int getElementNumber() const
Definition: expr.cpp:4580
static void lEmitSelectExprCode(FunctionEmitContext *ctx, llvm::Value *testVal, llvm::Value *oldMask, llvm::Value *fullMask, Expr *expr, llvm::Value *exprPtr)
Definition: expr.cpp:3105
static bool classof(ASTNode const *N)
Definition: expr.cpp:4489
int EstimateCost() const
Definition: expr.cpp:8302
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4890
static void lConvert(const From *from, To *to, int count, bool forceVarying)
Definition: expr.cpp:5362
Expr * index
Definition: expr.h:317
AddressOfExpr(Expr *e, SourcePos p)
Definition: expr.cpp:7382
Logical not.
Definition: expr.h:119
llvm::Constant * LLVMMaskAllOff
Definition: llvmutil.cpp:95
StorageClass storageClass
Definition: sym.h:94
Expr * lvalue
Definition: expr.h:218
Representation of a range of positions in a source file.
Definition: ispc.h:123
void Print() const
Definition: expr.cpp:7430
Expression representing a function symbol in the program (generally used for a function call)...
Definition: expr.h:655
bool disableUniformMemoryOptimizations
Definition: ispc.h:483
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4736
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:8065
uint64_t uint64Val[ISPC_MAX_NVEC]
Definition: expr.h:485
Expr * Optimize()
Definition: expr.cpp:1100
bool fastMath
Definition: ispc.h:396
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:3446
llvm::ConstantInt * LLVMInt32(int32_t ival)
Definition: llvmutil.cpp:233
bool CanConvertTypes(const Type *fromType, const Type *toType, const char *errorMsgBase, SourcePos pos)
Definition: expr.cpp:544
Post-decrement.
Definition: expr.h:117
Type implementation for enumerated types.
Definition: type.h:347
virtual const Type * GetAsNonConstType() const =0
const Type * GetType() const
Definition: expr.cpp:8043
Expr * TypeCheck()
Definition: expr.cpp:3604
static const AtomicType * VaryingBool
Definition: type.h:322
virtual std::string GetString() const =0
Expr * lCreateBinaryOperatorCall(const BinaryExpr::Op bop, Expr *a0, Expr *a1, const SourcePos &sp)
Definition: expr.cpp:1576
Abstract base class for types that represent collections of other types.
Definition: type.h:478
ExprList * TypeCheck()
Definition: expr.cpp:3779
void Print() const
Definition: ispc.cpp:1514
+= assignment
Definition: expr.h:195
bool force32BitAddressing
Definition: ispc.h:412
static ConstExpr * lConstFoldBinaryLogicalOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0)
Definition: expr.cpp:2053
bool IsIntType() const
Definition: type.cpp:817
static Expr * lOptimizeBitNot(ConstExpr *constExpr, const Type *type, SourcePos pos)
Definition: expr.cpp:1084
FunctionSymbolExpr(const char *name, const std::vector< Symbol *> &candFuncs, SourcePos pos)
Definition: expr.cpp:7657
int GetElementCount() const
Definition: type.h:699
int getElementNumber() const
Definition: expr.cpp:4802
static Expr * lArrayToPointer(Expr *expr)
Definition: expr.cpp:140
llvm::Instruction * SExtInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1655
Expr * TypeCheck()
Definition: expr.cpp:7628
const Op op
Definition: expr.h:183
std::vector< Symbol * > candidateFunctions
Definition: expr.h:700
Post-increment.
Definition: expr.h:116
llvm::Constant * LLVMUInt8Vector(uint8_t ival)
Definition: llvmutil.cpp:268
SourcePos pos
Definition: ast.h:76
Expr * Optimize()
Definition: expr.cpp:8298
static std::pair< llvm::Constant *, bool > lGetBinaryExprStorageConstant(const Type *type, const BinaryExpr *bExpr, bool isStorageType)
Definition: expr.cpp:2665
const BasicType basicType
Definition: type.h:320
Not equal.
Definition: expr.h:156
int64_t int64Val[ISPC_MAX_NVEC]
Definition: expr.h:484
int EstimateCost() const
Definition: expr.cpp:5957
static llvm::Type * PointerIntType
Definition: llvmutil.h:61
bool IsVoidType() const
Definition: type.cpp:167
const Type * type
Definition: expr.h:473
static llvm::PointerType * VoidPointerType
Definition: llvmutil.h:60
static const AtomicType * VaryingInt64
Definition: type.h:330
llvm::Constant * LLVMFloat(float fval)
Definition: llvmutil.cpp:249
void Error(SourcePos p, const char *fmt,...)
Definition: util.cpp:351
UnaryExpr(Op op, Expr *expr, SourcePos pos)
Definition: expr.cpp:1027
int getVectorWidth() const
Definition: ispc.h:245
const StructType * getStructType() const
Definition: expr.cpp:4603
const PointerType * GetAsSlice() const
Definition: type.cpp:853
Bitwise XOR.
Definition: expr.h:159
bool IsPointerType() const
Definition: type.cpp:161
#define FATAL(message)
Definition: util.h:116
llvm::Constant * LLVMDouble(double dval)
Definition: llvmutil.cpp:251
void Print() const
Definition: expr.cpp:3068
Expr * TypeCheck()
Definition: expr.cpp:8071
const AtomicType * GetElementType() const
Definition: type.cpp:1418
static const Type * lDeconstifyType(const Type *t)
Definition: expr.cpp:6887
int EstimateCost() const
Definition: expr.cpp:7640
Expr * Optimize()
Definition: expr.cpp:2941
void Print() const
Definition: expr.cpp:8300
A (short) vector of atomic types.
Definition: type.h:600
llvm::Value * InsertInst(llvm::Value *v, llvm::Value *eltVal, int elt, const char *name=NULL)
Definition: ctx.cpp:2854
Bit not.
Definition: expr.h:120
static llvm::Value * lEmitBinaryArith(BinaryExpr::Op op, llvm::Value *value0, llvm::Value *value1, const Type *type0, const Type *type1, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:1468
Expr * launchCountExpr[3]
Definition: expr.h:291
static llvm::Value * lEmitBinaryPointerArith(BinaryExpr::Op op, llvm::Value *value0, llvm::Value *value1, const Type *type0, const Type *type1, FunctionEmitContext *ctx, SourcePos pos)
Definition: expr.cpp:1387
static const Type * lMatchingBoolType(const Type *type)
Definition: expr.cpp:779
static const AtomicType * UniformUInt8
Definition: type.h:326
const Type * GetElementType(const std::string &name) const
Definition: type.cpp:1881
static llvm::Type * Int32Type
Definition: llvmutil.h:67
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:3767
const llvm::DataLayout * getDataLayout() const
Definition: ispc.h:224
void SetDebugPos(SourcePos pos)
Definition: ctx.cpp:1288
virtual const Type * GetAsUniformType() const =0
std::vector< Symbol * > getCandidateFunctions(int argCount) const
Definition: expr.cpp:7779
#define PTYPE(p)
Definition: llvmutil.h:47
llvm::Value * GetLValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:3548
#define ISPC_MAX_NVEC
Definition: ispc.h:69
static llvm::Value * lEmitOpAssign(AssignExpr::Op op, Expr *arg0, Expr *arg1, const Type *type, Symbol *baseSym, SourcePos pos, FunctionEmitContext *ctx)
Definition: expr.cpp:2792
bool ResolveOverloads(SourcePos argPos, const std::vector< const Type *> &argTypes, const std::vector< bool > *argCouldBeNULL=NULL, const std::vector< bool > *argIsConstant=NULL)
Definition: expr.cpp:7939
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:6567
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:4062
bool disableMaskedStoreToStore
Definition: ispc.h:471
static bool classof(StructMemberExpr const *)
Definition: expr.cpp:4488
#define Assert(expr)
Definition: util.h:128
virtual const Type * GetElementType() const =0
static bool Equal(const Type *a, const Type *b)
Definition: type.cpp:2853
static const AtomicType * VaryingUInt16
Definition: type.h:327
const Type * allocType
Definition: expr.h:760
Expression representing member selection ("foo.bar").
Definition: expr.h:328
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:7224
const bool isTask
Definition: type.h:882
#define TYPEQUAL_VARYING
Definition: decl.h:70
Pre-decrement.
Definition: expr.h:115
std::vector< Expr * > exprs
Definition: expr.h:266
const Type * getElementType() const
Definition: expr.cpp:4593
#define TYPEQUAL_UNIFORM
Definition: decl.h:69
static std::pair< llvm::Constant *, bool > lGetExprListConstant(const Type *type, const ExprList *eList, bool isStorageType)
Definition: expr.cpp:3781
static bool lArgIsPointerType(const Type *type)
Definition: expr.cpp:7800
static const AtomicType * UniformFloat
Definition: type.h:329
static const AtomicType * VaryingInt8
Definition: type.h:323
const PointerType * GetAsFrozenSlice() const
Definition: type.cpp:865
llvm::Value * GetInternalMask()
Definition: ctx.cpp:365
ISA getISA() const
Definition: ispc.h:231
Expr * TypeCheck()
Definition: expr.cpp:7286
int EstimateCost() const
Definition: expr.cpp:7056
virtual bool IsUnsignedType() const =0
BasicType
Definition: type.h:304
const Type * GetParameterType(int i) const
Definition: type.cpp:2541
llvm::Value * BitCastInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1518
>>= assignment
Definition: expr.h:198
static const AtomicType * UniformInt32
Definition: type.h:325
void SetInternalMaskAndNot(llvm::Value *oldMask, llvm::Value *test)
Definition: ctx.cpp:392
static llvm::Value * lConvertToSlicePointer(FunctionEmitContext *ctx, llvm::Value *ptr, const PointerType *slicePtrType)
Definition: expr.cpp:4169
Expr * rvalue
Definition: expr.h:218
llvm::Constant * LLVMFalse
Definition: llvmutil.cpp:91
Expression representing indexing into something with an integer offset.
Definition: expr.h:299
static MemberExpr * create(Expr *expr, const char *identifier, SourcePos pos, SourcePos identifierPos, bool derefLvalue)
Definition: expr.cpp:4811
static Expr * lOptimizeNegate(ConstExpr *constExpr, const Type *type, SourcePos pos)
Definition: expr.cpp:1092
Type representing a function (return type + argument types)
Definition: type.h:829
Representation of a program symbol.
Definition: sym.h:62
<<= assignment
Definition: expr.h:197
llvm::Value * ExtractInst(llvm::Value *v, int elt, const char *name=NULL)
Definition: ctx.cpp:2834
const PointerType * GetAsNonSlice() const
Definition: type.cpp:859
bool isLaunch
Definition: expr.h:290
Expr * expr2
Definition: expr.h:240
int varyingCFDepth
Definition: sym.h:96
static std::pair< llvm::Constant *, bool > lGetConstExprConstant(const Type *constType, const ConstExpr *cExpr, bool isStorageType)
Definition: expr.cpp:5824
static llvm::Value * lEmitBinaryBitOp(BinaryExpr::Op op, llvm::Value *arg0Val, llvm::Value *arg1Val, bool isUnsigned, FunctionEmitContext *ctx)
Definition: expr.cpp:1357
virtual bool IsConstType() const =0
Interface class that defines the type abstraction.
Definition: type.h:90
static const AtomicType * UniformDouble
Definition: type.h:332
Globals * g
Definition: ispc.cpp:72
virtual Variability GetVariability() const =0
llvm::Constant * LLVMInt16Vector(int16_t ival)
Definition: llvmutil.cpp:283
Expr abstract base class and expression implementations.
Expr * Optimize()
Definition: expr.cpp:3281
static const AtomicType * Void
Definition: type.h:333
void SetCurrentBasicBlock(llvm::BasicBlock *bblock)
Definition: ctx.cpp:361
const VectorType * exprVectorType
Definition: expr.cpp:4642
virtual const Type * GetAsConstType() const =0
static llvm::VectorType * MaskType
Definition: llvmutil.h:79
llvm::Instruction * SelectInst(llvm::Value *test, llvm::Value *val0, llvm::Value *val1, const char *name=NULL)
Definition: ctx.cpp:2940
Regular assignment.
Definition: expr.h:191
void Print() const
Definition: expr.cpp:7209
Expr * Optimize()
Definition: expr.cpp:4355
void Debug(SourcePos p, const char *fmt,...)
Definition: util.cpp:366
llvm::Type * LLVMType(llvm::LLVMContext *ctx) const
Definition: type.cpp:983
Addition.
Definition: expr.h:143
llvm::ConstantInt * LLVMUInt16(uint16_t ival)
Definition: llvmutil.cpp:229
Less than or equal.
Definition: expr.h:153
&= assignment
Definition: expr.h:199
Expr * TypeCheck()
Definition: expr.cpp:1197
void Print() const
Definition: expr.cpp:3938
const Type * GetLValueType() const
Definition: expr.cpp:6878
ExprList * Optimize()
Definition: expr.cpp:3777
int GetElementCount() const
Definition: type.cpp:1183
Expr * Optimize()
Definition: expr.cpp:3598
const Type * GetType() const
Definition: expr.cpp:8069
Expr is the abstract base class that defines the interface that all expression types must implement...
Definition: expr.h:47
llvm::Value * IntToPtrInst(llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1578
const Function * parentFunction
Definition: sym.h:102
static llvm::VectorType * DoubleVectorType
Definition: llvmutil.h:89
const Type * GetType() const
Definition: expr.cpp:3772
double doubleVal[ISPC_MAX_NVEC]
Definition: expr.h:483
MemberExpr(Expr *expr, const char *identifier, SourcePos pos, SourcePos identifierPos, bool derefLValue, unsigned scid)
Definition: expr.cpp:4882
Expr * TypeCheck()
Definition: expr.cpp:8058
static bool classof(VectorMemberExpr const *)
Definition: expr.cpp:4630
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7071
llvm::Value * All(llvm::Value *mask)
Definition: ctx.cpp:1138
llvm::Constant * LLVMInt8Vector(int8_t ival)
Definition: llvmutil.cpp:253
-= assignment
Definition: expr.h:196
ASTNode * Optimize(ASTNode *root)
Definition: ast.cpp:234
Expr * expr
Definition: expr.h:626
llvm::Constant * LLVMUInt16Vector(uint16_t ival)
Definition: llvmutil.cpp:298
Subtraction.
Definition: expr.h:144
llvm::ConstantInt * LLVMInt64(int64_t ival)
Definition: llvmutil.cpp:241
ConstExpr(const Type *t, int8_t i, SourcePos p)
Definition: expr.cpp:5017
Expression that represents dereferencing a reference to get its value.
Definition: expr.h:572
IndexExpr(Expr *baseExpr, Expr *index, SourcePos p)
Definition: expr.cpp:3951
const Type * type
Definition: expr.h:509
const Type * GetType() const
Definition: expr.cpp:7626
virtual const Type * GetBaseType() const =0
llvm::Value * SmearUniform(llvm::Value *value, const char *name=NULL)
Definition: ctx.cpp:1481
const Type * getElementType() const
Definition: expr.cpp:4809
static llvm::Value * lUniformValueToVarying(FunctionEmitContext *ctx, llvm::Value *value, const Type *type, SourcePos pos)
Definition: expr.cpp:6518
static llvm::VectorType * Int16VectorType
Definition: llvmutil.h:85
Shift right.
Definition: expr.h:149
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:2753
virtual Symbol * GetBaseSymbol() const
Definition: expr.cpp:90
Greater than or equal.
Definition: expr.h:154
const Type * GetType() const
Definition: expr.cpp:7396
*= assignment
Definition: expr.h:192
Variability GetVariability() const
Definition: type.cpp:811
Definition: ispc.h:653
Equal.
Definition: expr.h:155
#define PRId64
Definition: opt.cpp:110
static llvm::Value * lMaskForSymbol(Symbol *baseSym, FunctionEmitContext *ctx)
Definition: expr.cpp:902
int32_t int32Val[ISPC_MAX_NVEC]
Definition: expr.h:479
static Expr * lConstFoldBinaryFPOp(ConstExpr *constArg0, ConstExpr *constArg1, BinaryExpr::Op op, BinaryExpr *origExpr, SourcePos pos)
Definition: expr.cpp:2128
static const AtomicType * VaryingUInt8
Definition: type.h:326
bool is32Bit() const
Definition: ispc.h:235
const Type * GetBaseType() const
Definition: type.cpp:823
int GetElementCount() const
Definition: type.cpp:1416
std::pair< llvm::Constant *, bool > GetConstant(const Type *type) const
Definition: expr.cpp:7095
const Type * GetLValueType() const
Definition: expr.cpp:4548
bool IsIntType() const
Definition: type.cpp:171
int EstimateCost() const
Definition: expr.cpp:8094
Declaration of the Module class, which is the ispc-side representation of the results of compiling a ...
int EstimateCost() const
Definition: expr.cpp:4426
static const AtomicType * UniformInt64
Definition: type.h:330
int errorCount
Definition: module.h:144
Symbol * GetBaseSymbol() const
Definition: expr.cpp:7624
bool dereferenceExpr
Definition: expr.h:361
llvm::LLVMContext * ctx
Definition: ispc.h:611
static const AtomicType * UniformInt16
Definition: type.h:324
static llvm::Value * lAddVaryingOffsetsIfNeeded(FunctionEmitContext *ctx, llvm::Value *ptr, const Type *ptrRefType)
Definition: expr.cpp:3977
static const FunctionType * lGetFunctionType(Expr *func)
Definition: expr.cpp:3429
const Type * type
Definition: sym.h:82
const Type * GetType() const
Definition: expr.cpp:4503
uint16_t uint16Val[ISPC_MAX_NVEC]
Definition: expr.h:478
Expr * TypeCheck()
Definition: expr.cpp:7201
Expr * lConstFoldSelect(const bool bv[], ConstExpr *constExpr1, ConstExpr *constExpr2, const Type *exprType, SourcePos pos)
Definition: expr.cpp:3270
void Print() const
Definition: expr.cpp:1279
std::string GetString() const
Definition: type.cpp:2334
void Warning(SourcePos p, const char *fmt,...)
Definition: util.cpp:378
static llvm::Value * lEmitVaryingSelect(FunctionEmitContext *ctx, llvm::Value *test, llvm::Value *expr1, llvm::Value *expr2, const Type *type)
Definition: expr.cpp:3092
static bool EqualIgnoringConst(const Type *a, const Type *b)
Definition: type.cpp:2855
static ConstExpr * lConstFoldBinaryArithOp(BinaryExpr::Op op, const T *v0, const T *v1, ConstExpr *carg0, SourcePos pos)
Definition: expr.cpp:2077
const Type * GetType() const
Definition: expr.cpp:2947
Expr * expr1
Definition: expr.h:240
llvm::Instruction * CastInst(llvm::Instruction::CastOps op, llvm::Value *value, llvm::Type *type, const char *name=NULL)
Definition: ctx.cpp:1622
int EstimateCost() const
Definition: expr.cpp:2646
virtual Expr * TypeCheck()=0
Expr * Optimize()
Definition: expr.cpp:7568
bool IsNumericType() const
Definition: type.h:128
#define FOLD_OP_REF(O, E, TRef)
Definition: expr.cpp:2017
const Type * GetType() const
Definition: expr.cpp:7336
const SourcePos identifierPos
Definition: expr.h:353
void Print() const
Definition: expr.cpp:8053
^= assignment
Definition: expr.h:200
llvm::Value * GetValue(FunctionEmitContext *ctx) const
Definition: expr.cpp:3126
Expr * initExpr
Definition: expr.h:767
static const AtomicType * VaryingUInt32
Definition: type.h:328
llvm::Value * BinaryOperator(llvm::Instruction::BinaryOps inst, llvm::Value *v0, llvm::Value *v1, const char *name=NULL)
Definition: ctx.cpp:1383
Expr * TypeCheck()
Definition: expr.cpp:4361
int EstimateCost() const
Definition: expr.cpp:7570
void Print() const
Definition: expr.cpp:3400
Logical OR.
Definition: expr.h:162
int EstimateCost() const
Definition: expr.cpp:7362
static const AtomicType * VaryingFloat
Definition: type.h:329
virtual llvm::Type * LLVMStorageType(llvm::LLVMContext *ctx) const
Definition: type.cpp:125
Expression representing a function call.
Definition: expr.h:271
SymbolTable * symbolTable
Definition: module.h:148
static const AtomicType * UniformInt8
Definition: type.h:323
bool HasUnboundVariability() const
Definition: type.h:149
File with declarations for classes related to type representation.
Bitwise AND.
Definition: expr.h:158
llvm::Value * I1VecToBoolVec(llvm::Value *b)
Definition: ctx.cpp:1232
const Type * GetLValueType() const
Definition: expr.cpp:3587
NewExpr(int typeQual, const Type *type, Expr *initializer, Expr *count, SourcePos tqPos, SourcePos p)
Definition: expr.cpp:8099
static llvm::Constant * lConvertPointerConstant(llvm::Constant *c, const Type *constType)
Definition: expr.cpp:7073
llvm::Constant * LLVMTrueInStorage
Definition: llvmutil.cpp:92
virtual const Type * GetElementType(int index) const =0
One-dimensional array type.
Definition: type.h:521