Skip to content

Commit

Permalink
Add a type cast in printGEPExpression (#204)
Browse files Browse the repository at this point in the history
May fix #193 and may fix #203.
  • Loading branch information
swiszczoo authored Sep 30, 2024
1 parent 423df47 commit 0b887f8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
17 changes: 13 additions & 4 deletions lib/Target/CBackend/CBackend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5366,7 +5366,8 @@ void CWriter::visitAllocaInst(AllocaInst &I) {
}

void CWriter::printGEPExpression(Value *Ptr, unsigned NumOperands,
gep_type_iterator I, gep_type_iterator E) {
gep_type_iterator I, gep_type_iterator E,
std::optional<Type *> SourceType) {

// If there are no indices, just print out the pointer.
if (I == E) {
Expand Down Expand Up @@ -5397,9 +5398,16 @@ void CWriter::printGEPExpression(Value *Ptr, unsigned NumOperands,
Out << "])";
} else {
// When the first index is 0 (very common) we can simplify it.
if (tryGetTypeOfAddressExposedValue(Ptr)) {
std::optional<Type *> ExposedType = tryGetTypeOfAddressExposedValue(Ptr);
if (ExposedType) {
// Print P rather than (&P)[0]
Out << "(&";
Out << '(';
if (SourceType && SourceType.value() != ExposedType.value()) {
Out << "(";
printTypeName(Out, SourceType.value());
Out << "*)";
}
Out << '&';
writeOperandInternal(Ptr);
Out << ')';
} else if (I != E && I.isStruct()) {
Expand Down Expand Up @@ -5586,7 +5594,8 @@ void CWriter::visitGetElementPtrInst(GetElementPtrInst &I) {
cwriter_assert(++FirstOp == gep_type_end(I));
} else {
printGEPExpression(I.getPointerOperand(), I.getNumOperands(),
gep_type_begin(I), gep_type_end(I));
gep_type_begin(I), gep_type_end(I),
std::optional(I.getSourceElementType()));
}
}

Expand Down
3 changes: 2 additions & 1 deletion lib/Target/CBackend/CBackend.h
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,8 @@ class CWriter : public FunctionPass, public InstVisitor<CWriter> {
void printBranchToBlock(BasicBlock *CurBlock, BasicBlock *SuccBlock,
unsigned Indent);
void printGEPExpression(Value *Ptr, unsigned NumOperands, gep_type_iterator I,
gep_type_iterator E);
gep_type_iterator E,
std::optional<Type *> SourceType = std::nullopt);

std::string GetValueName(const Value *Operand);

Expand Down

0 comments on commit 0b887f8

Please sign in to comment.