================
@@ -2081,6 +2081,57 @@ void CGDebugInfo::CollectRecordLambdaFields(
   }
 }
 
+/// Try to create an llvm::Constant for a constexpr array of integer elements.
+/// Handles arrays of char, short, int, long with element width up to 64 bits.
+/// Returns nullptr if the array cannot be represented.
+static llvm::Constant *tryEmitConstexprArrayAsConstant(CodeGenModule &CGM,
+                                                       const VarDecl *Var,
+                                                       const APValue *Value) {
+  const auto *ArrayTy = 
CGM.getContext().getAsConstantArrayType(Var->getType());
+  if (!ArrayTy)
+    return nullptr;
+
+  const QualType ElemQTy = ArrayTy->getElementType();
+  if (ElemQTy.isNull() || !ElemQTy->isIntegerType())
+    return nullptr;
+
+  const unsigned ElemBitWidth = CGM.getContext().getTypeSize(ElemQTy);
+  // ConstantDataArray only supports 8/16/32/64-bit elements, and
+  // getZExtValue() asserts on wider types (e.g. __int128).
+  if (ElemBitWidth > 64)
+    return nullptr;
+
+  const unsigned NumElts = Value->getArraySize();
+  const unsigned NumInits = Value->getArrayInitializedElts();
+
+  // Preallocate with filler value, then overwrite initialized elements.
+  uint64_t FillVal = 0;
+  if (Value->hasArrayFiller()) {
+    const APValue &Filler = Value->getArrayFiller();
+    FillVal = Filler.getInt().getZExtValue();
+  }
+
+  SmallVector<uint64_t, 64> Vals(NumElts, FillVal);
+  for (unsigned I = 0; I < NumInits; ++I) {
+    const APValue &Elt = Value->getArrayInitializedElt(I);
+    Vals[I] = Elt.getInt().getZExtValue();
+  }
+
+  if (ElemBitWidth == 8) {
+    SmallVector<uint8_t, 64> Bytes(Vals.begin(), Vals.end());
----------------
dzhidzhoev wrote:

Can we avoid extra array copying (from Vals to Bytes) without making the code 
overcomplicated? Maybe using something like
```c++
template <typename T, unsigned N>
static llvm::Constant *toConstantDataArray(llvm::LLVMContext &Ctx,
                                           const APValue &Arr) {
  SmallVector<T, N> Vals(
      Arr.getArraySize(),
      Arr.hasArrayFiller()
          ? static_cast<T>(Arr.getArrayFiller().getInt().getZExtValue())
          : 0);
  for (unsigned I : llvm::seq(Arr.getArrayInitializedElts()))
    Vals[I] =
        static_cast<T>(Arr.getArrayInitializedElt(I).getInt().getZExtValue());
  return llvm::ConstantDataArray::get(Ctx, Vals);
}
```

https://github.com/llvm/llvm-project/pull/182442
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to